Adds a build timestamp to an assembly.
See Milestones for release notes.
https://nuget.org/packages/Timestamp/
PM> Install-Package Timestamp
File timestamps are not reliable since they can be 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-ddTHH:mm:ss.fffZ")]
So for example, if you compile your assembly on the 10th of September 2018 the timestamp will be
[assembly: Timestamp("2018-09-10T16:24:59.417Z")]
Note that the code that generates the timestamp uses UTC.
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
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;
}
DateTime
public static DateTime RetrieveTimestampAsDateTime()
{
var timestamp = RetrieveTimestamp();
return DateTime.ParseExact(timestamp, "yyyy-MM-ddTHH:mm:ss.fffZ", 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-ddTHH:mm:ss.fffZ"), 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