Assemebly
We can store a GIT version hash or a time stamp in the assembly during build time and read the data later at runtime.
Example:
<!-- *.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
<Target Name="SetSourceRevisionId" BeforeTargets="InitializeSourceControlInformation">
<Exec Command="git describe --long --always" ConsoleToMSBuild="True" IgnoreExitCode="False">
<Output PropertyName="SourceRevisionId" TaskParameter="ConsoleOutput" />
</Exec>
<ItemGroup>
<!-- e.g. store in existing metadata -->
<AssemblyMetadata Include="SourceRevisionId" Value="$(SourceRevisionId)" />
<!-- or store in custom attribute -->
<AssemblyAttribute Include="My.Namespace.MyGitHashAttribute">
<_Parameter1>$(SourceRevisionId)</_Parameter1>
</AssemblyAttribute>
<!-- Also possible with timestamp -->
<AssemblyMetadata Include="BuiltAt" Value="$([System.DateTime]::UtcNow.ToString('yyyy-MM-dd HH:mm:ss'))" />
</AssemblyAttribute>
</ItemGroup>
</Target>
</Project>
This data get stored in the build assembly. e.g:
// ...
using System;
using System.Reflection;
// Metadata
[assembly: System.Reflection.AssemblyMetadata("SourceRevisionId", "someHash")]
// Custome attribute
[assembly: My.Namespace.MyGitHashAttribute("someHash")]
// Timestamp
[assembly: BuildDateAttribute("20230330140538")]
// We could also use the existing one
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+someHash")]
[assembly: System.Reflection.AssemblyCompanyAttribute("MyApp")]
// ...
// Generated by the MSBuild WriteCodeFragment class.
We can then read it from the assembly during runtime.
// define custom attribute if chosen that way
public class MyGitHashAttribute : Attribute
{
public string Hash { get; }
public GitHashAttribute(string hash)
{
Hash = hash;
}
}
// usage at runtime
var hash1 = Assembly.GetEntryAssembly().GetCustomAttributes<AssemblyMetadataAttribute>.FirstOrDefault().Value;
var hash2 = Assembly.GetEntryAssembly().GetCustomAttribute<MyGitHashAttribute>().Hash;
var hash3 = Assembly.GetEntryAssembly().GetCustomAttribute<BuildDateAttribute>().Date;