MSBuild - trying to run xUnit (.net) tests - msbuild

I'm trying to set up a C# project that'll run xUnit tests when I build, so I can use them in continuous integration. I have a regular project, a class library test project using xUnit, and my test runner project. From everything I've read, it appears that I should be able to get this working by doing this in the test runner project:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Test"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
[auto-created project stuff]
<UsingTask AssemblyFile="xunit.runner.msbuild.dll"
TaskName="Xunit.Runner.MSBuild.xunit" />
<Target Name="Test">
<xunit Assembly="$(MSBuildProjectDirectory)\..\OnePageOneDb.Tests\bin\Debug\OnePageOneDb.Tests.dll" />
</Target>
</Project>
When I build my solution after a change (usually editing the .csproj file), I get this:
The "Xunit.Runner.MSBuild.xunit" task
could not be loaded from the assembly
C:\Users[myusername]\Code\OnePageOneDb\OnePageOneDb.TestRunner\xunit.runner.msbuild.dll.
Could not load file or assembly
'file:///C:\Users[myusername]\Code\OnePageOneDb\OnePageOneDb.TestRunner\xunit.runner.msbuild.dll'
or one of its dependencies. The system
cannot find the file specified.
Confirm that the
declaration is correct, that the
assembly and all its dependencies are
available, and that the task contains
a public class that implements
Microsoft.Build.Framework.ITask.
Even if I add xunit.runner.msbuild.dll and xunit.runner.utility.dll to the project in the location it refers to, I get this message. But if I build again with no changes, I consistently get this:
The "xunit" task was not found. Check
the following: 1.) The name of the
task in the project file is the same
as the name of the task class. 2.) The
task class is "public" and implements
the Microsoft.Build.Framework.ITask
interface. 3.) The task is correctly
declared with in the
project file, or in the *.tasks files
located in the
"C:\Windows\Microsoft.NET\Framework\v4.0.30319"
directory.
But I've checked all these things:
The task class in xunit.runner.msbuild.dll is Xunit.Runner.MSBuild.xunit (and xunit is lowercase in the class name).
The task class inherits from Task, which implements ITask.
So maybe there's a problem in UsingTask, but I don't know what it is.
(I also thought the problem might be that xunit.runner.msbuild.dll is targeted at .NET 2.0, and I'm using VS 2010, but I recreated the test runner project in .NET 2.0 and the problem persisted.)
Can anyone help?

You need to specify correct path to xunit.runner.msbuild.dll.
First of all, you can just set the full path and test that xunit just works as you want.
But for real environment you should specify relative path to the dll.
<UsingTask AssemblyFile="$(MSBuildProjectDirectory)\..\..\lib\xunit\xunit.runner.msbuild.dll"
TaskName="Xunit.Runner.MSBuild.xunit" />
MSBuildProjectDirectory is a reserved property and contains "the absolute path of the directory where the project file is located".
EDIT:
Try to use target by full name Xunit.Runner.MSBuild.xunit
<Target Name="Test">
<Xunit.Runner.MSBuild.xunit Assembly="$(MSBuildProjectDirectory)\..\OnePageOneDb.Tests\bin\Debug\OnePageOneDb.Tests.dll" />
</Target>

I get exactly the same error message if I have Pex and Moles installed. Everything works fine after uninstalling them.

By default building in "release" configuration triggers running xunit tests.
If you are trying to disable running xunit tests in tfsbuild pass the following build parameter.
This can be useful in the new cross platform builds where running unit tests is a separate step.
/p:RunXunitTests=false

Related

How to use YUI Compressor.Net MSBuild Task 2.3.0.0

I have tried searching the web for a solution to this problem but it seems very unclear. It sounds like people are seeing this but the solutions don't seem to work for me.
I have downloaded and installed YUICompressor.NET.MSBuild 2.3.0.0 from NuGet into my project.
I have created an MSBuild target file that closely resembles the example file included and exists as part of my .csproj file so I can run it in the AfterBuild step.
I am getting the following error everytime I try to build my VS project:
The "JavaScriptCompressorTask" task could not be loaded from the assembly SolutionDir\packages\YUICompressor.NET.MSBuild.2.3.0.0\lib\NET20\Yahoo.Yui.Compressor.Build.MsBuild.dll.
Could not load file or assembly 'Yahoo.Yui.Compressor, Version=2.3.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
My folder structure is as follows:
\Solution
\packages
YUICompressor.NET.MSBuild.2.3.0.0\lib\NET20\
\build
ProjectFile.csproj
In the csproj I have:
<UsingTask TaskName="CssCompressorTask" AssemblyFile="packages\YUICompressor.NET.MSBuild.2.3.0.0\lib\NET20\Yahoo.Yui.Compressor.Build.MsBuild.dll" />
<UsingTask TaskName="JavaScriptCompressorTask" AssemblyFile="packages\YUICompressor.NET.MSBuild.2.3.0.0\lib\NET20\Yahoo.Yui.Compressor.Build.MsBuild.dll" />
<Target Name="AfterBuild">
<ItemGroup>
<JavaScriptFiles Include="someFile.js" />
</ItemGroup>
<JavaScriptCompressorTask SourceFiles="#(JavaScriptFiles)" OutputFile="build\combined.js" DeleteSourceFiles="false" CompressionType="None" ObfuscateJavaScript="false" PreserveAllSemicolons="true" />
<JavaScriptCompressorTask SourceFiles="#(JavaScriptFiles)" OutputFile="build\combined.min.js" DeleteSourceFiles="false" CompressionType="Standard" />
</Target>
Am I missing something? Can anyone help me? Thank you.
Did you try to download version 2.3.0.0 directly from codeplex? Then make sure that the Yahoo.Yui.Compressor.Build.MsBuild.dll and Yahoo.Yui.Compressor.dll reside in the same directory. Like this I was able to make it work.
It's been a while since i've played around with the AfterBuild .. but how this works is that the the msbuild program is ran from some directory .. and therefore looks for those assembly files RELATIVE to where the msbuild is being executed from.
I'm not sure if this means the msbuild is being run from C:\program files(x86)\Microsoft Visual Studio\<whatever...>
TAKE NOTE: it's the folder/path (aka execution path) where visual studio is running the msbuild command from ... NOT where msbuild exists.
So therefore, it can't find the assemblies.
Try putting in the full path to the assemblies (just to see if that works).
eg. C:\Projects\Solution\packages\YUICompressor.NET.MSBuild.2.3.0.0\lib\NET20\Yahoo.Yui.Compressor.Build.MsBuild.dll
If it's running it from the \solution\bin directory, then you're in luck! cause then you can do ..\packages\YUICompressor.NET.MSBuild.2.3.0.0\lib\NET20\Yahoo.Yui.Compressor.Build.MsBuild.dll' (the..means: from thisbindirectory, go up one level tosolutionthen down intopackagesand then down intoYUIComp`... etc.
So the answer to your question is this: Find the location Visual Studio is running the msbuild command from, during an AfterBuild. Maybe put in some code in there to say 'write to file => current path i'm in :P'

Using NuGet PackageRestore with msbuild

I have a simple class library project (with Class1) and have enabled NuGet Package Restore for the solution.
That imports the restorepackages task into the .csproj file.
I can compile the project with
C:>msbuild myproj.csproj /t:compile
And I can call the restorepackages task successfully before adding packages with
C:>msbuild myproj.csproj /t:restorepackages
However, adding any package will cause the restorepackages task to fail with an error 3.
It seems that the NuGet task is called with a wrong working directory, and you may actually fix the behavior by removing the workingdir attribut in the NuGet.targets file, that was added to the solution.
Edit the task like this:
<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="Exists('$(PackagesConfig)')"
WorkingDirectory="$(NuGetToolsPath)" />
and remove the working dir:
<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="Exists('$(PackagesConfig)')"
/>
It seems to work as expected both from commandline msbuild and within VS2010.
Does anyone know if this change might break any tooling?
Can it be related to the issue "Package Restore's $(SolutionDir) goes too far"?
Did you check the injected SolutionDir property in your project file? It might be that the generated relative path won't point to the actual solution dir.

Preventing MSBuild from building a project in a .sln without using Solution Configurations

I want to inhibit the building of certain projects within a solution from building (within a TeamCity Build Configuration in order to optimize the speed of my Commit Build feedback if you must know).
I'm aware of the Solution Configurations mechanism but don't want to have to force lots of .sln files to end up with every permutation of things I want to be able to switch off. I have Convention based rule where I want to say "If I'm doing the Commit Build, I dont want to do the final installer packaging". (And I don't want to break it out into a separate solution).
I'd prefer not to use a solution involving find and replace in the .sln file or in a .proj file created via [MsBuildEmitSolution][1]. I'm aware of questions here which cover the out of the box solution and this slightly related question.
I see MSBuild /v:diag is saying:
2>Target "Build" in file "Z.sln.metaproj" from project "Z.sln" (entry point):
Using "MSBuild" task from assembly "Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
Task "MSBuild"
Global Properties:
BuildingSolutionFile=true
CurrentSolutionConfigurationContents=<SolutionConfiguration>
<ProjectConfiguration Project="{C83D035D-169B-4023-9BEE-1790C9FE22AB}" AbsolutePath="X.csproj" BuildProjectInSolution="True">Debug|AnyCPU</ProjectConfiguration>
<ProjectConfiguration Project="{15E7887D-F1DB-4D85-8454-E4EF5CBDE6D5}" AbsolutePath="Y.csproj" BuildProjectInSolution="True">Debug|AnyCPU</ProjectConfiguration>
</SolutionConfiguration>
So the question is:
Is there a neat way of me getting to do an XPath replace or similar to have the effect of changing BuildProjectInSolution="True" to BuildProjectInSolution="False" for Project Y above
Failing that, is there a relatively simple edit I can do within a .ccproj (An Azure 1.4 Package) or a .csproj (a general project) file to cause the effects (including triggering of dependent projects) of the project being enabled within a commandline msbuild Z.sln solution build to be nullified?
Not sure it qualifies as neat, but you can set CustomAfterMicrosoftCommonTargets to import an msbuild file to over-ride the BuildDependsOn property, pointing it to your own custom build task. Basically, by setting CustomAfterMicrosoftCommonTargets you get msbuild to import an msbuild file containing the following:
<PropertyGroup>
<OldBuildDependsOn>$(BuildDependsOn)</OldBuildDependsOn>
<BuildDependsOn>MyBuild</BuildDependsOn>
</PropertyGroup>
<Target Name="OldBuild" DependsOnTargets="$(OldBuildDependsOn)" />
<Target Name="MyBuild">
<CallTarget Targets="OldBuild" Condition="<IfIWantThis>" />
</Target>
Edit
You can use the following MyBuild target to Include/Exclude projects based on regular expressions passed in as IncludeInBuild and ExcludeFromBuild properties. (If you want complex regexes, you may fall foul of MSBuild special character escaping, but this works well enough for simple matching)
> msbuild /p:ExcludeFromBuild="Tests|Install|Azure"
<Target Name="MyBuild">
<CallTarget Targets="OldBuild" Condition="('$(IncludeInBuild)'=='' OR
'$([System.Text.RegularExpressions.Regex]::IsMatch($(MSBuildProjectFullPath),
$(IncludeInBuild),
System.Text.RegularExpressions.RegexOptions.IgnoreCase))'=='True') AND
('$(ExcludeFromBuild)'=='' OR
'$([System.Text.RegularExpressions.Regex]::IsMatch($(MSBuildProjectFullPath),
$(ExcludeFromBuild),
System.Text.RegularExpressions.RegexOptions.IgnoreCase))'=='False')" />
</Target>
You could always pass the particular projects you want to build as parameters to the MSBuild.
The MSBuild command line would look like this:
MSBuild /t:<Project Name>:Rebuild;<Another Project Name>:Rebuild
In TeamCity, you would put <Project Name>:<Target Action> in the target field in the MSBuild runner.
I add a system parameter under Parameters
Name: system.ExcludeFromBuild
Kind: System property (system.)
Value: path to your csproj

Can MS Deploy do a package and transform, but not deploy?

Using msbuild in .NET 4.0, I can build web project with the "Package" target, and it does a nice job of putting the package in a zip file. But, when I look at the web.config in there, it's not transformed, it has "$(ReplacableToken_Web_SiteConnection-Web.config Connection String_0)"
I can run the "TransformWebConfig" target and it will do the proper transform, but just in its own silo.
I can also run the "Build" target and pass the "DeployOnBuild=True;DeployTarget=MSDeployPublish" properties and it will deploy the package on my server with the proper web.config transform done.
But, if I want to manually deploy the package to the server, how do I do a "Package" with a "TransformWebConfig" so that the zip file has the final web.config in there?
If you want to skip this from happening then you need to set a property in your build. You can do this in two ways
Edit your project file
Create a .wpp.targets file
I would recommend #2. For this case create a new file in the same directory as your project file with the name {ProjectName}.wpp.targets where {ProjectName} is the name of your project. Then inside of this file you should place the following contents.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="4.0">
<PropertyGroup>
<AutoParameterizationWebConfigConnectionStrings>false</AutoParameterizationWebConfigConnectionStrings>
</PropertyGroup>
</Project>
In this case you are setting the property AutoParameterizationWebConfigConnectionStrings which tells the Web Publishing Pipeline to not insert those {} placeholders in the web.config for the connection strings.
The way we do this is by modifiying the project build to do the transform prior to packaging it up.
The Target is call TransformXml and is a part of Microsoft.Web.Publishing.Tasks.dll
In your own targets its
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll" />
But it will be included in a default VS C# build.
So
<TransformXml Source="web.config" Transform="web.release.config" Destination="$(DeployPath)\web.config" />
Does the trick for us.
Set up those paths with the right ItemGroup ("content" most likely) and make sure that target gets fired prior to the call to Package in your .csproj, and the build output will contain a "Web.config" like normal, with the right transformed values.
Alternatively (we've used this for packages that need to be everything to everyone), you can use that trick to do ALL the transforms and include each of them in the final package.
Then you call Msdeploy manually and use its skip and replace directives (forgot the technical term) to only output the right one at deploy-time
Assuming you have a web.usethisone.config in your package, that looks like
-skip:objectname=filepath,absolutepath=web\..*\.config
-replace:objectName=filepath,match=.*web\.usethisone\.config,replace=web.config

Overriding MSBuildExtensionsPath in the MSBuild task is flaky

This is already cross-posted at MS Connect:
https://connect.microsoft.com/VisualStudio/feedback/details/560451
I am attempting to override the property $(MSBuildExtensionsPath) when building a solution containing a C# web application project via msbuild. I am doing this because a web application csproj file imports the file "$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v9.0\WebApplications\Microsoft.WebApplication.targets". This file is installed by Visual Studio to the standard $(MSBuildExtensionsPath) location (C:\Program Files\MSBuild). I would like to eliminate the dependency on this file being installed on the machine (I would like to keep my build servers as "clean" as possible). In order to do this, I would like to include the Microsoft.WebApplication.targets in source control with my project, and then override $(MSBuildExtensionsPath) so that the csproj will import this included version of Microsoft.WebApplication.targets. This approach allows me to remove the dependency without requiring me to manually modify the web application csproj file.
This scheme works fine when I build my solution file from the command line, supplying the custom value of $(MSBuildExtensionsPath) at the command line to msbuild via the /p flag. However, if I attempt to build the solution using the MSBuild task in a custom msbuild project file (overriding MSBuildExtensionsPath using the "Properties" attribute), it fails because the web app csproj file is attempting to import the Microsoft.WebApplication.targets from the "standard" Microsoft.WebApplication.targets location (C:\Program Files\MSBuild). Notably, if I run msbuild using the "Exec" task in my custom project file, it works. Even more notably, the FIRST time I run the build using the "MSBuild" task AFTER I have run the build using the "EXEC" task (or directly from the command line), the build works.
Has anyone seen behavior like this before? Am I crazy? Is anyone aware of the root cause of this problem, a possible workaround, or whether this is a legitimate bug in MSBuild?
Steps to Reproduce:
1) Create a new empty solution in MSVS 2008 (Fake.sln)
2) Add a new C# web application to the solution (WebApplication1.csproj)
3) Close MSVS
4) Copy the contents of "C:\Program Files\MSBuild\" to a directory called "MSBuildExtensions" in the directory containing your solution.
5) rename the directory "C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\WebApplications" so that WebApplication1.csproj will not be able to import Microsoft.WebApplication.targets from that location.
6) Create a custom MSBuild project file called "TestBuild.proj" in the same directory as the solution. It should have the following content:
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="BuildMSBuild">
<PropertyGroup>
<MSBuildExtensionsPath>$(MSBuildProjectDirectory)\MSBuildExtensions\</MSBuildExtensionsPath>
<BuildThis>Fake.sln</BuildThis>
</PropertyGroup>
<Target Name="BuildMSBuild">
<MSBuild Projects="$(BuildThis)" Properties="MSBuildExtensionsPath=$(MSBuildExtensionsPath);" Targets="Clean" />
<MSBuild Projects="$(BuildThis)" Properties="MSBuildExtensionsPath=$(MSBuildExtensionsPath);"/>
</Target>
</Project>
7) execute "msbuild TestBuild.proj" from a MSVS command prompt (note: the build may succeed the first time, but will fail if you run more than once)
Did you try setting the environment variable MSBuildExtensionPath in the CMD prompt and then running your build?
For example:
C:\> SET MSBuildExtensionsPath=C:\My\MSBuild\Extensons
Then on this project file:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Build">
<Message Text='MSBuildExtensionsPath="$(MSBuildExtensionsPath)"' />
</Target>
</Project>
you will get the following output:
c:\Users\chuckeng\Desktop\ConsoleApplication1>"C:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe" my.proj
Microsoft (R) Build Engine Version 3.5.30729.4926
[Microsoft .NET Framework, Version 2.0.50727.4927]
Copyright (C) Microsoft Corporation 2007. All rights reserved.
Build started 6/25/2010 1:04:05 PM.
Project "c:\my.proj" on node 0 (default targets).
MSBuildExtensionsPath="C:\My\MSBuild\Extensons"
Done Building Project "c:\my.proj" (default targets).
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:00.03
This works from v4.0 as well. Although, support is generally better in v4.0 for things like this. And, v4.0 is 100% backward compatible (bugs not withstanding). So, you can build your v3.5 and prior projects with v4.0. Just select ToolsVersion 3.5.
msbuild my.proj /tv:3.5
Hope this helps...
Chuck England
Visual Studio
Program Manager - MSBuild
This is a bug in MSBuild 3.5 but it is fixed in MSBuild 4.
If you can, switch to MSBuild 4 (you still can compile your 3.5 projects), otherwise you'll have to override the property in the project file.
It works fine if you override MSBuildExtensionsPath directly in the web app .csproj file.
<PropertyGroup>
<MSBuildExtensionsPath>C:\Users\madgnome\Desktop\msbuild</MSBuildExtensionsPath>
<!-- It works too with relative path -->
<!--<MSBuildExtensionsPath>..\msbuild</MSBuildExtensionsPath>-->
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />
Don't know if this might help anyone in the future, but I was able to use the following at the top of my file and it works as I would expect in both 32 and 64 bit build environments.
<PropertyGroup>
<MSBuildExtensionsPath Condition=" '$(MSBuildExtensionsPath64)' != '' ">$(MSBuildExtensionsPath64)</MSBuildExtensionsPath>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\ExtensionPack\4.0\MSBuild.ExtensionPack.tasks"/>