Adding a File to the Compile ItemGroup
Saturday 22 July 2006
I've finally got round to switching from NAnt to MSBuild for building XML-RPC.NET so I'm tentatively finding my way around MSBuild at the moment. One thing I wanted to do was to ensure that builds of the XML-RPC.NET assembly do not have a valid version number when built from within the Visual Studio IDE, so they don't get confused with proper builds. I use a file called AssemblyBuildNumber.cs, created during a build, to define the build number so I wanted to exclude that from builds within the IDE.
My first attempt was to add a condition to the entry for the file in the Compile item group in the project file:
<ItemGroup>
<Compile Include="AssemblyBuildNumber.cs"
Condition="'$(BuildingInsideVisualStudio)' == ''">
<SubType>Code</SubType>
</Compile>
...
However, although this works from a build point of view, it results in the file being flagged as missing in the IDE Solution Explorer window. So I found a way of adding the file to the Compile ItemGroup at build time by overriding the BeforeBuild target. If you look in the Microsoft.Common.Targets file (located in %windir%\Microsoft.NET\Framework\v2.0.50727) you can see that this target is defined solely for being overidden:
<!--
=====================================
BeforeBuild
Redefine this target in your project in order to run tasks just before Build
=====================================
-->
<Target Name="BeforeBuild"/>
In the overriding version of BeforeBuild I used the CreateItem task to add the required file to the Compile item group but only if the build is not from within the IDE:
<Target Name="BeforeBuild">
<CreateItem Include="AssemblyBuildNumber.cs"
Condition="'$(BuildingInsideVisualStudio)' == ''">
<Output TaskParameter="Include" ItemName="Compile"/>
</CreateItem>
</Target
Of course, I'm new to MSBuild and I may well be missing a blatantly obvious one-liner to do this. If there is, please email me and I'll post an update here.