Yet another developer journey ...

Yet another developer journey ...

.Net 5/6... application versioning howto

Photo by Jessica Lewis on Unsplash

.Net 5/6... application versioning howto

Dominik Schischma's photo
Dominik Schischma
·Jul 24, 2022·

1 min read

Until we switched to .net 6 from the .net framework we used a major.minor (m.xxx) versioning together with the compile/build time as build number.

Verifying the build number together with the version when has proven itself when it is coming to many builds in short time (to deploy multiple changes to multiple customers).

In .net this can be handled by the project file directly using these 2 properties:

<!--application versioning-->
<AssemblyVersion>6.6.0.3</AssemblyVersion>
<SourceRevisionId>build$([System.DateTime]::UtcNow.ToString("yyyyMMddHHmmss"))</SourceRevisionId>

Please note, not to use the old AssemblyInfo.cs as this will result in a conflict.

After this change, the correct version and 'revision' is visible in the properties of the executable. But how to retrieve it? Really, in the first minutes I was very confused... However here is the solution:

public static (string AppName, string Version, string Build) GetCSharpVersion()
{
    var entryAssembly = Assembly.GetEntryAssembly();
    if (entryAssembly == null)
        return ("itxClLogon", "0.00", "0");

    string appName = entryAssembly.GetName().Name;
    var appVersion = entryAssembly.GetName().Version;

    DateTime buildDate = DateTime.MinValue;

    const string buildVersionMetadataPrefix = "+build";
    var attribute = entryAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
    if (attribute?.InformationalVersion == null) 
        return (appName, $"{appVersion}", $"{buildDate:yyyyMMdd.HHmm}");
    var value = attribute.InformationalVersion;
    var index = value.IndexOf(buildVersionMetadataPrefix, StringComparison.Ordinal);
    if (index > 0)
    {
        value = value.Substring(index + buildVersionMetadataPrefix.Length);
        DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.None, out buildDate);
    }

    return (appName, $"{appVersion}", $"{buildDate:yyyyMMdd.HHmm}");
}

Happy coding!

 
Share this