PackageReference condition is ignored for old project format - msbuild

I'm trying to centralize some of our project configurations by using the Directory.Builds.props/Directory.Build.targets files. Unfortunately we have a mixture of the old and new (sdk-style) project format. And not all of our projects can be converted to the new format due to some features not available in in the new format.
The issues that I'm running into is that I would like to have all our test projects automatically reference certain nuget packages. For projects in the new format, this works fine. However projects in the old format seem to ignore any conditions for the PackageReferences that I specify. It doesn't seem to matter what I use for the condition.
Here is an example of a very simple Directory.Build.Targets file:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<PackageReference Include="Moq" Version="4.12.0" Condition="False" />
</ItemGroup>
</Project>
In this case I should never see the Moq package included in any project.
For all the projects in the old format it is included regardless.
I have also tried to use the condition on:
ItemGroup itself
Choose/When block
Putting a condition on a property group or property works as expected on the other hand.
I haven't see any mention in the documentation that conditions are not supported for ItemGroup or PackageReference.
Is there something I'm missing?
Thanks

I don't believe non-SDK projects support PackageReference; I suspect they are being ignored regardless of any condition you specify. Check for a packages.config file in the same directory as the project file-- if I am right it is present and references the package(s) in question.

The Nuget docs currently state:
You can use a condition to control whether a package is included, where conditions can use any MSBuild variable or a variable defined in the targets or props file. However, at presently, only the TargetFramework variable is supported.
My experience was that the Condition="" was ignored by Visual Studio, but respected by the msbuild command line. However, in my testing the <Choose><When Condition=""> block did seem to be respected by both tools.

Related

MSBuild 16.9 .NET Core 3.1 - OutDir isn't searched for dependencies

I'm trying to use MSBuild in a powershell script to build many projects and solutions in a full application suite. I set the parameter for OutDir to point to a single binaries directory and from an output perspective that works.
However the documentation states that OutDir is included in AssemblySearchPaths. But looking at the logs MSBuild is clearly stuck using the hintpath from the csproj file. I've tried setting AdditionalLibPaths as well with no success. This appears to be an issue with building from Visual Studio 2019 as well. My hintpaths point to a common debug directory. A release build still looks in the debug directory. This used to work in older versions of Studio in the .NET Framework days. It worked in older TFS XAML builds setting Output Location to "SingleFolder"
I've also played around with OutDir path ending various quantities of back slashes. I suspect that this old issue is fixed.
How can I get MSBuild to use an alternate directory for the dependencies?
https://learn.microsoft.com/en-us/visualstudio/msbuild/common-msbuild-project-properties?view=vs-2019
EDIT:
As per the accepted answer, adding OutDir to the AssemblySearchPaths does the trick. For me, I've created a proj file that I've added to each .NET Core csproj files. My thought is that when this gets fixed I can remove the tweak in one place.
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<AssemblySearchPaths>$(AssemblySearchPaths);$(OutDir)</AssemblySearchPaths>
</PropertyGroup>
My hintpaths point to a common debug directory. A release build still
looks in the debug directory.
The outdir is always the output folder which does not distinguish between Release and Debug. So you have to use <OutDir>C:\ttt\$(Configuration)\</OutDir> to distinguish between them.
Actually, the system msbuild properties are read earlier than the start of build task. You have to set the properties before the start of build process.
Simply modifying the system properties outdir in csproj will only take effect during the build process, but the system properties are still read before the build starts, also AssemblySearchPaths property read the previous outdir property. So you always take the default values before the modification.
You have to use Directory.Build.props file, it set the values earlier than msbuild start.
1) create a file called Directory.Build.props under your project folder.
2) add the outdir property like these into the file.
<Project>
<PropertyGroup>
<OutDir>C:\ttt\$(Configuration)\</OutDir>
</PropertyGroup>
</Project>
3) restart VS to enable it.
However, I note that it works well in non-sdk net framework projects but it does not list under new-sdk net core projects.
non-sdk net framework projects
new-sdk net core projects
Not sure it is an issue or the Team has forgotten it. Anyway, I have reported it to our DC Forum. You can vote it or add any comments if I did not described it in detail.
As a workaround, you could try to set the new value for AssemblySearchPaths property.
In order not to lose the original value of AssemblySearchPaths, you must add it to csporj file rather than Directory.Build.props file.
Just add these into csproj file:
<PropertyGroup>
<AssemblySearchPaths>$(AssemblySearchPaths);$(OutDir)</AssemblySearchPaths>
</PropertyGroup>
Update 1
I think it is an issue for net core projects.
What I said before is for VS IDE build. Now for MSBuild Command Line, it is another situation.
For non-sdk net framework projects
When I used msbuild xxx\xxx.csproj -p:outdir=c:\ttt -v:diagnostic, it shows this:
Well. It works perfect as we wished.
However, when we used the same command line for new-sdk net core projects, it does nothing. So I think it is quite an issue for net core projects.
And you should note that AdditionalLibPaths cannot be recognized by AssemblySearchPaths.
When I used this under :
msbuild xxx\xxx.csproj -p:AdditionalLibPaths=c:\ttt -v:diagnostic
And you should note that there is no property for AdditionalLibPaths under the list of AssemblySearchPaths property. And it also does not work for net core projects.
In short, it is quite an issue for net core projects no doubt. I also modify the DC ticket.
Now for new-sdk net core projects,
Since you used msbuild command line to set properties, so there is no need to use Directly.Build.props file. MSbuild command line property assignment is actually the same effect of the file.
Also, AssemblySearchPaths is not ready-only. You could modify it. And actually, all msbuild properties can be overwritten and that is a flexible feature of MSBuild.
In summary, you still have to use AssemblySearchPaths.
Solution
Since The Team has some problems with this detail in the net core project, we can use the flexibility of MSbuild to manually modify to get what we want:
1) abandon using Directly.Build.props file and also keep adding these on the net core csproj file:
<PropertyGroup>
<AssemblySearchPaths>$(AssemblySearchPaths);$(OutDir)</AssemblySearchPaths>
</PropertyGroup>
2) use the following command line for net core projects:
msbuild xxx\xxx.csproj -p:Outdir=c:\ttt -v:diagnostic

.net core (csproj) global.json 'projects' equivalent

With .net core (project.json) I used to switch between nuget packages and source code by adding the path to source code to the projects field in the global.json. After I did that it would add all the projects that it could find in that path that could replace the nuget packages I referenced.
I used this feature alot because I have my own nuget packages that I use, but I want to test the changes in my other project before I publish. But once I switched to Sdk 1.0.0/VS 2017/csproj .net core that feature seemed to disappear.
The alternative is just manually adding each project, switch the references manually (since they are broken up into project, nuget and sdk references), and then after switch it all back.
Any thoughts or advice would be great.
UPDATE:
Sounds like there is no equivalent in csproj (as expected), but there are msbuild workarounds for now (As of the initial VS 2017/.NET Core SDK 1.0.0 release)
Yes, I too had gotten used to this functionality and built my workflow around it. I am still looking for a solution but I'm currently playing with the idea of using conditional logic in the csproj files. Since it's now msbuild, you can do things like this:
<Choose>
<When Condition="Exists('..\..\..\MyProject')">
<ItemGroup>
<ProjectReference Include="..\..\..\MyProject\src\MyProject\MyProject.csproj" />
</ItemGroup>
</When>
<Otherwise>
<ItemGroup>
<PackageReference Include="MyProject" Version="1.0.0" />
</ItemGroup>
</Otherwise>
</Choose>
This replaces the hard reference to a package with a conditional that uses a project reference if it can find the source code (in this case the directory), and a package reference if can't.
So by default you would be referencing the package, but if you want to debug one of your projects, you check it out in the location that the conditional checks, and add the project to your solution.
This way you only need to change your solution file (by adding the project) when you want to include source code, instead of rewiring all your project references.
For others that are interested in attempting to emulate with Global.json did, I worked around this for now using a couple powershell scripts and a custom json file that mimics it. Check out my answer here:
https://stackoverflow.com/a/43795974/5504245

MSBuild to include dynamically generated files as part of project dependency when the dynamic files are in the bin directory

An extension of this question, but slightly different, and the accepted answer does not quite work for this situation.
We've got a process in place on the build of our project which is generating some additional files, these files are getting (correctly) generated into the /bin folder as expected. However they are not getting copied across when this project is referenced as a dependency.
Following the above questions accepted answer (with a little bit of tweaking), I managed to get them copying across to the dependant project however they are all getting put into a /bin sub folder of the dependants /bin folder (i.e. /bin/bin), which is not what I need to have happen.
The process we're running is a 3rd party process (specifically Surviveplus.XmlCommentLocalization), so I have no control over that side of it.
I could do something additional on the dependant project to move them out of the /bin/bin into the level up, but I'd rather have the original project work as I'd expect it to.
This is the ItemGroup I'm using, derived from the other question:
<ItemGroup>
<Content Include="$(OutputPath)\**\*\*.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
I've also tried setting specifically the TargetPath value, which while un-documented (or I'm blind to it), seems to exist - as per the msbuild output log
<ItemGroup>
<Content Include="$(OutputPath)\**\*\*.xml" KeepMetadata="TargetPath">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<TargetPath>..\</TargetPath>
</Content>
</ItemGroup>
But it appears that when it comes to the Copy task it just ignores it, and resolves a new TargetPath. I've also tried a myriad of combinations of attributes/item types in that item group (i.e. None, EmbeddedResource) but they didn't solve it either.
Ideally I suppose MSBuild needs to mark the generated files as part of the generated assembly? But after getting lost in .target files and MSDN docs, I couldn't figure it out.
MSBuild being used is version 12.0, compiling for .net4.5.

How can I run the current version of a NuGet package executable from the MSBuild project file?

I have added the xunit.runners package to a solution. The current version is 1.9.1, so I have hard-coded the path to the executable in an MSBuild project file:
<StartAction>Program</StartAction>
<StartProgram>$(MSBuildProjectDirectory)\..\..\Packages\xunit.runners.1.9.1\tools\xunit.gui.clr4.exe</StartProgram>
<StartArguments>"$(MSBuildProjectDirectory)\$(OutPutPath)$(AssemblyName).dll"</StartArguments>
(Off-topic: with this configuration, F5 starts the xUnit GUI runner and I can debug specific unit tests.)
I know that everytime I update the Nuget package, I will forget to change the path. Changing the path is a minor nuisance, since I have to unload the project, edit the file, then reload the project.
How can I start the executable, regardless of the actual version of the package? Can I find the executable in the folder named xunit.runners.* using a wildcard in MSBuild, then use that as a property in the <StartProgram> element?
Edit:
Something like:
<ItemGroup>
<Runners Include="$(MSBuildProjectDirectory)\..\..\Packages\xunit.runners.*\tools\xunit.gui.clr4.exe" />
</ItemGroup>
Will give me all runners in #(Runners), sorted by version. How can I get one of them, preferably the last one?
For filtering you can build a custom task. It can even be inline http://msdn.microsoft.com/en-us/library/dd722601.aspx, were you can write the c# code you need to loop over the items and pick the right one. Then you can expose the chosen path in an output property that you then use to set the value of the StartProgram property.
This question shows a custom inline task that gets an item array and does stuff with it. You can probably start from there.
You'll need to use this task in a target that runs before the target that initiates the debugging.
With fsimonazzi's comment I ended up with this:
<PropertyGroup>
<Package>$([System.IO.Directory]::GetDirectories("$(MSBuildProjectDirectory)\\..\\..\\Packages\\", "xunit.runners.*").GetValue(0))</Package>
<StartAction>Program</StartAction>
<StartProgram>$(Package)\tools\xunit.gui.clr4.exe</StartProgram>
<StartArguments>"$(MSBuildProjectDirectory)\$(OutPutPath)$(AssemblyName).dll"</StartArguments>
</PropertyGroup>
Apparently, NuGet will guarantee there's only one version of the package.

MSBuild - Project-specific targets for solution does not work

I have a solution that has multiple projects in it, including a web application. I want MSBuild to execute "WebPublish" target against the web application project and "default target" for all other projects in the solution.
This MSDN article says that I can do it specifying the command line
msbuild SlnFolders.sln /t:NotInSlnfolder:Rebuild;NewFolder\InSolutionFolder:Clean
But I never could make it work - MSBuild return an error, something like "NotInSlnFolder:Rebuild" target does not exist. It does not matter what target to specify, Build, Rebuild or Clean - it does not work in any case.
How can I achieve my goal of specifying project-specific targets for a solution?
The MSDN documentation does not work. Or have I missed something?
NOTE: This workaround is not officially supported by Microsoft, so there is no guarantee that it will work forever.
Short Answer
In folder with the SLN file, create the file before.{YourSolution}.sln.targets, with the following content: (Replace what in curly brackets to whatever you need.)
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="{MyCompany_MyProduct_WebApp:WebPublish}">
<MSBuild
Condition="'%(ProjectReference.Identity)' == '{$(SolutionDir)MyCompany.MyProduct.WebApp\MyCompany.MyProduct.WebApp.csproj}'"
Projects="#(ProjectReference)"
Targets="{WebPublish}"
BuildInParallel="True"
ToolsVersion="4.0"
Properties="BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"
SkipNonexistentProjects="%(ProjectReference.SkipNonexistentProjects)" />
</Target>
</Project>
After that you can execute the command line:
msbuild {YourSolution}.sln /t:{MyCompany_MyProduct_WebApp:WebPublish}
Long Answer
If you add environment variable MSBUILDEMITSOLUTION, setting its value to 1, MSBuild will not delete temporary files generated for the solution and projects.
This will allow you to find {YourSolution}.sln.metaproj and {YourSolution}.sln.metaproj.tmp files generated in the solution folder, which are just standard MSBuild project files.
For MSBuild 3.5, the generated file is {YourSolution}.sln.cache and is retained regardless of environment variables. Analyzing those files, you will understand low-level details of the process and to see the customization opportunities available.
After executing MSBuild with some project-specific target in the .Metaproj file you will find out that the list of project-specific targets is hardcoded and only standard targets are supported (Build, Rebuild, Clean, Compile, Publish; note: Publish and WebPublish are not the same). MSBuild 3.5 only generates Clean, Rebuild and Publish targets as well as a target with just the project's name that means "Build".
You also can see that NotInSlnfolder:Rebuild is just a name of an autogenerated target. In reality MSBuild does not parse it and does not care about project names and location. Also note that the autogenerated target names specify the project name with solution folders hierarchy if it's in one, e.g. SolFolder\SolSubfolder\ProjectName:Publish.
One more critically important thing you will find: The MSBuild Target Name does not support dots. All dots in project names are replaced with underscores. For example, for a project named MyCompany.MyProduct.Components you will have to specify in the command line:
/t:MyCompany_MyProduct_Components:Rebuild
That's why even standard project-specific target Build didn't work - my project name contained dots.
Analyzing file {YourSolution}.sln.metaproj.tmp, you will find out that at runtime it tries to import targets from file named before.{YourSolution}.sln.targets and after.{YourSolution}.sln.targets, if those files exist. This has a key to the workaround for this MSBuild limitation/bug.
You can open your solution file in text editor and check whether following line is exist or not if not then you can add
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> inside the <Project> tag.
Hope this help you.