Sunday, June 3, 2012

What is the process for strong naming an assembly

What is the process for strong naming an assembly ?
or
What is the purpose of strong naming tool ( sn.exe ) in .NET ?

In .NET, the assembly name usually consists of 4 parts as listed below.
1. Simple Textual Name
2. Version Number (The version number is also divided into 4 parts)
3. Culture
4. Public Key Token

If an assembly contains, all the 4 parts, then the assembly is a strongly named assembly, other wise the assembly is called as a weak named assembly. In general, when you compile any .NET application, the generated assembly by default will have the Simple Textual Name, Version Number and Culture but not the public key token. If you have to sign the assembly with a public key token, you first have to generate the key pair using key generation tool called strong naming tool (sn.exe). The generated key pair will consist of a private and a public key and are written into a key file. Key files have the extension of .snk.

We now have to associate the key file with the project, so that when we compile the project, the generated assembly is signed using the key pair. To do this, In AssemblyInfo.cs file of the project, specify AssemblyKeyFile attribute as shown below.
              [assembly: AssemblyKeyFile("MyKey.snk")]

The last and final step is to build the project which will automatically sign the assembly using the key file. This process generates the strongly named assembly.



In short, there are 3 simple steps to generate a strongly named assembly.
1. Generate the key pair using strong naming tool, SN.exe.

2. Associate the generated Key file to the project using AssemblyKeyFile, which is present in AssemblyInfo.cs file.

3. Build the project.

Once, you have strongly named the assembly, you can copy it to GAC. There are 2 ways to copy an assembly into GAC.
1. Using simple drag and drop : Drag the generated assembly into the GAC folder. Usually the path for GAC is c:\windows\assembly. On some machines this could be c:\winnt\assembly.

2. Use GAC utility : Use GAC Utility tool(gacutil.exe) as shown below in visual studio command prompt.
               gacutil.exe -i C:\MyAssembly.dll (- i stands for install)

Once, you have successfuly copied the assembly into GAC, notice the four parts of the assembly name. The culture column could be empty, indicating that the assembly is language neutral.

No comments:

Post a Comment