Trick to run different pre/post build events when building with MSBuild or from Visual Studio IDE - visual-studio

Don't ask me why, but does anyone know any trick to put in the pre/post build event command that will run different commands if the project is being built from command line with MSBuild or from inside the Visual Studio IDE?

The easiest solution would be to define build targets that are conditioned on the $(BuildingInVisualStudio) property that visual studio sets to true when buildinging.
<Target Name="SpecialPreBuild" BeforeTargets="BeforeBuild" Condition="'$(BuildingInVisualStudio)' != 'true'">
<Exec Command="some-command.exe --magic" />
<Copy SourceFiles="foo.txt" DestinationFolder="bin\$(Configuration)\bar" />
</Target>
<Target Name="SpecialPostBuild" AfterTargets="AfterBuild" Condition="'$(BuildingInVisualStudio)' != 'true'">
<Exec Command="some-other-command.exe --magic" />
</Target>
If you want to skip these targets in other IDEs / editors as well, you could introduce a custom property as well and change the Condition attributes above to
Condition="'$(PerformSpecialLogic)' == 'true'"
That way no "default" builds will execute these targets and you could build with the following arguments in your build script / CI definition:
msbuild /p:PerformSpecialLogic=true

Related

Visual Studio Project - MSBuild Target - AfterBuild - Condition - Only When Binary File Updated

I have a long afterbuild process on my Visual Studio project file's after build target, as show below.
The issue is that it always runs the AfterBuild target when I hit build even when the actual source code has not changed and the project is not compiled.
How can I have this only run when the project has been compiled and the physical binary is written or update on the disk?
<Target Name="AfterBuild">
<Exec Command=""$(ProgramFiles)\Microsoft\ILMerge\ILMerge.exe" /copyattrs /log /target:library /targetplatform:4,C:\Windows\Microsoft.NET\Framework64\v4.0.30319 /Lib:"$(TargetDir)\" /keyfile:"$(ProjectDir)\Plugin.snk" /out:"$(TargetDir)\$(AssemblyName).merged.dll" "$(AssemblyName).dll" "PluginCommandCommon.dll" "Common.dll"" />
<Copy SourceFiles="$(TargetDir)\$(AssemblyName).merged.dll" DestinationFolder="$(ProjectDir)..\PluginPackage\bin\$(Configuration)\" />
</Target>
Option 1:
Instead of AfterBuild use AfterRebuild (one of MSBuild's many undocumented features):
<Target Name="AfterRebuild" >...</Target>
Option 2:
Hook up one of the incremental build's conditions:
<Target Name="AfterBuild" Condition=" '#(_SourceItemsToCopyToOutputDirectory)' != '' " >
UPDATE:
Using MSBuild Extension Pack's ILMerge task will allow better control, I.E check for each file existence:
<Target Name="ILMergeItems">
<ItemGroup>
<Input Include="C:\b\MSBuild.ExtensionPack.dll"/>
<Input Include="C:\b\Ionic.Zip.dll"/>
</ItemGroup>
<MSBuild.ExtensionPack.Framework.ILMerge
Condition="Exists('%(Input.FullPath)')"
InputAssemblies="#(Input)"
OutputFile="C:\a\MyNewAssembly.dll"/>
</Target>
There is a ComboBox in Properties>>Build Events>>Run the post-build event...if this is what you mean.

How to turn off caching of build definitions in Visual studio

In project file I import my own target file
<Import Project="Build\CopyDependencies.target" />
and later I call target from that target file
<CallTarget Targets="CopyDependencies" UseResultsCache="false" />
If I edit CopyDependencies.target file I have to reload whole solution and only then changes to CopyDependencies.target take effect. I believe it is some sort of build definitions caching in Visual Studio? If it is, maybe it can be turned off?
Thanks #KazR
Here is a smaller Solution that you can insert into your .csproj file
<Target Name="AfterBuild">
<PropertyGroup>
<TempProjectFile>Build.$([System.Guid]::NewGuid()).proj</TempProjectFile>
</PropertyGroup>
<Copy SourceFiles="Build.proj" DestinationFiles="$(TempProjectFile)" />
<MSBuild Projects="$(TempProjectFile)" />
<ItemGroup>
<TempProjectFiles Include="Build.????????-????-????-????-????????????.proj"/>
</ItemGroup>
<Delete Files="#(TempProjectFiles)" />
</Target>
Problem solved
I don't know how you would disable the VS cache, however I may have a workaround that would allow you to edit the build target without having to reload the solution.
You could use the MSBuild task in your proj file to call a wrapper target that copies your CopyDependencies.target file to CopyDependencies.[RandomNumber].target, then invokes your CopyDependencies target in the newly created file, and finally deletes it.
This would force VS to reload the target on each invocation as the filename is different.
Here's an example:
myProject.proj
Add this to the AfterBuild target:
<MSBuild Projects="Wrapper.target" Targets="MyWrappedTarget" UnloadProjectsOnCompletion="true"/>
Wrapper.target
Here we have the target that will - at build time - copy the real target file and invoke the desired build target within it (I've used an inline c# task which is only available in MSBuild 4.0):
<UsingTask TaskName="RandomNumber" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<Number ParameterType="System.Int32" Output="true"/>
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs">
<!-- CDATA -->
Random rndGenerator = new Random();
Number = rndGenerator.Next(Int32.MaxValue);
<!-- CDATA -->
</Code>
</Task>
</UsingTask>
<Target Name="MyWrappedTarget">
<Message Text="MyWrappedTarget target called"/>
<RandomNumber>
<Output TaskParameter="Number" PropertyName="FileNumber"/>
</RandomNumber>
<PropertyGroup>
<CopiedTarget>inner.test.$(FileNumber).target</CopiedTarget>
</PropertyGroup>
<Copy SourceFiles="inner.test.target" DestinationFiles="$(CopiedTarget)"/>
<MSBuild Projects="$(CopiedTarget)" Targets="_innerTestTarget"/>
<Delete Files="$(CopiedTarget)"/>
</Target>
inner.test.target
This contains the real build target you want to execute, in this example it's a simple file copy.
<Target Name="_innerTestTarget">
<Message Text="This is a inner test text message"/>
<Copy SourceFiles="x.txt" DestinationFiles="x1.txt"/>
</Target>
This isn't production ready, but hopefully illustrates my point.
With this (slightly convoluted) process in place, you can change the inner.test.target file without having to reload the solution in VS.
Here's a solution that doesn't require any MSBuild scripting at all.
I noticed that unloading and reloading a project doesn't get around the cache, but closing and reopening the solution does. In addition, Visual Studio will prompt you to reload the solution if it notices the .sln file has changed. And finally, this superuser question explains how to touch a file in Windows.
Putting these together, I added a Visual Studio external tool to touch the current solution file. Here's how:
Select TOOLS > External Tools ...
Click the Add button to add a new tool.
Set properties as follows:
Title: Reload Solution
Command: cmd.exe
Arguments: /c copy "$(SolutionFileName)"+>nul
Initial directory: $(SolutionDir)
and turn on Use Output window
Click OK to close the External Tools window
Now if you have made changes to your MSBuild files, just select TOOLS > Reload Solution and all your build files will be reloaded.
I'm using Windows 7 64-bit and Visual Studio 2012 Express for Windows Desktop.
I have a different solution, not involving temporary files:
Include.targets file:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Foobar">
<Copy SourceFiles="test.source" DestinationFiles="testFoobar.dest" />
</Target>
</Project>
Project file:
....
<Target Name="BeforeBuild">
<Exec Command="$(MSBuildToolsPath)\MSBuild.exe Include.targets /t:Foobar" ContinueOnError="false" />
</Target>
....
in this case VS does not recognize the MSBuild command, and does not cache the file.
happy coding!
Before running MSBuild I run this to clear the download cache:
call "%VS120COMNTOOLS%vsvars32.bat"
echo Clear download cache
gacutil -cdl

MSBuild "Debug" configuration not working in VS 2010 Beta 2

I'm trying to set up my environment for developing, debugging and deploying Windows Desktop Gadgets. I've hit a bit of a roadblock in my project, where I can't run a build on my gadget when the configuration is set to "Debug". If the configuration is set to "Release", the build goes through the following custom tasks:
Copy gadget contents to a seperate folder.
Minify/obfuscate the javascript files, removing comments and whitespace.
Package the files into a CAB file.
Sign the CAB file with a digital certificate.
This runs just fine, my "Debug" configuration has the following tasks defined
Copy gadget folder to AppData\Local\Microsoft\Windows Sidebar\Gadgets\.
Start the gadget using the IDesktopGadget interface.
If I copy those two tasks to the "Release" configuration, they run just fine - no problems whatsoever. I've tried creating a seperate configuration called "Test", copied from the "Release" configuration.
If I try to build any configuration other than "Release", I get an instant message saying "Build succeeded" but no tasks have run at all.
EDIT: I've started a bounty because I still have the same problem with VS 2010 RC and it's very frustrating.
FURTHER EDIT:
Thanks to John I was able to debug the build process. It led me to realize that the <Target> element with condition for debugging was being completely ignored (not even processed). When I swapped the position of my <Target> elements, it worked:
<Target Name="Build" Condition="'$(Configuration)' == 'Release'">
<!--
<Obfuscate PathToJasob="C:\Program Files (x86)\Jasob.com\Jasob 3.5" Path="$(GadgetFolder)" Output="$(GadgetName)_obf" log="jasob_log.txt" />
-->
<BuildGadget BuildFormat="CAB" Path="$(GadgetFolder)" Target="$(GadgetName).gadget" />
<SignGadget CertName="Cert1" TimestampURL="http://timestamp.comodoca.com/authenticode" Target="$(GadgetName).gadget" />
</Target>
<Target Name="Build" Condition="'$(Configuration)' == 'Debug'">
<CopyToGadgets GadgetFolder="$(GadgetFolder)" GadgetName="$(GadgetName)" />
<RunGadget GadgetName="$(GadgetName)" />
</Target>
So it looks like the second <Target Name="Build"> element overrides the first, despite the Condition attribute being present. What can I do?
As Joe suggests:
Change your output path like this, and see if that fixes the issue:
<OutputPath>bin\Debug\</OutputPath>
Update
Have you tried running msbuild /verbosity:diagnostic ?
Can you try that and show the output?
Second Update
Make one target 'build', and then make two tasks in that target:
<Target Name="Build">
<CallTarget Targets="BuildRelease" Condition="'$(Configuration)' == 'Release'" />
<CallTarget Targets="BuildDebug" Condition="'$(Configuration)' == 'Debug'" />
</Target>
<Target Name="BuildRelease">
<!--
<Obfuscate PathToJasob="C:\Program Files (x86)\Jasob.com\Jasob 3.5" Path="$(GadgetFolder)" Output="$(GadgetName)_obf" log="jasob_log.txt" />
-->
<BuildGadget BuildFormat="CAB" Path="$(GadgetFolder)" Target="$(GadgetName).gadget" />
<SignGadget CertName="Cert1" TimestampURL="http://timestamp.comodoca.com/authenticode" Target="$(GadgetName).gadget" />
</Target>
<Target Name="BuildDebug">
<CopyToGadgets GadgetFolder="$(GadgetFolder)" GadgetName="$(GadgetName)" />
<RunGadget GadgetName="$(GadgetName)" />
</Target>
Just a guess:
Your Debug build has its output path set to bin\Release\.
The timestamps of the files in bin\Release\ are probably causing MSBuild to conclude that the debug build is already up to date. Try changing the the output path to bin\Debug\ for debug builds.

Publish ClickOnce from the command line

Is there a way to have Visual Studio 2008 execute the "Publish Now" button from the command line?
I've seen posts that suggest to use msbuild /target:publish to call it. That is OK, but MSBuild doesn't increment the revision number. I'm hoping for something like:
devenv mysolution.sln /publish
To increment build numbers, I am using MSBuild Extension pack inside my .csproj file as follows:
<Target Name="BeforeBuild" Condition=" '$(Configuration)|$(Platform)' == 'Release-VersionIncrement|AnyCPU' ">
<CallTarget Targets="CleanAppBinFolder" />
<MSBuild.ExtensionPack.VisualStudio.TfsSource TaskAction="Checkout" ItemCol="#(AssemblyInfoFiles)" WorkingDirectory="C:\inetpub\wwwroot\MySolution" ContinueOnError="true" />
<!-- Microsoft's task that goes over assembly files and increments revision number. -->
<MSBuild.ExtensionPack.Framework.AssemblyInfo Condition="'$(Optimize)'=='True' " AssemblyInfoFiles="#(AssemblyInfoFiles)" AssemblyRevisionType="AutoIncrement" AssemblyFileRevisionType="AutoIncrement">
<Output TaskParameter="MaxAssemblyVersion" PropertyName="MaxAssemblyVersion" />
</MSBuild.ExtensionPack.Framework.AssemblyInfo>
<Message Text="----current version---: '$(MaxAssemblyVersion)'" />
</Target>
This way, anytime the configuration is set to Release-VersionIncrement, the version number is changed. When this is done, I can use the following MSBuild command to publish it:
msbuild c:\projects\MyProject.csproj
/t:ResolveReferences;_CopyWebApplication
/p:Configuration=Release;BuildingProject=true;WebProjectOutputDir=c:\inetpub\wwwroot\OutputProject\MyProjectOutput;OutDir=c:\inetpub\wwwroot\OutputProject\MyProjectOutput
Note that this is for an ASP.NET 3.5 web application.

How can we display a "step" inside Visual Studio build process?

When you are monitoring the TFS build from Visual Studio (2008 or 2005), you can see where it is up to.
The issue is that I have some Post-Build custom steps I would like the developer to be able to see directly throught the UI. Those steps take some times and we can also get a "timing" of the build step.
Any idea how to have it displayed?
This is the pattern that I normally use for adding steps to the build report in TFS 2008. (See http://code.msdn.microsoft.com/buildwallboard/ for the full example that I usually use in my Team Build talks)
Basically, the magic is that there is a custom task provided for you in TFS2008 called "BuildStep". Here is the section where I generate and MSI installer and build the appropriate build steps in the report:
<Target Name="PackageBinaries">
<!-- create the build step -->
<BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Message="Creating Installer"
Condition=" '$(IsDesktopBuild)' != 'true' " >
<Output TaskParameter="Id"
PropertyName="InstallerStepId" />
</BuildStep>
<!-- Create the MSI file using WiX -->
<MSBuild Projects="$(SolutionRoot)\SetupProject\wallboard.wixproj"
Properties="BinariesSource=$(OutDir);PublishDir=$(BinariesRoot);Configuration=%(ConfigurationToBuild.FlavourToBuild)" >
</MSBuild>
<!-- If we sucessfully built the installer, tell TFS -->
<BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Id="$(InstallerStepId)"
Status="Succeeded"
Condition=" '$(IsDesktopBuild)' != 'true' " />
<!-- Note that the condition above means that we do not talk to TFS when doing a Desktop Build -->
<!-- If we error during this step, then tell TFS we failed-->
<OnError ExecuteTargets="MarkInstallerFailed" />
</Target>
<Target Name="MarkInstallerFailed">
<!-- Called by the PackageBinaries method if creating the installer fails -->
<BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
Id="$(InstallerStepId)"
Status="Failed"
Condition=" '$(IsDesktopBuild)' != 'true' " />
</Target>
So initially, I create the build step and save the Id of the step in a propery called InstallerStepId. After I have performed my task, I set the status of that step to Succeeded. If any errors occur during the step then I set the status of that step to Failed.
Good luck,
Martin.
Note that in #Martin Woodward's great example, PackageBinaries is one of the existing TFS build targets. If you want to use your own targets, you can use the CallTarget task to call them from one of the known targets, e.g.,
<Target Name="AfterDropBuild">
<CallTarget Targets="CreateDelivery"/>
<CallTarget Targets="CreateInventory"/>
</Target>
Then in your targets (e.g., CreateDelivery) use the BuildStep task as per Martin's example.

Resources