Net Core迁移到MSBuild

Net Core迁移到MSBuild平台(二)

阅读目录

回到目录

一、前言

在上一篇文章.Net Core迁移到MSBuild的多平台编译问题中,简单的讲了下新的项目配置文件中的节点配置,这篇我将用一些例子来详细讲下从project.json迁移到msbuild过程的节点配置。做过完整迁移新项目配置文件的朋友,肯定会觉得新的项目配置文件Msbuild的配置太扯了,虽然能直接编辑项目文件,但整个配置文件中没有了像project.json中的智能提示,当你在打开文件后你就会发现以前很轻松能写出来的json配置,现在已经什么都写不出来了,而且也没有文档可以参考,一般的情况下,往往开发人员就会关掉项目文件,打开NuGet管理器来进行包引用,但是这真的够用吗?不是所有的配置都能用可视化的方法来完成。

回到目录

二、XML定义

新的.csproj是基于xml格式的,下面介绍下project.json与.csproj文件的差异定义的例子:

项目名称 (ProjectName)

{
  "name": "MyProjectName"
}

在csproj的配置中并没有对应的定义,它只会有项目文件名相同如:MyProjectName.csproj

程序集版本 (Version)

{
  "version": "1.0.0-alpha-*"
}
<PropertyGroup>
  <VersionPrefix>1.0.0</VersionPrefix>
  <VersionSuffix>alpha</VersionSuffix>
</PropertyGroup>

当然也可以只使用Version来定义:

<PropertyGroup>
  <Version>1.0.0-alpha</Version>
</PropertyGroup>

程序集描述

{
  "authors": [ "Anne", "Bob" ],
  "company": "Contoso",
  "language": "en-US",
  "title": "My library",
  "description": "This is my library.\r\nAnd it‘s really great!",
  "copyright": "Nugetizer 3000",
  "userSecretsId": "xyz123"
}
<PropertyGroup>
  <Authors>Anne;Bob<Authors>
  <Company>Contoso<Company>
  <NeutralLanguage>en-US</NeutralLanguage>
  <AssemblyTitle>My library</AssemblyTitle>
  <Description>This is my library.
And it‘s really great!</Description>
  <Copyright>Nugetizer 3000</Copyright>
  <UserSecretsId>xyz123</UserSecretsId>
</PropertyGroup>

frameworks (单目标框架)

  "frameworks": {
    "netcoreapp1.0": {}
  }
<PropertyGroup>
  <TargetFramework>netcoreapp1.0</TargetFramework>
</PropertyGroup>

frameworks (多目标框架)

 "frameworks": {
    "netcoreapp1.0": {},
    "net451": {}
  }
<PropertyGroup>
  <TargetFrameworks>netcoreapp1.0;net451</TargetFrameworks>
</PropertyGroup>

dependencies (框架依赖)

"dependencies": {
    "Microsoft.AspNetCore": "1.1.0"
  }
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.0" />
</ItemGroup>

不同目标框架的依赖 (Per-framework dependencies)

{
  "framework": {
    "net451": {
      "dependencies": {
        "System.Collections.Immutable": "1.3.1"
      }
    },
    "netstandard1.5": {
      "dependencies": {
        "Newtonsoft.Json": "9.0.1"
      }
    }
  }
}
<ItemGroup Condition="‘$(TargetFramework)‘==‘net451‘">
  <PackageReference Include="System.Collections.Immutable" Version="1.3.1" />
</ItemGroup>

<ItemGroup Condition="‘$(TargetFramework)‘==‘netstandard1.5‘">
  <PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
</ItemGroup>

imports (兼容导入)

 {
  "dependencies": {
    "xxx": "1.0-pre001"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50",
        "dotnet"
      ]
    }
  }
}
<PropertyGroup>
  <PackageTargetFallback>dnxcore50;dotnet</PackageTargetFallback>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="xxx" Version="1.0-pre001" />
</ItemGroup>

依赖类型 (dependency type)

type: build

{
  "dependencies": {
    "Microsoft.EntityFrameworkCore.Design": {
      "version": "1.1.0",
      "type": "build"
    }
  }
}
<ItemGroup>
  <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.0" PrivateAssets="All" />
</ItemGroup>

type: platform

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.1.0",
      "type": "platform"
    }
  }
}

在*.csproj项目配置文件中没有对应的配置节点,只有目标框架定义:

<TargetFramework>netcoreapp1.1</TargetFramework>

之前想要编译出独立发布的可执行文件,就需要把 "type": "platform"节点删除掉。

独立发布定义 (runtimes)

{
  "runtimes": {
    "win7-x64": {},
    "osx.10.11-x64": {},
    "ubuntu.16.04-x64": {}
  }
}
<PropertyGroup>
  <RuntimeIdentifiers>win7-x64;osx.10-11-x64;ubuntu.16.04-x64</RuntimeIdentifiers>
</PropertyGroup>

现在想生成独立发布版本,只需要在项目配置中定义RuntimeIdentifiers节点,并运行如下命令:

dotnet publish --framework netcoreapp1.0 --runtime osx.10.11-x64

DOTNET CLI工具 (tools)

{
  "tools": {
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-*"
  }
}
<ItemGroup>
  <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
</ItemGroup>

提示:tools下的引用,不再支持“imports”节点定义(不能兼容非dotnet core版本的tools)。

编译可执行 (emitEntryPoint)

{
  "buildOptions": {
    "emitEntryPoint": true
  }
}
<PropertyGroup>
  <OutputType>Exe</OutputType>
</PropertyGroup>
{
  "buildOptions": {
    "emitEntryPoint": false
  }
}
<PropertyGroup>
  <OutputType>Library</OutputType>
</PropertyGroup>

程序集强命名签名 (keyFile)

{
  "buildOptions": {
    "keyFile": "MyKey.snk"
  }
}
<PropertyGroup>
  <AssemblyOriginatorKeyFile>MyKey.snk</AssemblyOriginatorKeyFile>
  <SignAssembly>true</SignAssembly>
  <PublicSign Condition="‘$(OS)‘ != ‘Windows_NT‘">true</PublicSign>
</PropertyGroup>

其它编译设置

{
  "buildOptions": {
    "warningsAsErrors": true,
    "nowarn": ["CS0168", "CS0219"],
    "xmlDoc": true,
    "preserveCompilationContext": true,
    "outputName": "Different.AssemblyName",
    "debugType": "portable",
    "allowUnsafe": true,
    "define": ["TEST", "OTHERCONDITION"]
  }
}
<PropertyGroup>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  <NoWarn>$(NoWarn);CS0168;CS0219</NoWarn>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <PreserveCompliationContext>true</PreserveCompliationContext>
  <AssemblyName>Different.AssemblyName</AssemblyName>
  <DebugType>portable</DebugType>
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  <DefineConstants>$(DefineConstants);TEST;OTHERCONDITION</DefineConstants>
</PropertyGroup>

打包设置 (packOptions)

{
  "packOptions": {
    "summary": "A bundle of cats",
    "tags": ["hyperscale", "cats"],
    "owners": [ "Nate", "Jenna" ],
    "releaseNotes": "Version 1.0",
    "iconUrl": "https://icons.com/awesomeness.png",
    "projectUrl": "https://github.com/natemcmaster",
    "licenseUrl": "https://www.apache.org/licenses/LICENSE-2.0",
    "requireLicenseAcceptance": false,
    "repository": {
      "type": "git",
      "url": "https://github.com/natemcmaster/natemcmaster.github.io"
    }
  }
}
<PropertyGroup>
  <Description>A bundle of cats</Description>
  <PackageTags>hyperscale;cats</PackageTags>
  <PackageReleaseNotes>Version 1.0</PackageReleaseNotes>
  <PackageIconUrl>https://icons.com/awesomeness.png</PackageIconUrl>
  <PackageProjectUrl>https://github.com/natemcmaster</PackageProjectUrl>
  <PackageLicenseUrl>https://www.apache.org/licenses/LICENSE-2.0</PackageLicenseUrl>
  <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
  <RepositoryType>git</RepositoryType>
  <RepositoryUrl>https://github.com/natemcmaster/natemcmaster.github.io</RepositoryUrl>
  <!-- regrettably, ‘owners‘ does not translate to MSBuild. -->
</PropertyGroup>

MsBuild脚本

{
  "scripts": {
    "precompile": "generateCode.cmd",
    "postpublish": [ "obfuscate.cmd", "removeTempFiles.cmd" ]
  }
}
<Target Name="MyPreCompileTarget" BeforeTargets="Build">
  <Exec Command="generateCode.cmd" />
</Target>
<Target Name="MyPostCompileTarget" AfterTargets="Publish">
  <Exec Command="obfuscate.cmd" />
  <Exec Command="removeTempFiles.cmd" />
</Target>

运行时设置 (runtimeOptions)

{
  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true,
      "System.GC.Concurrent": true,
      "System.GC.RetainVM": true,
      "System.Threading.ThreadPool.MinThreads": 10,
      "System.Threading.ThreadPool.MaxThreads": 100
    }
  }
}
<PropertyGroup>
  <ServerGarbageCollection>true</ServerGarbageCollection>
  <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
  <RetainVMGarbageCollection>true</RetainVMGarbageCollection>
  <!-- I‘m not suggesting these settings...just showing usage ;) -->
  <ThreadPoolMinThreads>10</ThreadPoolMinThreads>
  <ThreadPoolMaxThreads>100</ThreadPoolMaxThreads>
</ProeprtyGroup>

当然如果你创建的是一个web项目的话,及Microsoft.NET.Sdk.Web。那么 ServerGarbageCollection设置将默认为true。

项目文件管理

{
  "buildOptions": {
    "compile": {
      "copyToOutput": "notes.txt",
      "include": "../Shared/*.cs",
      "exclude": "../Shared/Not/*.cs"
    },
    "embed": {
      "include": "../Shared/*.resx"
    }
  },
  "packOptions": {
    "include": "Views/",
    "mappings": {
      "some/path/in/project.txt": "in/package.txt"
    }
  },
  "publishOptions": {
    "include": [
      "files/",
      "publishnotes.txt"
    ]
  }
}
<ItemGroup>
  <Compile Include="..\Shared\*.cs" Exclude="..\Shared\Not\*.cs" />
  <EmbeddedResource Include="..\Shared\*.resx" />
  <Content Include="Views\**\*" PackagePath="%(Identity)" />
  <None Include="some/path/in/project.txt" Pack="true" PackagePath="in/package.txt" />

  <None Include="notes.txt" CopyToOutputDirectory="Always" />
  <!-- CopyToOutputDirectory = { Always, PreserveNewest, Never } -->

  <Content Include="files\**\*" CopyToPublishDirectory="PreserveNewest" />
  <None Include="publishnotes.txt" CopyToPublishDirectory="Always" />
  <!-- CopyToPublishDirectory = { Always, PreserveNewest, Never } -->

  <!-- you can set both copy output and publish directories-->
  <None Include="testasset.txt" CopyToOutputDirectory="Always" CopyToPublishDirectory="Always" />

  <!-- alternatively, use nested XML attributes. They‘re functionally the same-->
  <None Include="testasset2.txt">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    <CopyToPublishDirectory>Always</CopyToPublishDirectory>
  </None>

</ItemGroup>

单元测试

xunit

{
  "testRunner": "xunit",
  "dependencies": {
    "dotnet-test-xunit": "<any>"
  }
}
<ItemGroup>
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
  <PackageReference Include="xunit" Version="2.2.0" />
  <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
</ItemGroup>

mstest

{
  "testRunner": "mstest",
  "dependencies": {
    "dotnet-test-mstest": "<any>"
  }
}
<ItemGroup>
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
  <PackageReference Include="MSTest.TestAdapter" Version="1.1.12" />
  <PackageReference Include="MSTest.TestFramework" Version="1.1.11" />
</ItemGroup>

回到目录

三、结语

说实话MSBuild的项目配置系统还是比较灵活的,以后整个dotnet体系的构建过程也都得到了统一。在dotnet cli中也集成了msbuild,即dotnet build。

.NET Core 开源学习群:214741894

GitHub:https://github.com/maxzhang1985/YOYOFx 如果觉还可以请Star下, 欢迎一起交流。

时间: 2024-08-24 04:40:47

Net Core迁移到MSBuild的相关文章

.Net Core迁移到MSBuild的多平台编译问题

一.前言 本篇主要讨论.NET Core应用程序项目结构的主题,重点探索.NET Core应用程序的多平台编译问题,这里指的多平台是指.NET Framework..NET Core App..NET Standard.Mono.UWP等多平台的条件编译.项目(包)引用.编译符号等问题. .NET Core已经将新的项目管理配置过渡回MSBuild编译系统中.虽然现在可以从无到有的使用VS2017来创建一个新的MSBuild项目,但是还是有好多遗留程序使用着以JSON格式存储的项目配置文件为基础

.NET Core迁移技巧之web.config配置文件

大家都知道.NET Core现在不再支持原来的web.config配置文件了,取而代之的是json或xml配置文件.官方推荐的项目配置方式是使用appsettings.json配置文件,这对现有一些重度使用web.cofig配置的项目迁移可能是不可接受的. 但是好消息是,我们是可以直接在.NET Core 2.0项目种利用上现有的web.config的. 迁移方法 1.首先在解决方案中引入System.Configuration.ConfigurationManager,只有引入它才可以让我们已

.NET Core 迁移躺坑记续集--Win下莫名其妙的超时

继上一集里说到遇到的各种问题并且弄了n个解决方案之后,特别是对于问题4的解决方案对于切换了HttpClientFactory 我用了你家netcore 2.1下专门解决之前HttpClient口病已久的灵丹妙药了,信心满满的上线…..然后挂了,该超时的继续超 其中这个问题比较诡异在于超时的主要集中在两台机器上(俗称两兄弟了) 由于不明真相到底是什么导致的,而且接下来又要到五一了,为了欢度五一这么一个伟大艰巨的任务,为了证明迁移core的伟大光荣正确,怎么也要解决掉这个问题 步骤一,先确认问题的复

.NetCore技术研究-.NET Core迁移前的准备工作

前段时间迁移.NET Core做了大量的试水和评估,今天整理一下分享给大家.大致有以下几个部分: 1. .NET Core的由来 2. 为什么要迁移.NET Core 3. .NET Core3.X主要特性 4. .NET Standard和.NET Core 5. .NET Core Roadmap&版本选择 接下来,我们详细展开说吧. 一..NET Core的由来 这个更像是科普的资料,因为团队的小伙伴有半路出家的,对.NET 的光辉历史不是非常了解,所以有必要带着大家看一遍.NETCore

Entity Framework Core 迁移命令

Add-Migration init Update-Database init 修改model后,执行迁移的命令 更新数据库 每次更新都要{update}修改 Add-Migration {update} Update-Database {update} Remove-Migration 删除最近一次迁移.如果不能输出,把数据库的迁移表删除就没有问题 原文地址:https://www.cnblogs.com/TTonly/p/11101739.html

EF Core Model更新迁移

EF Core 迁移 感觉就是以前EF Code First的自动同步数据库功能 内容:在你新增.更新TableModel后,如何自动化的更新DB中的真实Table.以及对这些更改进行一个版本控制. 本文将以一个示例进行简单明了的演示输出.(不会很详细,只记录主要步骤) 当下我们已经有了一个ASP.NET Core的web应用程序,本文我们所关心的只有2个: 1.Model 2.DB Table 当下: Model 最后一个为导航属性,无视. Table 现在我们要在Model/Student.

[WPF]是时候将WPF控件库从.Net Framework升级到.NET Core 3.1

1. 升级到Core的好处 去年中我曾考虑将我的控件库项目Kino.Toolkit.Wpf升级到.NET Core,不过很快放弃了,因为当时.NET Core是预览版,编译WPF还需要使用最新的Visual Studio 2019,这样作为一个教学项目不够友好.到了今天.NET Core 3.1都出来了,已经正式支持WPF和Winform,Visual Studio 2019也已经普及,我觉得应该是时候将我的控件库升级到.NET Core.那么现在是WPF正式迁移到.NET Core的好时机吗?

使用Entity Framework Core需要注意的一个全表查询问题

.NET Core 迁移工作如火如荼,今天在使用 Entity Frameowork Core(又名EF Core)时写了下面这样的 LINQ 查询表达式: .Where(u => u.Id == new Guid(userId)).FirstOrDefaultAsync(); 结果在 SQL Server Profiler 中发现竟然进行了全表查询. 之后将 new Guid(userId) 从表达式中移出,保存于一个局部变量中,使用这个局部变量进行查询,全表查询问题就解决了. var use

Entity Framework Core 2.0 新特性

本文翻译来自:https://docs.microsoft.com/en-us/ef/core/what-is-new/index 一.模型级查询过滤器(Model-level query filters) ef core2.0包含了一个新特性,我们叫他模型级查询过滤器(Model-level query filters).此特性允许使用Linq查询表达式直接定义在实体类型的元数据模型上.这样的过滤器会自动应用到任何LINQ查询所涉及的那些实体类型,包括间接引用的实体类型(对象引用,导航属性).