Adds a build timestamp to an assembly.
File timestamps are not reliable since they can changed by various mechanisms, for example when being transferred over the wire.
Note that this is done at compile time and you will not see the code in your project.
namespace Timestamp
{
[System.AttributeUsage(System.AttributeTargets.Assembly)]
class TimestampAttribute : System.Attribute
{
public string Timestamp { get; private set; }
public TimestampAttribute(string timestamp)
{
Timestamp = timestamp;
}
}
}
[assembly: Timestamp("yyyy-MM-dd")]
So for example if you compile your assembly on the 20th of November 2013 the timestamp will be.
[assembly: Timestamp("2013-11-20")]
Note that the code that generates the timestamp uses UTC.
DateTime.UtcNow.ToString("yyyy-MM-dd")
In standard .net you can use the following
public static string RetrieveTimestamp()
{
var attribute = Assembly.GetExecutingAssembly()
.GetCustomAttributes(false)
.First(x => x.GetType().Name == "TimestampAttribute");
return (string) attribute.GetType()
.GetProperty("Timestamp")
.GetValue(attribute);
}
If you are on .net 4.5 you can make use of the AttributeType property use the below code. It will be a little faster due to less reflection.
public static string RetrieveTimestamp()
{
var attribute = Assembly.GetExecutingAssembly()
.GetCustomAttributesData()
.First(x => x.AttributeType.Name == "TimestampAttribute");
return (string)attribute.ConstructorArguments.First().Value;
}
public static DateTime RetrieveTimestampAsDateTime()
{
var timestamp = RetrieveTimestamp();
return DateTime.ParseExact(timestamp, "yyyy-MM-dd", null, DateTimeStyles.AssumeUniversal)
.ToUniversalTime();
}
Since all this happens at compile time, with no code seen by you, it is advisable to add a unit test to verify that the injection has happened.
[Test]
public void EnsureTimestampHasBeenAdded()
{
var timestamp = RetrieveTimestamp();
Assert.AreEqual(DateTime.UtcNow.ToString("yyyy-MM-dd"), timestamp);
}
Note that this test makes the assumption that the test is being run on the same day as the compilation of the target assembly. Feel free to change the tolerance of that assumption.
Nuget package http://nuget.org/packages/Timestamp
To Install from the Nuget Package Manager Console
PM> Install-Package Timestamp
Mayan Calendar designed by Arturo Alejandro Romo Escartin from The Noun Project