C# version number stamping with Jenkins

Automatically stamp version number into C# assembly using Jenkins and msbuildtasks.

The following code snippet can be inserted in a vsproj file and will dynamically, at compile time, create a cs file containing version info, that will be used in the assembly.
It should be noted, that the version and description properties must be removed from the default AssemblyInfo.cs file.

The format of the version is major.minor.patch.build.

Code snippet from .vsproj file:

  <!--
     VERSION NUMBER STAMPER
  -->

  <!-- The major, minor, build and revision parts defined -->
  <PropertyGroup Condition="'$(BUILD_NUMBER)' == ''">
    <major>0</major>
    <minor>0</minor>
    <build>0</build>
    <revision>0</revision>
    <commit>?</
commit>
  </PropertyGroup>
  <PropertyGroup Condition="'$(BUILD_NUMBER)' != ''">
    <major>1</major>
    <minor>2</minor>
    <build>$(BUILD_NUMBER)</build>
    <revision>1</revision>
    <
commit Condition="'$(GIT_COMMIT)' == ''">?</commit>
    <
commit Condition="'$(GIT_COMMIT)' != ''">$(GIT_COMMIT)</commit>
  </PropertyGroup>


  <!-- Import the msbuildtasks -->
  <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')" />


  <!--
       Execute the BeforeBuild step, creating the AssemblyVersionInfo.cs file containing the version numbers.
       Both version and file version

  -->
  <Target Name="BeforeBuild" Condition="Exists('$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets')">

    <Message Text="Version: $(major).$(minor).$(revision).$(build)" />
    <Attrib Files="$(MSBuildProjectDirectory)\AssemblyVersionInfo.cs" Normal="true" />
    <AssemblyInfo
        CodeLanguage="CS"
        OutputFile="$(MSBuildProjectDirectory)\AssemblyVersionInfo.cs"
        AssemblyDescription="Git SHA: $(commit)"

        AssemblyVersion="$(major).$(minor).$(revision).$(build)"
        AssemblyFileVersion="$(major).$(minor).$(revision).$(build)" />
  </Target>

Additionally an <ItemGroup> must contain:

    <Compile Include="AssemblyVersionInfo.cs">
        <Link>AssemblyVersionInfo.cs</Link>
    </Compile>

In order to understand the existence of the file.

References

Jenkins CI
loresoft/msbuildtasks
how-can-i-auto-increment-the-c-sharp-assembly-version-via-our-ci-platform-hudso
how-can-i-change-assemblyproduct-assemblytitle-using-msbuild
msbuild-custom-assembly-version-format

Comments