Saturday, September 15, 2012

How to: Insert AsemblyFileName in C# Code

Ever get burned by a cached assembly? I just did recently and it was no fun.

There is nothing worse than troubleshooting an issue you have already resolved. In my case I was working on a Custom Retention Policy and after troubleshooting for far longer than I would like to admit, I realized that when I initiated the retention policy date calculation it would work fine (this uses the W3WP.exe process) but when the Expiration Policy Timer Job ran it didn't work as expected (that timer job runs under the context of the OWSTimer.exe) so the OWSTimer had cached my code and was running old code.  I restarted the OWSTimer and just like magic all was well.

So I posed a question to myself, how can I know exactly what version of your code I am running? Sure you can right click on the assembly and check the properties there but that doesn't mean that is what the timer service is running for example. Entering a version number in your code can be a great way of ensuring that you are running the latest and (hopefully greatest) version of your code.

This is what I ended up with...this will take the AssemblyFileVersion from the AssemblyInfo.cs file:
   1: using System.Reflection;
   2: ...
   3:
   4: Version fileVersion = new Version("0.0.0.0");
   5: AssemblyFileVersionAttribute[] fileVersionAttributes = (AssemblyFileVersionAttribute[])Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true);
   6: if (fileVersionAttributes != null && fileVersionAttributes.Length > 0)
   7: {
   8:     fileVersion = new Version(fileVersionAttributes[0].Version);
   9: }
  10: string workflowVersion = "Workflow Version: " + fileVersion;
You can then take that string and output it in a ULS Log entry for example.

Next step...Use TFS to increment the AssemblyFileVersion durring the build ;)