What is default msbuild platform - msbuild

How does msbuild chose a platform if it is not specified? It seems to me that for some solutions it selects "Mixed Platforms" for others "x86".
I switch on the diagnostics level of logging and the only thing I can see is that "Initial Properties" at the beginning contain e.g. "Platform = Mixed Platforms" without any explanation why.
To preempt some answers, I know that I can override the platform manually. That is not an issue. I need to know what msbuild does when it is NOT specified.

This may help: I was researching this and finally tracked down the default platform for my install, by looking in Microsoft.Cpp.Default.props (line 21 in this version of Visual Studio), which lives in Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120:
<Platform Condition="'$(Platform)' == ''">Win32</Platform>
This means that under VS12 (Visual Studio 2013) MSBuild will pick Win32 as the platform if no other platform is explicitly specified. As noted in some other questions, setting an environment variable named Platform will change the default to the value you set.
Important note: If you invoke MSBuild on a Visual Studio solution file (*.sln) rather than a project file, and you don't specify a platform in the MSBuild arguments, then it appears that MSBuild will choose the platform automatically based on the first entry under the SolutionConfigurationPlatforms global section in the solution file. I haven't found this documented anywhere but from experimentation it appears to be the case. This means that editing your project file and providing a different default Platform property (as described above), MSBuild will ignore this default, because it will have chosen the platform already before it even starts looking at the project. Invoking MSBuild directly on the project file seems to bypass this behavior.

MSBuild does not choose but whatever MSBuild project it is building may default certain properties. I am assuming that your question relates to how MSBuild builds a solution file.
msbuild.exe "somesolution.sln" /t:Build
You need to look at the projects that make up the solution, in there you will see the properties that are set. For example you will probably see the following at the top of the project file:
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
...
</PropertyGroup>
This shows a PropertyGroup containing amongst others two properties, Configuration and Platform. Their values are set based on a Condition. The condition says says that if no value has been set for the property Configuration it should default to 'Debug'. Likewise if nothing is set for Platform it should default to AnyCPU.
You may also see a Conditional PropertyGroup:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
...
</PropertyGroup>
What this condition says is that if the property Configuration and Platform match Debug and AnyCPU then it should apply all of the properties contained within.
A point to note is that the property names are just an arbitrary name and the values are just strings. However when building .Net projects there is a convention to which these properties and their values are a part. To see what the default values are you do not need to open each project in a text editor. You can go into Visual Studio and look at the solution configuration.

Related

How do you disable Roslyn Analyzers when using msbuild through the command line?

The Roslyn Analyzers are installed as nuget packages, which are dependencies of the FxCop Analyzers (also installed as nuget packages).
I have enabled full solution analysis as instructed here: How to Enable and disable full solution analysis for managed code.
I have a fairly large solution with most of the projects using the FxCop/Roslyn Analyzers and Visual Studio builds fine, usually in under a minute.
However, when running msbuild through the command line using:
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/MSBuild/15.0/Bin/MSBuild.exe" "C:\Source\MySolution\MySmartClient.sln" /p:Configuration=Develop;Platform="Any CPU" /
t:Build
Building the solution takes anywhere from 4-15 minutes. The same is true on the build server which uses the same command.
I've tried /p:RunCodeAnalysis=False and that has no effect. I've also used process monitor to emulate the msbuild command that VS sends to msbuild with no change.
And, according to this doc: How to: Enable and disable automatic code analysis for managed code
The Enable Code Analysis on Build check box only affects static code analysis. It doesn't affect Roslyn code analyzers, which always execute at build if you installed them as a NuGet package.
These excessive build times are not practical. Is there any way to disable when using msbuild through the command line?
It's not really supported, but there is a workaround:
Create a Directory.Build.targets (msbuild >= v15.0), After.{SolutionName}.sln.targets (msbuild < 15.0) file in your solution root folder and add:
<Project>
<Target Name="DisableAnalyzers"
BeforeTargets="CoreCompile"
Condition="'$(UseRoslynAnalyzers)' == 'false'">
<!--
Disable analyzers via an MSBuild property settable on the command line.
-->
<ItemGroup>
<Analyzer Remove="#(Analyzer)" />
</ItemGroup>
</Target>
</Project>
You can pass in /p:UseRoslynAnalyzers=false now to remove all analyzers configured in the project.
See also:
https://github.com/dotnet/roslyn/issues/23591#issuecomment-507802134
https://learn.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2019#directorybuildprops-and-directorybuildtargets
You can edit the condition to also trigger on RunCodeAnalysis=False or Never.
<Target Name="DisableAnalyzers"
BeforeTargets="CoreCompile"
Condition="
'$(UseRoslynAnalyzers)' == 'false'
or '$(RunCodeAnalysis)' == 'false'
or '$(RunCodeAnalysis)' == 'never'" >
To disable a specific analyzer, use this trick:
We just spent 2 hours figuring out how to disable an analyzer based on an MSBuild property, AMA.
https://twitter.com/Nick_Craver/status/1173996405276467202?s=09
The documentation has changed since the original answers. There is now this page documenting how to disable code analysis from analyzers:
There are 3 MSBuild properties you can use to control analyzer behavior (all default to true):
RunAnalyzersDuringBuild Controls whether analyzers run at build time.
RunAnalyzersDuringLiveAnalysis Controls whether analyzers analyze code live at design time.
RunAnalyzers Disables analyzers at both build and design time. This property takes precedence over RunAnalyzersDuringBuild and RunAnalyzersDuringLiveAnalysis.
Edit: it looks like there is an issue being tracked where these props don't work unless your project has Microsoft.CodeAnalysis.targets included. So your mileage may vary until this is fixed.
In case anyone else happens to find themselves here, I came across this issue on the dotnet/roslyn project on Github:
Feature: MSBuild switch for turning on/off analysis #23591
The preceding issue describes a work-around:
Substitute for old MSBuild properties? #1431
<PropertyGroup>
<RunCodeAnalysis Condition="'$(RunCodeAnalysis)' == ''">true</RunCodeAnalysis>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="<whatever analyzers package you are depending on>" Condition="'$(RunCodeAnalysis)' == 'true'" />
</ItemGroup>
# You'll need to run a restore when changing this value
msbuild /p:RunCodeAnalysis=false
Although, I had a couple of differences though since I'm not using package references. This worked for me.
<ItemGroup>
<Analyzer Include="<whatever analyzers package you are depending on>" Condition="'$(RunCodeAnalysis)' == 'true'" />
</ItemGroup>
<!-- I added the condition to the EnsureNugetPackageBuildImports too. -->
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="'$(RunCodeAnalysis)' == 'true' AND !Exists('<relative path to the prop of whatever analyzers you are depending on>')" Text="$([System.String]::Format('$(ErrorText)', '<relative path to the prop of whatever analyzers you are depending on>'))" />
</Target>

What configuration and platform does msbuild use by default when building a solution file or project files

If I execute msbuild from the command line with my solution file or project file as input without setting configuration and platform how does msbuild determine which configuration and platform to use for each project in the solution or the single project file?
In case of solution files - both msbuild and xbuild try to find Debug config and Mixed platforms platform, but if that doesn't exist then it falls back to the first one that it can find under SolutionConfigurationPlatforms in the .sln file. Keep in mind that this is just solution level config/platform, and it uses the mapping in ProjectConfigurationPlatforms in the .sln file to determine the config/platform to use for the project.
In case of project files, the *proj files usually have the default Configuration and Platform specified. But if even that is missing then the Microsoft.Common.*targets file chooses Debug|AnyCPU as the default.
Update: default specification in the csproj might look like this:
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
...
It's essentially saying "if $(Configuration) is unspecified, then set it to Debug", and similar for Platform.

Visual Studio macro/anything else to iterate through all projects and set project properties

I'm trying to write a macro/anything else to iterate though all projects and remove all other build configuration other that Active Solution Configuration - Debug and Active Solution Platform - x86. Also after editing the configuration for all projects, I want to set pre-build and post-build events to all projects. I have no clue where to start. Please help. I have like 44 projects in solution and its really hard and time consuming to set all these manually.
Pre Build event:
rd /s /q "$(ProjectDir)bin"
Post Build event:
copy "$(TargetPath)" "$(SolutionDir)TOTALOUTPUT\" /y
I could not understand your point clearly but let me try to help...
You can create a new configuration by clickint Build->Configuration Manager->New (top left, there is active solution configuration, click on it you will see New option)
Name it and check the projects you wanna compile
Then simply go your solution, select the projects with Ctrl and then leftclick->properties
VS allows you to change the properties of multiple projects, so you can easily writes post builds and pre builds events like that, it will work for all projects you selected...
You can choose to put this in a macro, or not, however I would actually recommend directly going to the .csproj and .sln files. In the .csproj files they have a series of property groups that specify the build configuration like so:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
If you create a simple script/program/etc that traverses all the .csproj files in question, and read the .csproj xml file. While going through it, you can simply ensure that only the 2 PropertyGroups defining configurations show up. These two configurations will be your debug/release configs. Further, in that same script you can add your pre/post build events, they are simply a different type of property group, such as so:
<PropertyGroup>
<PostBuildEvent>xcopy $(TargetName).* "%25SEARCH1%25"\bin\ /i /y</PostBuildEvent>
</PropertyGroup>
Note: It is likely better to do this as a script when Visual Studio is closed rather than as a macro, but I see no reason why simply wrapping this into a macro wouldn't work either.

Suppressing C#-specific warnings in a solution that contains both C# and VB.NET projects

We use TFS 2010 for server builds. I would like to turn some of the less useful warnings off. I can achieve that by specifying custom MSBuild arguments:
/p:NoWarn=1591
It works for a solution with C# projects. However, we have one solution that also has some VB.NET projects in it. VB.NET compiler doesn't have the warnings that C# compiler has, so I get the following error message:
vbc: warning number '1591' for the option 'nowarn' is either not configurable or not valid
Is there a way to achieve this for solution that include projects in several .NET languages without specifying list of ignored warnings separately for every project in the solution?
BC* warnings can't be suppressed. Your best option is to reevaluate the NoWarn property in VB projects using the BeforeCompile target, by editing the .vbproj files:
<Target Name="BeforeCompile">
<PropertyGroup Condition=" '$(NoWarn)' == '1591' ">
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
</Target>

How do I specify the platform for MSBuild?

I am trying to use MSBuild to build a solution with a specified target platform (I need both binaries, x86 and x64). This is how I tried it:
C:\WINDOWS\Microsoft.NET\Framework\v3.5>MsBuild SolutionPath\Solution.sln /t:Rebuild /p:Configuration=Release /p:Platform="x86"
However the build always fails if the platform is different from "Any CPU". What am I doing wrong?
This is the while output MSBuild prints:
C:\WINDOWS\Microsoft.NET\Framework\v3.5>MsBuild
SolutionPath\Solution.sln /t:Rebuild
/p:Configuration=Release
/p:Platform="x86" Microsoft (R) Build
Engine Version 3.5.30729.1 [Microsoft
.NET Framework, Version
2.0.50727.3082] Copyright (C) Microsoft Corporation 2007. All rights
reserved.
Build started 1.7.2010 8:28:10.
Project "SolutionPath\Solution.sln" on
node 0 (Rebuild targe t(s)).
SolutionPath\Solution.sln : error
MSB4126: The specified sol ution
configuration "Release|x86" is
invalid. Please specify a valid
solution c onfiguration using the
Configuration and Platform properties
(e.g. MSBuild.exe Solution.sln
/p:Configuration=Debug
/p:Platform="Any CPU") or leave those
prope rties blank to use the default
solution configuration. Done Building
Project "SolutionPath\Solution.sln"
(Rebuild t arget(s)) -- FAILED.
Build FAILED.
"SolutionPath\Solution.sln" (Rebuild
target) (1) ->
(ValidateSolutionConfiguration target)
-> SolutionPath\Solution.sln : error MSB4126: The specified s olution
configuration "Release|x86" is
invalid. Please specify a valid
solution configuration using the
Configuration and Platform properties
(e.g. MSBuild.ex e Solution.sln
/p:Configuration=Debug
/p:Platform="Any CPU") or leave those
pro perties blank to use the default
solution configuration.
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.03
If I try to build it for x86/x64 with devenv it works perfectly, however I am trying to set up a build server without installing all the necessary versions of Visual Studio. By the way, if there is a better free tool (that supports .NET framework 4) out there, I'd love to hear about it.
In MSBuild or Teamcity use command line
MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64
or use shorter form:
MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64
However you need to set up platform in your project anyway, see the answer by Julien Hoarau.
If you want to build your solution for x86 and x64, your solution must be configured for both platforms. Actually you just have an Any CPU configuration.
How to check the available configuration for a project
To check the available configuration for a given project, open the project file (*.csproj for example) and look for a PropertyGroup with the right Condition.
If you want to build in Release mode for x86, you must have something like this in your project file:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
...
</PropertyGroup>
How to create and edit the configuration in Visual Studio
(source: microsoft.com)
(source: msdn.com)
(source: msdn.com)
How to create and edit the configuration (on MSDN)
If you're trying to do this from the command line, you may be encountering an issue where a machine-wide environment variable 'Platform' is being set for you and working against you. I can reproduce this if I use the VS2012 Command window instead of a regular windows Command window.
At the command prompt type:
set platform
In a VS2012 Command window, I have a value of 'X64' preset. That seems to interfere with whatever is in my solution file.
In a regular Command window, the 'set' command results in a "variable not defined" message...which is good.
If the result of your 'set' command above returns no environment variable value, you should be good to go.
Hopefully this helps someone out there.
For platform I was specifying "Any CPU", changed it to "AnyCPU" and that fixed the problem.
msbuild C:\Users\Project\Project.publishproj /p:Platform="AnyCPU" /p:DeployOnBuild=true /p:PublishProfile=local /p:Configuration=Debug
If you look at your .csproj file you'll see the correct platform name to use.
For VS2017 and 2019... with the modern core library SDK project files, the platform can be changed during the build process. Here's an example to change to the anycpu platform, just before the built-in CoreCompile task runs:
<Project Sdk="Microsoft.NET.Sdk" >
<Target Name="SwitchToAnyCpu" BeforeTargets="CoreCompile" >
<Message Text="Current Platform=$(Platform)" />
<Message Text="Current PlatformTarget=$(PlatformName)" />
<PropertyGroup>
<Platform>anycpu</Platform>
<PlatformTarget>anycpu</PlatformTarget>
</PropertyGroup>
<Message Text="New Platform=$(Platform)" />
<Message Text="New PlatformTarget=$(PlatformTarget)" />
</Target>
</Project>
In my case, I'm building an FPGA with BeforeTargets and AfterTargets tasks, but compiling a C# app in the main CoreCompile. (partly as I may want some sort of command-line app, and partly because I could not figure out how to omit or override CoreCompile)
To build for multiple, concurrent binaries such as x86 and x64: either a separate, manual build task would be needed or two separate project files with the respective <PlatformTarget>x86</PlatformTarget> and <PlatformTarget>x64</PlatformTarget> settings in the example, above.
When you define different build configurations in your visual studio solution for your projects using a tool like ConfigurationTransform, you may want your Teamcity build, to build you a specified build configuration. You may have build configurations e.g., Debug, Release, Dev, UAT, Prod etc defined. This means, you will have MSBuild Configuration transformation setup for the different configurations. These different configurations are usually used when you have different configurations, e.g. different database connection strings, for the different environment. This is very common because you would have a different database for your production environment from your playground development environment.
They say a picture is worth a thousand words, please see the image below how you would specify multiple build configurations in Teamcity.
In the commandline input text box, specify as below
/p:OutputPath=Publish;Configuration=Dev
Here, I have specified two commandline build configurations/arguments OutputPath and build Configuration with values Publish and Dev respectively, but it could have been, UAT or Prod configuration. If you want more, simply separate them by semi-colon,;
There is an odd case I got in VS2017, about the space between ‘Any’ and 'CPU'.
this is not about using command prompt.
If you have a build project file, which could call other solution files. You can try to add the space between Any and CPU, like this (the Platform property value):
<MSBuild Projects="#(SolutionToBuild2)" Properties ="Configuration=$(ProjectConfiguration);Platform=Any CPU;Rerun=$(MsBuildReRun);" />
Before I fix this build issue, it is like this (ProjectPlatform is a global variable, was set to 'AnyCPU'):
<MSBuild Projects="#(SolutionToBuild1)" Properties ="Configuration=$(ProjectConfiguration);Platform=$(ProjectPlatform);Rerun=$(MsBuildReRun);" />
Also, we have a lot projects being called using $ (ProjectPlatform), which is 'AnyCPU' and work fine. If we open proj file, we can see lines liket this and it make sense.
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
So my conclusion is,
'AnyCPU' works for calling project files, but not for calling solution files,
for calling solution files, using 'Any CPU' (add the space.)
For now, I am not sure if it is a bug of VS project file or MSBuild.
I am using VS2017 with VS2017 build tools installed.
In Visual Studio 2019, version 16.8.4, you can just add
<Prefer32Bit>false</Prefer32Bit>