C Sharp

Using Specific Versions of Assemblies

Now let's look at another common issue with versioning. In the last part of this demo, we'll introduce an error into the equation. Create a folder called Account1002 in the Account\Business folder. In that folder, create the following Account class. Notice that this time the AccountPrint version is purposely programmed to throw an exception to simulate a nonworking update to the Account class.

// Accounting\Business\Account1002\Account.cs
using System;
using System.Reflection;
[assembly:AssemblyKeyFile("..\\..\\Account.key")]
[assembly:AssemblyVersion("1.0.0.2")]
public class Account
{
    public static void PrintVersion()
    {
        // This is purposely thrown to simulate code failure.
        throw new Exception();
        Console.WriteLine
            ("This is version 1.0.0.2 of the Account class");
    }
}

Now build this version of the Account assembly as follows: -

csc /t:library Account.cs
gacutil -i Account.dll

Running either the Personalor Businessapplications will result in the uncaught exception causing the application to abort. Here I'm simulating an all-too-common phenomenon in software deployment-the installation of something that doesn't work and that winds up breaking several other applications. In the case of the Personalapplication, we don't want to revert to safe mode because we want to run the latest working version of Account (version 1.0.0.1) and safe mode would have us working with the first version (1.0.0.0).

Once again, the answer lies in the application configuration file. Now modify the Accounting\PersonalAccounting.cfg such that its XML tags look like this: -

<?xml version ="1.0"?>
<Configuration>
<BindingPolicy>
<BindingRedir Name="Account"
                  Originator="32ab35a4550339b1"
                  Version="*"
                  VersionNew="1.0.0.1"
                  UseLatestBuildRevision="no"/>
</BindingPolicy>
</Configuration>

Note that the key specified for the Originator attribute is the one used on my system. You need to substitute the one generated when you created the Account.key file. You can locate the value needed by opening the assembly cache and locating the Account class.

Finally, run the Personal application again, and you'll see that it runs without any problems and that the Account class being used is indeed the version (1.0.0.1) that we requested.

Summary

In this chapter, I discussed the major advantages of using assemblies, including packaging, deployment, versioning, and security.

I also discussed single-file and multifile assemblies and the Assembly Generation tool (al.exe), how to create and share assemblies by using the Strong Name tool (sn.exe), and the Global Assembly Cache tool (gacutil.exe).

I also demonstrated how to control the default versioning policies used by .NET with the creation of XML-based configurations files.