Publish ASP.NET Core with MSBuild 15 - c#

In my company, we have some projects using .NET Framework (4.5.1) and one project using .NET Core.
Currently, all the .NET Framework projects are built with MSBuild.exe (version 12) and i would like to update the build to use MSBuild 15 so i would be able to build both .NET Framework and .NET Core projects in the same build.
Currently, the build compiles successfully when i'm building only my .NET Core project. But i wish to publish it, and the build result is not my desired outcome as it doesn't publish it correctly (the build results in the folders: bin, Properties, Views, wwwroot, and the configuration files).
I dont know what im doing wrong here, i have searched the web for a couple of days and still wasnt able to figure out what i did wrong. Please advice.
Note: to be able to build in the first place, i had to add to my .NET Core's project .csproj file the following lines so it wont fail while building:
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" Condition="true" />
The command line to execute the build
"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild" DailyBuild.proj /t:DailyBuild /p:VersionNumber=15
DailyBuild.proj
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SourcesPath>$(MSBuildProjectDirectory)\..\..\</SourcesPath>
<CSCleanProperties>BuildType=Clean;Configuration=Release;IsFormalBuild=true</CSCleanProperties>
<CSBuildProperties>BuildType=ReBuild;Configuration=Release;PauseBuildOnError=false;PublishWebSites=true;VersionName=Prod-$(VersionNumber)</CSBuildProperties>
</PropertyGroup>
<Target Name="DailyBuildWithClean">
<MSBuild Projects="$(MSBuildProjectDirectory)\Make2.proj" Targets="Clean" Properties="$(CSCleanProperties)"/>
<MSBuild Projects="$(MSBuildProjectDirectory)\Make2.proj" Properties="$(CSCleanProperties)"/>
<MSBuild Projects="$(MSBuildProjectDirectory)\Make2.proj" Targets="FormalBuild" Properties="$(CSBuildProperties)"/>
</Target>
<Target Name="DailyBuild">
<MSBuild Projects="$(MSBuildProjectDirectory)\Make2.proj" Targets="SW;PreparePackFolder" Properties="$(CSBuildProperties)"/>
</Target>
</Project>
Make2.proj
<Project DefaultTargets="SW" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" InitialTargets="CreateProperties;Clean">
<ItemGroup>
<SourcesPathItem Include='$(MSBuildProjectDirectory)\..\..\' />
</ItemGroup>
<PropertyGroup>
<MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\MSBuild.Community.Tasks.v1.4.0.88</MSBuildCommunityTasksPath>
</PropertyGroup>
<Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets" />
<PropertyGroup>
<Configuration>Debug</Configuration>
<Platform>x86</Platform>
<CSConfiguration>$(Configuration)</CSConfiguration>
<BuildType Condition=" '$(BuildType)' == '' ">Build</BuildType>
<PauseBuildOnError>true</PauseBuildOnError>
<PublishWebSites>false</PublishWebSites>
<IsFormalBuild>false</IsFormalBuild>
<VersionName>Prod</VersionName>
</PropertyGroup>
<Target Name="CreateProperties" >
<CreateProperty Value="%(SourcesPathItem.Fullpath)Src\">
<Output PropertyName="SourcesPath" TaskParameter="Value"/>
</CreateProperty>
<CreateProperty Value="%(SourcesPathItem.Fullpath)Artifacts\">
<Output PropertyName="MainArtifactsFolder" TaskParameter="Value"/>
</CreateProperty>
<CreateProperty Value="%(SourcesPathItem.Fullpath)Packages\">
<Output PropertyName="PackageFolder" TaskParameter="Value"/>
</CreateProperty>
<CreateProperty Value="%(SourcesPathItem.Fullpath)Artifacts\DeployedArtifacts\">
<Output PropertyName="DeployedPackageFolder" TaskParameter="Value"/>
</CreateProperty>
<CreateProperty Value="%(SourcesPathItem.Fullpath)Src\Util\InspectorWebService\InspectorWebService\Publish\">
<Output PropertyName="InspectorWebServicePublishPath" TaskParameter="Value"/>
</CreateProperty>
</Target>
<PropertyGroup>
<CSPlatformIndependentProjectProperties>Configuration=$(CSConfiguration);Platform=AnyCPU</CSPlatformIndependentProjectProperties>
<CSPlatformSpecificProjectProperties>Configuration=$(CSConfiguration);Platform=$(Platform)</CSPlatformSpecificProjectProperties>
<VCConfiguration>Configuration=$(CSConfiguration);Platform=Win32</VCConfiguration>
</PropertyGroup>
<Target Name="InspectorWebService">
<RemoveDir Directories="$(InspectorWebServicePublishPath)"/>
<MSBuild Projects="$(SourcesPath)Util\InspectorWebService\InspectorWebService\InspectorWebService.csproj" Targets="$(BuildType)" Properties="$(CSPlatformIndependentProjectProperties)"/>
<MSBuild Condition=" '$(BuildType)' != 'Clean' And '$(PublishWebSites)' == 'true' " Projects="$(SourcesPath)Util\InspectorWebService\InspectorWebService\InspectorWebService.csproj"
Targets="ResolveReferences;_WPPCopyWebApplication" Properties="WebProjectOutputDir=$(InspectorWebServicePublishPath);BuildingProject=true" />
</Target>
<PropertyGroup>
<AllProcessesTargets>
InspectorWebService;
</AllProcessesTargets>
</PropertyGroup>
<Target Name="SW">
<CallTarget Targets="$(AllProcessesTargets)" RunEachTargetSeparately="false"/>
<OnError ExecuteTargets="PauseBuild"/>
</Target>
<Target Name="FormalBuild">
<CallTarget Targets="SW;PreparePackFolder;Pack"/>
<OnError ExecuteTargets="ErrorHandler"/>
</Target>
<Target Name="PreparePackFolder">
<RemoveDir Directories="$(MainArtifactsFolder)" />
<MakeDir Directories="$(MainArtifactsFolder)" />
<MSBuild Projects="$(MSBuildProjectFile)" Targets="PreparePackFolderInternal" Properties="ArtifactFormat=Old;MixedArtifiactFolder=$(MainArtifactsFolder)MixedArtifacts\"/>
<MSBuild Projects="$(MSBuildProjectFile)" Targets="PreparePackFolderInternal" Properties="ArtifactFormat=New;MixedArtifiactFolder=$(MainArtifactsFolder)DeployedArtifacts\"/>
</Target>
<Target Name="PreparePackFolderInternal">
<CallTarget Targets="PrepareInspectorWebServiceToPack;PrepareOtherFolders"/>
</Target>
<Target Name="CopyDefaultFiles">
<Exec Condition=" '$(ArtifactFormat)' == 'Old'" Command="xcopy "$(CompleteBinFolder)*.*" "$(MixedArtifiactFolder)$(ComponenetName)\Binaries" /I /Y /D /E /F"/>
<Exec Condition=" '$(ArtifactFormat)' == 'New'" Command="xcopy "$(CompleteBinFolder)*.*" "$(MixedArtifiactFolder)$(ComponenetName)" /I /Y /D /E /F"/>
<ItemGroup>
<GeneralConfigFiles Include="$(MixedArtifiactFolder)$(ComponenetName)\Binaries\*.config"/>
<PDBFiles Include="$(MixedArtifiactFolder)$(ComponenetName)\**\*.pdb"/>
</ItemGroup>
<Move Condition=" '$(ArtifactFormat)' == 'Old'" SourceFiles="#(GeneralConfigFiles)" DestinationFolder="$(MixedArtifiactFolder)$(ComponenetName)\Configurations"/>
<Move Condition=" '$(ArtifactFormat)' == 'New'" SourceFiles="#(PDBFiles)" DestinationFolder="$(MainArtifactsFolder)PDBs\$(ComponenetName)"/>
<Delete Condition=" '$(ArtifactFormat)' == 'Old'" Files="#(PDBFiles)"/>
</Target>
<Target Name="PrepareInspectorWebServiceToPack" Condition=" '$(BuildType)' != 'Clean' ">
<MSBuild Projects="$(MSBuildProjectFile)" Targets="CopyDefaultFiles" Properties="CompleteBinFolder=$(InspectorWebServicePublishPath);ComponenetName=InspectorWebService"/>
</Target>
<Target Name="PrepareOtherFolders">
<Exec Command="xcopy "$(SourcesPath)..\Certificates\*.*" "$(MixedArtifiactFolder)Certificates" /I /Y /D /E /F"/>
<Exec Command="xcopy "$(SourcesPath)\Resources\CCI\*.*" "$(DeployedPackageFolder)CCI\Configuration\" /I /Y /D /E /F"/>
</Target>
<Target Name="Pack" Condition=" '$(BuildType)' != 'Clean' ">
<RemoveDir Directories="$(PackageFolder)" />
<MakeDir Directories="$(PackageFolder)" />
<ItemGroup>
<InspectorWebServiceFilesForZip Include="$(DeployedPackageFolder)InspectorWebService\**\*.*" Exclude="$(DeployedPackageFolder)InspectorWebService\**\*.pdb" />
</ItemGroup>
<Zip ZipFileName="$(PackageFolder)$(VersionName)-InspectorWebService.zip" WorkingDirectory="$(DeployedPackageFolder)InspectorWebService" Files="#(InspectorWebServiceFilesForZip)" ZipLevel="9" ParallelCompression="false" />
<ItemGroup>
<AllZipFiles Include="$(DeployedPackageFolder)\**\*.*" Exclude="$(DeployedPackageFolder)\**\*.pdb" />
</ItemGroup>
<Zip ZipFileName="$(PackageFolder)$(VersionName)-!All.zip" WorkingDirectory="$(DeployedPackageFolder)" Files="#(AllZipFiles)" ZipLevel="9" ParallelCompression="false" />
<ItemGroup>
<AllPDBFiles Include="$(MainArtifactsFolder)PDBs\**\*.pdb"/>
</ItemGroup>
<Zip ZipFileName="$(PackageFolder)$(VersionName)-!PDBForAll.zip" WorkingDirectory="$(MainArtifactsFolder)PDBs" Files="#(AllPDBFiles)" ZipLevel="9" ParallelCompression="false" />
</Target>
<Target Name="Clean" Condition=" '$(BuildType)' == 'Clean' ">
<RemoveDir Directories="$(InspectorWebServicePublishPath)"/>
<RemoveDir Directories="$(PackageFolder)"/>
<RemoveDir Directories="$(MixedArtifiactFolder)"/>
</Target>
<Target Name="PauseBuild" Condition=" '$(PauseBuildOnError)' == 'true' ">
<Prompt Text="Press any key to continue ..." />
</Target>
<Target Name="ErrorHandler">
</Target>
</Project>

Related

How to include git's commit id in the log's filename?

NLog produces the following log filename MyMachine_MyExe_1.0.0.0.log. It includes the assembly version, but not the git's commit id which can be seen in dll's Product version property below.
Is there a way, either via NLog.config or programmatically to include the git's commit id in the log's filename?
NLog.config
<variable name="callsite" value="${callsite:includeNamespace=false:className=true:methodName=true}"/>
<variable name="baseLogDir" value="logs" />
<variable name="baseLogFilename" value="${machinename}_${processname}_${assembly-version}" />
<variable name="debugTraceLayout" value="${longdate}|${level:uppercase=true}|${callsite}|${message}" />
<targets>
<target
xsi:type="Console"
name="console"
layout="${longdate}|${level:uppercase=true}|${message}" />
<target xsi:type="File"
name="fileInfo"
fileName="${baseLogDir}/${baseLogFilename}.log"
layout="${longdate}|${level:uppercase=true}|${message}"
archiveFileName="${baseLogDir}/archive/${baseLogFilename}_{#}.log"
archiveNumbering="Date"
archiveOldFileOnStartup="true"
archiveDateFormat="yyyyMMdd_HHmmss" />
MyProject.csproj
<Project Sdk="Microsoft.NET.Sdk">
<Target Name="SetSourceRevisionId" BeforeTargets="InitializeSourceControlInformation">
<Exec Command="git describe --long --always --dirty --exclude=* --abbrev=8" ConsoleToMSBuild="True" IgnoreExitCode="False">
<Output PropertyName="SourceRevisionId" TaskParameter="ConsoleOutput" />
</Exec>
</Target>
</Project>
MyLibrary.dll Properties
I would define additional assembly attributes in your msbuild project;
<Project Sdk="Microsoft.NET.Sdk">
<Target Name="SetSourceRevisionId" BeforeTargets="InitializeSourceControlInformation">
<Exec ...></Exec>
<ItemGroup>
<AssemblyMetadata Include="SourceRevisionId" Value="$(SourceRevisionId)" />
</ItemGroup>
</Target>
</Project>
Which I believe you can use to define NLog's Global Diagnostic Context (GDC)
GlobalDiagnosticsContext.Set(
"SourceRevisionId",
typeof(Program).Assembly
.GetCustomAttributes<AssemblyMetadataAttribute>()
.Where(a => a.Key == "SourceRevisionId")
.Single()
.Value
);
And define the output filename;
fileName="${baseLogDir}/${gdc:item=SourceRevisionId}.log"

Python as a post-build step to C#

I'm looking into ways to execute python as part of a C# build.
Specifically, I want to create a Python package based on a C# project through python.net. My general idea was to build the C# project first. And then, as some sort of post-build step, invoke python to build a package based on the newly generated NET assemblies.
I can't presume python will installed on the build host, so ideally I want to include a "portable" - even more ideally, nuget-based - python distribution.
I have found a promising nuget package, but am not entirely sure of its usage. It incldues no C# code, but has all python binaries included, and has build props as copy/pasted below for reference.
Given on that package's props - can I somehow reference its binaries from my own project as a post-build step?
Say, for example, I want to add a post-build step to my own project, that simply just invokes "python.exe" after the build. How could I do that?
My own project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<GenerateProgramFile>false</GenerateProgramFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="python" Version="3.10.0-a6" />
</ItemGroup>
<Target Name="MyCustomStep" AfterTargets="Build">
<!-- .. now what? I can't seem to access. e.g. #(PythonHome) or $(PythonHome) from here --/>
<Target>
</Project>
Props of the python package from nuget:
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="$(Platform) == 'X64'">
<PythonHome Condition="$(PythonHome) == ''">$([System.IO.Path]::GetFullPath("$(MSBuildThisFileDirectory)\..\..\tools"))</PythonHome>
<PythonInclude>$(PythonHome)\include</PythonInclude>
<PythonLibs>$(PythonHome)\libs</PythonLibs>
<PythonTag>3.10</PythonTag>
<PythonVersion>3.10.0-a6</PythonVersion>
<IncludePythonExe Condition="$(IncludePythonExe) == ''">true</IncludePythonExe>
<IncludeDistutils Condition="$(IncludeDistutils) == ''">false</IncludeDistutils>
<IncludeLib2To3 Condition="$(IncludeLib2To3) == ''">false</IncludeLib2To3>
<IncludeVEnv Condition="$(IncludeVEnv) == ''">false</IncludeVEnv>
<GetPythonRuntimeFilesDependsOn>_GetPythonRuntimeFilesDependsOn310_None;$(GetPythonRuntimeFilesDependsOn)</GetPythonRuntimeFilesDependsOn>
</PropertyGroup>
<ItemDefinitionGroup Condition="$(Platform) == 'X64'">
<ClCompile>
<AdditionalIncludeDirectories>$(PythonInclude);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>$(PythonLibs);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<Target Name="GetPythonRuntimeFiles" Returns="#(PythonRuntime)" DependsOnTargets="$(GetPythonRuntimeFilesDependsOn)" />
<Target Name="_GetPythonRuntimeFilesDependsOn310_None" Returns="#(PythonRuntime)">
<ItemGroup>
<_PythonRuntimeExe Include="$(PythonHome)\python*.dll" />
<_PythonRuntimeExe Include="$(PythonHome)\python*.exe" Condition="$(IncludePythonExe) == 'true'" />
<_PythonRuntimeExe>
<Link>%(Filename)%(Extension)</Link>
</_PythonRuntimeExe>
<_PythonRuntimeDlls Include="$(PythonHome)\DLLs\*.pyd" />
<_PythonRuntimeDlls Include="$(PythonHome)\DLLs\*.dll" />
<_PythonRuntimeDlls>
<Link>DLLs\%(Filename)%(Extension)</Link>
</_PythonRuntimeDlls>
<_PythonRuntimeLib Include="$(PythonHome)\Lib\**\*" Exclude="$(PythonHome)\Lib\**\*.pyc;$(PythonHome)\Lib\site-packages\**\*" />
<_PythonRuntimeLib Remove="$(PythonHome)\Lib\distutils\**\*" Condition="$(IncludeDistutils) != 'true'" />
<_PythonRuntimeLib Remove="$(PythonHome)\Lib\lib2to3\**\*" Condition="$(IncludeLib2To3) != 'true'" />
<_PythonRuntimeLib Remove="$(PythonHome)\Lib\ensurepip\**\*" Condition="$(IncludeVEnv) != 'true'" />
<_PythonRuntimeLib Remove="$(PythonHome)\Lib\venv\**\*" Condition="$(IncludeVEnv) != 'true'" />
<_PythonRuntimeLib>
<Link>Lib\%(RecursiveDir)%(Filename)%(Extension)</Link>
</_PythonRuntimeLib>
<PythonRuntime Include="#(_PythonRuntimeExe);#(_PythonRuntimeDlls);#(_PythonRuntimeLib)" />
</ItemGroup>
<Message Importance="low" Text="Collected Python runtime from $(PythonHome):%0D%0A#(PythonRuntime->' %(Link)','%0D%0A')" />
</Target>
</Project>
That is for the use of internal nuget rather than your main project. You cannot get that property under main project.
You have to use my function:
1) edit csproj file and set this for your PackageReference python
<GeneratePathProperty>true</GeneratePathProperty>
Like this:
<ItemGroup>
<PackageReference Include="python" Version="3.10.0-a6">
<GeneratePathProperty>true</GeneratePathProperty>
</PackageReference>
</ItemGroup>
2) Then, you can use $(Pkgpython) to get that path.
<Target Name="MyCustomStep" AfterTargets="Build">
<Exec Command="$(Pkgpython)\tools\python.exe" />
</Target>

.Net Core msbuild build.proj equivilent of AssemblyInfo

I'm upgrading a project from AspNet Mvc 4 to AspNet Core Mvc 2.2; I am attempting to migrate the msbuild build.proj file to set the version and other attributes for the projects that create dll's; everything is working except the GenerateAssemblyInfo task. Is there a new way to do this in netcoreapp2.2?
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="GetRevisionInfo" BeforeTargets="Build">
<GitPendingChanges ContinueOnError="WarnAndContinue">
<Output TaskParameter="HasPendingChanges" PropertyName="HasPendingChanges" />
</GitPendingChanges>
<!--This will throw git Error 128 if there are no Tags -->
<GitDescribe SoftErrorMode="true" Lightweight="true" ContinueOnError="WarnAndContinue">
<Output TaskParameter="Tag" PropertyName="Tag" />
<Output TaskParameter="CommitCount" PropertyName="CommitCount" />
<Output TaskParameter="CommitHash" PropertyName="CommitHash" />
</GitDescribe>
<GitBranch ContinueOnError="WarnAndContinue">
<Output TaskParameter="Branch" PropertyName="Branch" />
</GitBranch>
<PropertyGroup>
<ShortCommitHash Condition="'$(CommitHash)' != ''">$(CommitHash.Substring(0,6))</ShortCommitHash>
<ReleaseType Condition="'$(CommitCount)' != '' AND '$(CommitCount)' != '0'">Beta</ReleaseType>
<ReleaseType Condition="'$(Branch)' != '' AND '$(Branch)' != 'master'">Alpha</ReleaseType>
</PropertyGroup>
</Target>
<!-- Error out if this is a release and our working copy has uncommitted changes -->
<Target Name="CheckRelease" AfterTargets="GetRevisionInfo" Condition="'$(Configuration)' == 'Release'">
<Error Text="Cannot build a Release Version when there are uncommitted changes, commit or revert all changes." Condition="'$(CommitHash)' != '' AND '$(HasPendingChanges)' == 'True'" />
</Target>
<!-- Generates AssemblyInfo file using Git Describe -->
<Target Name="GenerateAssemblyInfo" AfterTargets="CheckRelease" Condition="'$(CommitHash)' != ''">
<Time>
<Output TaskParameter="Year" PropertyName="Year" />
</Time>
<AssemblyInfo
CodeLanguage="CS"
OutputFile="$(MSBuildProjectDirectory)\Properties\AssemblyInfo.cs"
AssemblyProduct="$(MSBuildProjectName) $(ReleaseType)"
AssemblyCompany="xxx xxx xxx, LLC"
AssemblyCopyright="Copyright © $(Year) xxx xxx xxx, LLC. All rights reserved."
AssemblyConfiguration="$(Configuration)-$(Platform)"
AssemblyVersion="$(Tag).$(CommitCount)"
AssemblyFileVersion="$(Tag).$(CommitCount)"
AssemblyInformationalVersion ="$(Tag)-$(CommitCount)-$(ShortCommitHash) $(ReleaseType)"
AssemblyTitle="$(Tag)-$(CommitCount)-$(CommitHash)"/>
</Target>
<!-- copy framework files to libraries -->
<Target Name="CopyLibraries" Condition="'$(MSBuildProjectName)' == 'BaseApplication'" AfterTargets="Build">
<CreateItem Include="$(TargetDir)xxx.*">
<Output TaskParameter="Include" PropertyName="CopyFiles" />
</CreateItem>
<Copy SourceFiles="$(CopyFiles)" DestinationFolder="$(MSBuildProjectDirectory)\..\libraries\xxx\$(Configuration)"/>
</Target>
<Target Name="CopyKendoUI" AfterTargets="AfterBuild">
<ItemGroup>
<KendoFiles Include="
$(TargetDir)kendo.mvc.*;
$(TargetDir)\**\Kendo.Mvc.resources.*;" />
</ItemGroup>
<Copy SourceFiles="#(KendoFiles)" DestinationFolder="$(MSBuildProjectDirectory)\..\libraries\kendoui\$(Configuration)\%(RecursiveDir)"/>
</Target>
</Project>
There were a few things preventing this from working in Visual Studio 2019 using .Net Core;
The name of the target cannot be "GenerateAssemblyInfo", if this is the name of the target, it just gets ignored, no error, warning, or message, the target just doesn't run...
In the csproj file for the project that the msbuild project is imported in, you need to add false, I added this right below the
You have to manually create the Properties folder if you set the OutputFile to be in that folder.
Below is the working build.proj file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="GetRevisionInfo" BeforeTargets="Build">
<GitPendingChanges ContinueOnError="WarnAndContinue">
<Output TaskParameter="HasPendingChanges" PropertyName="HasPendingChanges" />
</GitPendingChanges>
<!--This will throw git Error 128 if there are no Tags -->
<GitDescribe SoftErrorMode="true" Lightweight="true" ContinueOnError="WarnAndContinue">
<Output TaskParameter="Tag" PropertyName="Tag" />
<Output TaskParameter="CommitCount" PropertyName="CommitCount" />
<Output TaskParameter="CommitHash" PropertyName="CommitHash" />
</GitDescribe>
<GitBranch ContinueOnError="WarnAndContinue">
<Output TaskParameter="Branch" PropertyName="Branch" />
</GitBranch>
<PropertyGroup>
<ShortCommitHash Condition="'$(CommitHash)' != ''">$(CommitHash.Substring(0,6))</ShortCommitHash>
<ReleaseType Condition="'$(CommitCount)' != '' AND '$(CommitCount)' != '0'">Beta</ReleaseType>
<ReleaseType Condition="'$(Branch)' != '' AND '$(Branch)' != 'master'">Alpha</ReleaseType>
</PropertyGroup>
</Target>
<!-- Error out if this is a release and our working copy has uncommitted changes -->
<Target Name="CheckRelease" AfterTargets="GetRevisionInfo" Condition="'$(Configuration)' == 'Release'">
<Error Text="Cannot build a Release Version when there are uncommitted changes, commit or revert all changes." Condition="'$(CommitHash)' != '' AND '$(HasPendingChanges)' == 'True'" />
</Target>
<!-- Generates AssemblyInfo file using Git Describe -->
<Target Name="GenerateAssemblyInfo" AfterTargets="CheckRelease" Condition="'$(CommitHash)' != ''">
<Time>
<Output TaskParameter="Year" PropertyName="Year" />
</Time>
<AssemblyInfo
CodeLanguage="CS"
OutputFile="$(MSBuildProjectDirectory)\Properties\AssemblyInfo.cs"
AssemblyProduct="$(MSBuildProjectName) $(ReleaseType)"
AssemblyCompany="xxx xxx xxx, LLC"
AssemblyCopyright="Copyright © $(Year) xxx xxx xxx, LLC. All rights reserved."
AssemblyConfiguration="$(Configuration)-$(Platform)"
AssemblyVersion="$(Tag).$(CommitCount)"
AssemblyFileVersion="$(Tag).$(CommitCount)"
AssemblyInformationalVersion ="$(Tag)-$(CommitCount)-$(ShortCommitHash) $(ReleaseType)"
AssemblyTitle="$(Tag)-$(CommitCount)-$(CommitHash)"/>
</Target>
<!-- copy framework files to libraries -->
<Target Name="CopyLibraries" Condition="'$(MSBuildProjectName)' == 'BaseApplication'" AfterTargets="Build">
<CreateItem Include="$(TargetDir)xxx.*">
<Output TaskParameter="Include" PropertyName="CopyFiles" />
</CreateItem>
<Copy SourceFiles="$(CopyFiles)" DestinationFolder="$(MSBuildProjectDirectory)\..\libraries\xxx\$(Configuration)"/>
</Target>
<Target Name="CopyKendoUI" AfterTargets="AfterBuild">
<ItemGroup>
<KendoFiles Include="
$(TargetDir)kendo.mvc.*;
$(TargetDir)\**\Kendo.Mvc.resources.*;" />
</ItemGroup>
<Copy SourceFiles="#(KendoFiles)" DestinationFolder="$(MSBuildProjectDirectory)\..\libraries\kendoui\$(Configuration)\%(RecursiveDir)"/>
</Target>
</Project>
And the MyProject.csproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MSBuildTasks" Version="1.5.0.235">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Http.Abstractions">
<HintPath>C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.abstractions\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
</Reference>
</ItemGroup>
<Import Project="../.build/build.proj" />
</Project

MSBuild. Create EmbeddedResource before build

I want to embed local references in the assembly before compiling the main unit. But the written target does not work.
<Target Name="EmbedLocal" BeforeTargets="CoreCompile">
<Message Text="Run EmbedLocal for $(MSBuildProjectFullPath)..." Importance="high"/>
<ItemGroup>
<EmbeddedResource Include="#( ReferencePath->WithMetadataValue( 'CopyLocal', 'true' )->Metadata( 'FullPath' ) )"/>
</ItemGroup>
<Message Text="Embed local references complete for $(OutputPath)$(TargetFileName)." Importance="high" />
</Target>
#(EmbeddedResource) at this moment contains valid list of paths.
Update:
Now my import file contains:
<Project ToolsVersion="$(MSBuildToolsVersion)" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EmbedLocalReferences Condition=" '$(EmbedLocalReferences)' == '' ">True</EmbedLocalReferences>
</PropertyGroup>
<Target Name="EmbedLocal" BeforeTargets="ResolveReferences" Condition=" '$(EmbedLocalReferences)' == 'True' ">
<Message Text="Run EmbedLocal for $(MSBuildProjectFullPath)..." Importance="high"/>
<ItemGroup>
<EmbeddedResource Include="#(ReferenceCopyLocalPaths->WithMetadataValue( 'Extension', '.dll' )->Metadata( 'FullPath' ))">
<LogicalName>%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
<Message Text="Embed local references complete for $(OutputPath)$(TargetFileName)." Importance="high" />
</Target>
</Project>
It works fine. Output assembly contains all .dll references as EmbeddedResource.
MSBuild. Create EmbeddedResource before build
You can try to use BeforeBuild action to the csproj file to include the embedded resources:
<Target Name="BeforeBuild">
...
<ItemGroup>
<EmbeddedResource Include="..."/>
</ItemGroup>
...
</Target>
Now MSBuild will add this file as embedded resource into your assembly.
Update:
Thanks #Martin Ullrich. He pointed out the correct direction, we could use <Target Name="EmbedLocal" BeforeTargets="PrepareForBuild"> in the Directory.Build.props to resolve this issue. You can check if it works for you.
<Target Name="EmbedLocal" BeforeTargets="PrepareForBuild">
...
<ItemGroup>
<EmbeddedResource Include="..."/>
</ItemGroup>
...
</Target>

MSBuild solution with many web projects output to same directory

I'd like to build many web projects and output them to a directory such as ./output/Project1 ./output/Project2 etc. Each of these folders would contain essentially what's output to _PublishedWebsites. I've tried this:
msbuild support.sln /p:configuration=Release;DeployOnBuild=true;DeployTarget=Package;_PackageTempDir=c:/ws/code/supportsite/output/ /t:package
but it seems to overwrite the contents of the output directory with each project that's built.
Why not make target file.
XCopyWebDeploy.targets
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>
<XCopyDeployWebPackage Condition=" '$(XCopyDeployWebPackage)' == '' ">false</XCopyDeployWebPackage>
</PropertyGroup>
<ItemGroup>
<ProjectFileItem Include="$(ProjectPath)"/>
</ItemGroup>
<PropertyGroup>
<!-- Make the build depend on web deploy packages -->
<BuildDependsOn Condition="$(XCopyDeployWebPackage) == 'true'">
$(BuildDependsOn);
Package;
XCopyDeployWebPackage;
</BuildDependsOn>
</PropertyGroup>
<Target Name="XCopyDeployWebPackage">
<CreateItem Include="$(ProjectDir)obj\$(Configuration)\Package\PackageTmp\**\*.*">
<Output ItemName="XCopyWebDeployPackageOutputFiles" TaskParameter="Include"/>
</CreateItem>
<CreateProperty Value="c:\ws\code\supportsite\output\%(ProjectFileItem.Filename)">
<Output PropertyName="XCopyWebDeployOutput" TaskParameter="Value"/>
</CreateProperty>
<Copy
SourceFiles="#(XCopyWebDeployPackageOutputFiles)"
DestinationFiles="#(XCopyWebDeployPackageOutputFiles->'$(XCopyWebDeployOutput)\%(RecursiveDir)%(Filename)%(Extension)')"/>
</Target>
</Project>
And import in web project(s) file.
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{BF6B6392-1398-42D3-AA90-ED87D02D351A}</ProjectGuid>
<ProjectTypeGuids>{E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MvcApplication1</RootNamespace>
<AssemblyName>MvcApplication1</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<MvcBuildViews>false</MvcBuildViews>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<!--!!!-->
<XCopyDeployWebPackage>true</XCopyDeployWebPackage>
<!--!!!-->
</PropertyGroup>
<!-- Some lines omitted -->
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<!--!!!-->
<Import Project="$(SolutionDir)\XCopyWebDeploy.targets" />
<!--!!!-->
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target> -->
</Project>

Categories