You are on page 1of 9

What is an assembly?

An Assembly is a logical unit of code Assembly physically exist as DLLs or EXEs One assembly can contain one or more files The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs When you compile your source code by default the exe/dll generated is actually an assembly Unless your code is bundled as assembly it can not be used in any other application When you talk about version of a component you are actually talking about version of the assembly to which the component belongs. Every assembly file contains information about itself. This information is called as Assembly Manifest.

What is assembly manifest? Assembly manifest is a data structure which stores information about an assembly This information is stored within the assembly file(DLL/EXE) itself The information includes version information, list of constituent files etc. What is private and shared assembly? The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which encapsulates your business logic. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to your application. Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies. What is Global Assembly Cache? Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. It is located under <drive>:\WinNT\Assembly folder. How assemblies avoid DLL Hell? As stated earlier most of the assemblies are private. Hence each client application refers assemblies from its own installation folder. So, even though there are multiple versions of same assembly they will not conflict with each other. Consider following example : You created assembly Assembly1 You also created a client application which uses Assembly1 say Client1 You installed the client in C:\MyApp1 and also placed Assembly1 in this folder After some days you changed Assembly1 You now created another application Client2 which uses this changed Assembly1 You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder

Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly Now consider the case when you develop assembly that is shared one. In this case it is important to know how assemblies are versioned. All assemblies has a version number in the form: major.minor.build.revision If you change the original assembly the changed version will be considered compatible with existing one if the major and minor versions of both the assemblies match. When the client application requests assembly the requested version number is matched against available versions and the version matching major and minor version numbers and having most latest build and revision number are supplied. How do I create shared assemblies? Following steps are involved in creating shared assemblies : Create your DLL/EXE source code Generate unique assembly name using SN utility Sign your DLL/EXE with the private key by modifying AssemblyInfo file Compile your DLL/EXE Place the resultant DLL/EXE in global assembly cache using AL utility

How do I create unique assembly name? Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys are generated using a utility called SN.exe (SN stands for shared name). The most common syntax of is : sn -k mykeyfile.key Where k represents that we want to generate a key and the file name followed is the file in which the keys will be stored. How do I sign my DLL/EXE? Before placing the assembly into shared cache you need to sign it using the keys we just generated. You mention the signing information in a special file called AssemblyInfo. Open the file from VS.NET solution explorer and change it to include following lines : [assembly:AssemblyKeyFile("file_path")] Now recompile the project and the assembly will be signed for you. Note : You can also supply the key file information during command line compilation via /a.keyfile switch. How do I place the assembly in shared cache? Microsoft has provided a utility called AL.exe to actually place your assembly in shared cache. AL /i:my_dll.dll Now your dll will be placed at proper location by the utility.

Hands On... Now, that we have understood the basics of assemblies let us apply our knowledge by developing a simple shared assembly. In this example we will create a VB.NET component called SampleGAC ( GAC stands for Global Assembly Cache). We will also create a key file named sample.key. We will sign our component with this key file and place it in Global Assembly Cache. Step 1 : Creating our sample component Here is the code for the component. It just includes one method which returns a string.
imports system namespace BAJComponents public class Sample public function GetData() as string return "hello world" end function end class end namespace

Step 2 : Generate a key file To generate the key file issue following command at command prompt.
sn -k sample.key

This will generate the key file in the same folder Step 3 : Sign your component with the key Now, wee will sign the assembly with the key file we just created.
vbc sampleGAC.vb /t:library /a.keyfile:sample.key

Step 4 : Host the signed assembly in Global Assembly Cache We will use AL utility to place the assembly in Global Assembly Cache.
AL /i:sampleGAC.dll

After hosting the assembly just go to WINNT\Assembly folder and you will find your assembly listed there. Note how the assembly folder is treated differently that normal folders. Step 5 : Test that our assembly works Now, we will create a sample client application which uses our shared assembly. Just create a sample code as listed below :
imports system imports BAJComponents public class SampleTest shared sub main() dim x as new sample dim s as string="x".getdata() console.writeline(s)

end sub end class

Compile above code using :


vbc sampletest.vb /t:exe /r:<assembly_dll_path_here>

Now, copy the resulting EXE in any other folder and run it. It will display "Hello World" indicating that it is using our shared assembly.

you can also add a strong key to a project's dll. for instance if Edraw is your project in VS 2008 and its generating Edraw.dll then you can goto project properties (i.e. right click on project-> properties) then "Signing" tab, and after that check "Sign the assembly" check box. A drop down box below "Sign the assembly" checkbox will get enable "choose a strong name key file" select New in it will ask you for file name pass Edraw.snk to it. if you want the file to be password protected pass the password information to the same dialog box otherwise uncheck the "protect my key file with a password" checkbox.

This article describes how to generate a strong name for an assembly and to install a .dll file in the Global Assembly Cache. The Global Assembly Cache (GAC) enables you to share assemblies across numerous applications. The GAC is automatically installed with the .NET runtime. Components are typically stored in C:\WINNT\Assembly. In order to install an assembly in the GAC, you must give the assembly a strong (that is, globally unique) name. Actually, it is not a name but a cryptographic hash key, or signature. The strong name ensures correct component versioning, which helps to prevent components that have the same name from conflicting with each other or being incorrectly used by a consuming application. Back to the top

Requirements
The following items describe the recommended hardware, software, network infrastructure, skills and knowledge, and service packs that you need: Administrator rights to the computer on which the shared assembly is being installed Prior knowledge required: General familiarity with assemblies in .NET General familiarity with the use of tools from the command-line prompt Back to the top

Global Assembly Cache


To create a small Class Library project by using Visual Studio .NET or Visual Studio 2005, to generate a strong name, and to install the project's .dll file in the Global Assembly Cache, follow these steps: 1. Open Visual Studio .NET or Visual Studio 2005. 2. Create a new Class Library project named GAC in Visual Basic .NET or in Visual Basic 2005. 3. A strong name is needed. To generate this cryptographic key pair, use the SN Tool, which is located in the \bin subdirectory, where the .NET Framework Solution Developer Kit (SDK) is installed. The SN Tool is very easy to use. The command-line statement takes the following form: sn -k "C:\[DirectoryToPlaceKey]\[KeyName].snk" 4. For convenience, create a directory named GACDemo in C:\ so that you can easily locate the key and access the key from the command prompt. NOTE: For most users, the .NET tools are located in C:\Program Files\Microsoft.NET\FrameworkSDK\Bin. Before you type the following SN command, you may want to copy this similar path on your computer to the .NET bin directory, type cd from the command prompt, right-click to paste the path, and then press ENTER to quickly change the directory where the SN Tool is located. Type the following: sn -k "C:\GACDemo\GACkey.snk" Note In the .NET Framework 2.0, the .NET tools are located in the C:\Program Files\Microsoft.NET\SDK\v2.0\Bin folder. 5. A key is generated, but it is not yet associated with the project's assembly. To create this association, double-click the AssemblyInfo.vb file in the Visual Studio .NET or Visual Studio 2005 Solution Explorer. Add the following to the list of assembly attributes that are included in this file by default when a project is created in Visual Studio .NET or in Visual Studio 2005: <Assembly: AssemblyKeyFile("C:\GACDemo\GACKey.snk")> Compile the project by clicking CTRL+SHIFT+B. No further code is necessary at this point in order to install a .dll file in the GAC. 6. You can install the .dll file by using the Gacutil Tool or by dragging the .dll file into the appropriate directory. If you use the Gacutil Tool, you can use the following command: gacutil -I "C:\[PathToBinDirectoryInVSProject]\gac.dll" If you want to drag the file, use Microsoft Windows Explorer. Open two instances of Windows Explorer. In one, navigate to the location of the .dll file output for your console project. In the other, navigate to c:\[SystemRoot]\Assembly. Drag your .dll file into the folder. Back to the top

Complete Code Listing (AssemblyInfo.vb)


Imports System.Reflection Imports System.Runtime.InteropServices <Assembly: <Assembly: <Assembly: <Assembly: AssemblyTitle("")> AssemblyDescription("")> AssemblyCompany("")> AssemblyProduct("")>

<Assembly: <Assembly: <Assembly: <Assembly:

AssemblyCopyright("")> AssemblyTrademark("")> CLSCompliant(True)> AssemblyKeyFile("C:\GACDemo\GACKey.snk")>

<Assembly: Guid("E3492A62-5389-4286-94A3-1331CC29EA6D")> <Assembly: AssemblyVersion("1.0.*")>

Back to the top

Verification
1. Start Windows Explorer. 2. Navigate to C:\WINNT\assembly. 3. Find GAC in the list of installed .dll files.

An assembly, or a dynamic linking library (DLL), is linked to your program at run time. To demonstrate building and using a DLL, consider the following scenario: MathLibrary.DLL: The library file that contains the methods to be called at run time. In this example, the DLL contains two methods, Add and Multiply. Add: The source file that contains the method Add. It returns the sum of its parameters. The class AddClass that contains the method Add is a member of the namespace UtilityMethods. Mult: The source code that contains the method Multiply. It returns the product of its parameters. The class MultiplyClass that contains the method Multiply is also a member of the namespace UtilityMethods. TestCode: The file that contains the Main method. It uses the methods in the DLL file to calculate the sum and the product of the run-time arguments. his file contains the algorithm that uses the DLL methods, Add and Multiply. It starts with parsing the arguments entered from the command line, num1 and num2. Then it calculates the sum by using the Add method on the AddClass class, and the product by using the Multiply method on the MultiplyClass class. Notice that the using directive (Imports in Visual Basic) at the beginning of the file enables you to use the unqualified class names to reference the DLL methods at compile time, as follows:
MultiplyClass.Multiply(num1, num2); UtilityMethods.MultiplyClass.Multiply(num1, num2);

To run the program, enter the name of the EXE file, followed by two numbers, as follows: TestCode 1234 5678 To build the file MathLibrary.DLL, compile the two files Add and Mult by using the following command line.
csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs

The /target:library compiler option tells the compiler to output a DLL instead of an EXE file. The /out compiler option followed by a file name is used to specify the DLL file name. Otherwise, the compiler uses the first file (Add.cs) as the name of the DLL. To build the executable file, TestCode.exe, use the following command line:
csc /out:TestCode.exe /reference:MathLibrary.DLL TestCode.cs

The /out compiler option tells the compiler to output an EXE file and specifies the name of the output

file (TestCode.exe). This compiler option is optional. The /reference compiler option specifies the DLL file or files that this program uses.

// File: Add.cs namespace UtilityMethods { public class AddClass { public static long Add(long i, long j) { return (i + j); } } } ... // File: Mult.cs namespace UtilityMethods { public class MultiplyClass { public static long Multiply(long x, long y) { return (x * y); } } } ... // File: TestCode.cs using UtilityMethods; class TestCode { static void Main(string[] args) { System.Console.WriteLine("Calling methods from MathLibrary.DLL:"); if (args.Length != 2) { System.Console.WriteLine("Usage: TestCode <num1> <num2>"); return; } long num1 = long.Parse(args[0]); long num2 = long.Parse(args[1]);

long sum = AddClass.Add(num1, num2); long product = MultiplyClass.Multiply(num1, num2); System.Console.WriteLine("{0} + {1} = {2}", num1, num2, sum); System.Console.WriteLine("{0} * {1} = {2}", num1, num2, product);

} } /* Output (assuming 1234 and 5678 are entered as command-line arguments): Calling methods from MathLibrary.DLL: 1234 + 5678 = 6912 1234 * 5678 = 7006652 */

You might also like