Introduction

I was looking around for some information on how best to add the AssemblyVersion to an MVC site. In the end I thought I'd do it my self as it can't be too difficult. It wasn't and I've included how to do it in this post to help other people out.
Adding a Helper Class to MVC project
The first thing to do is add a Helper class to your existing project. I decided not to use a namespace so I didn't have to import the namespace into the View.
using System; using System.Web.Mvc; using System.Reflection; // // No Namespace // public static class VersionHelper { /// <summary> /// Return the Current Version from the AssemblyInfo.cs file. /// </summary> public static string CurrentVersion(this HtmlHelper helper) { try { System.Version version = Assembly.GetExecutingAssembly().GetName().Version; return version.Major + "." + version.Minor + "." + version.Build; } catch (Exception) { return "?.?.?"; } } }
Adding the Code to your view
Once you've added the above Html helper class you'll be able to reference the CurrentVersion() Method using intellisense.
<span>Version <%=Html.CurrentVersion() %></span>
Conclusion
That's it. You can now reference the version from anywhere in any of your views. Here is what it looks like on the default MVC project.
Also if you want the code, you can download it from here.
Made a slight modification to your code by putting it into the constructor of a Lazy object, like so.
ReplyDeleteprivate static Lazy version = new Lazy(() =>
{
try
{
System.Version version = Assembly.GetExecutingAssembly().GetName().Version;
return String.Format("{0}.{1}.{2}.{3}",
version.Major,
version.Minor,
version.Build,
version.Revision);
}
catch (Exception)
{
return "?.?.?.?";
};
});
///
/// Returns the Current Version from the AssemblyInfo.cs file.
///
public static string CurrentVersion(this HtmlHelper helper)
{
return version.Value;
}
This guarantees that the code only runs once per and not every time a page is rendered. It's a small optimization, but I figured there is no reason to calculate the same value repeatedly.
This might interest those who call their helper from a separate project and do not receive the correct version number: http://stackoverflow.com/a/2815382/41211
ReplyDeleteExcellent post.I would like to learn more about this topic.Keep sharing.
ReplyDeleteRegards,
DOTNET Training in Chennai | DOTNET course in Chennai | DOTNET Training Institute in Chennai
nice post
ReplyDeleteHi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
ReplyDeleteor Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.