Embedding SVN revision number at compile time with MsBuild
If you, like me, are using Subversion as your primary Version System and want to embed the SVN revision number directly in the assembly, but don’t know how, this post will try to explain it.
What do you need?
Before proceeding any further, you would need to download the following two packages (free!)
I assume that you are familiar with MsBuild and how to work with SVN.
What is the process to follow
In the explanation I assume the build process is made out of a Build Server (Hudson, Bamboo, Team City, or others..) but exactly the same process applies if the compilation is done manually.
In the image above, I am showing two different steps:
- Developer, committing the code in the SVN repository
- In my case, a Continuous Integration server that compiles the project. Steps that the Build Service has to perform are:
- Download the latest version of the source code
- Change the AssemblyInfo.cs file with the Repository Revision number. I will show how to do this, just keep reading.
- Compile the solution.
It’s pretty much clear and simple to follow this steps.
Preprocessing the AssemblyInfo.cs in MsBuild
The main point of the whole process in the building (compilation) of the project.
The following MsBuild Target will help you with the “pre-processing”, which means, changing the AssemblyInfo.cs file before the code is compiled. In this way we are able to embed the revision number.
Two tasks are used from the MsBuild Community Tasks
so on top of your MsBuild file you would need to include the following declaration:
<UsingTask TaskName="SvnVersion" AssemblyFile="MSBuild.Community.Tasks.dll"/> <UsingTask TaskName="FileUpdate" AssemblyFile="MSBuild.Community.Tasks.dll"/>
and use this target to be executed BEFORE the main compilation.
For brevity I am including only the Target itself, as your build process could vary.
<!-- ****************************** @@ PRE-BUILD PROCESSING @@ Sets the revision version for the assemblies. *********************************** --> <Target Name="PreBuild"> <ItemGroup> <!-- find all the AssemblyInfo.cs files in the solution--> <AssemblyInfoFiles Include="$(BuildPath)\*\Properties\AssemblyInfo.cs"/> </ItemGroup> <PropertyGroup> <SVNToolPath><!--Path to the svnVersion.exe--/> </PropertyGroup> <!-- Getting the revision number from svn by using the svnVersion--> <SvnVersion LocalPath="$(BuildPath)" ToolPath="$(SVNToolPath)"> <Output TaskParameter="Revision" PropertyName="Revision"/> </SvnVersion> <Message Text="Revision: $(Revision)"/> <!--uploading the AssemblyInfo.cs files--> <FileUpdate Files="@(AssemblyInfoFiles)" Regex='(d+).(d+).(d+).(d+)' ReplacementText="$1.$2.$3.$(Revision)"/> </Target>
I believe that this is a very effective and simple way of including the revision number directly in the assembly, which makes the revision tracking simpler overall.
If you think there are other and more effective ways, please let me know!