JG Vimalan's Blog

It is all about coding!

Check actual vs. required version of the current assembly using C#

This sample code gives an idea of checking actual vs. required version of the current assembly. This will be really useful in a solution with many class libraries and their version is maintained.

   /// <summary>
  /// Check versions of assemblies.
  /// </summary>
  /// <param name=”assembly”>
  /// Assembly dependent on assemblies to check.
  /// </param>
  /// <remarks>
  /// This function checks the versions of assemblies on which the
  /// <c>assembly</c> depends. The required versions of assemblied to be
  /// checked has to be specified via custom attribute based on the
  /// <c>VersionAttribute</c> class.
  /// </remarks>
  public static void Check(Assembly assembly)
  {
   foreach (
    System.Attribute attr in Attribute.GetCustomAttributes(assembly)
   )
   {
    if (attr.GetType().IsSubclassOf(typeof(Attribute)))
    {
     ((Attribute)attr).Check();
    }
   }
  }
  /// <summary>
  /// Check actual vs. required version of the current assembly and
  /// assemblies on which the current assembly depends.
  /// </summary>
  private void Check()
  {
   Assembly assembly = Assembly.GetAssembly(GetType());
   AssemblyName assemblyName = assembly.GetName();
   string actualVersion = assemblyName.Version.ToString();
   if (actualVersion != _RequiredVersion)
   {
    throw new ApplicationException(
     “Incorrect assembly version!\r\n” +
     ”  Assembly: ” + assemblyName.Name + “\r\n” +
     ”  Actual version: ” + actualVersion + “\r\n” +
     ”  Required version: ” + _RequiredVersion
     );
   }

   // Check assemblies on which the current assembly depends.
   Check(assembly);
  }
  private string _RequiredVersion

Advertisements

October 9, 2009 - Posted by | C#.NET

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: