Introduction to assemblies
The assembly is an important element of .NET programming. On the .NET platform, an assembly is a unit of reuse, versioning, security and deployment. In order to package and deploy our types, they must be placed into modules that are part of an assembly. Every managed application in .NET is deployed as an assembly. It means that the entire .NET code on compilation gets converted into an Intermediate Language (IL) code and gets stored as an assembly. In addition to the IL code, an assembly also contains Assembly metadata (Manifest), Type metadata and Resources. Assemblies are hence self-describing. Let us peep into the structure of an assembly.
Structure of an assembly
If an assembly is to be made up of several programs, the programs can be stored in separate modules. Suppose there are two source files ‘a.cs’ and ‘b.cs’ of which, ‘a.cs’ is stored in a module, whereas, ‘b.cs’ is stored in the assembly itself. Both comprise an assembly named ‘mydll.dll’. The structure of the assembly ‘mydll.dll’ would look as shown in the following figure.
The PE file ‘a.dll’ is said to be stored in a module of the ‘mydll.dll’ assembly. Had ‘mydll.dll’ contained resources, they would also get added in the structure with the type metadata and manifest. The ‘assembly description’ shown in manifest contains the identity of the assembly, consisting of its name, version and culture. An assembly has a four part version number e.g. 1.0.1.1. The parts are . . . . Other contents are the names of all the files in the assembly, information regarding whether all the types defined in the assembly are visible to other assemblies or private to one, a hash of all files in the assembly and details of any security permissions that clients need to have in order to be able to run the assembly.
Private and shared assemblies
We can create two types of assemblies—private assemblies and shared assemblies. A private assembly is used by only one application while a shared assembly is shared amongst different applications.
By default, when a C# program is compiled, the assembly produced will be a private assembly. This assembly (DLL/EXE) should be placed in the same folder as the calling application. With a private assembly it’s not necessary to think about naming conflicts with other classes or versioning problems because each application has its own copy of the assembly. In shared assemblies we have to ensure that the assembly is unique, and therefore, give it a unique name (called strong name).
In this article we would see how to build and use a shared assembly.
Let us write a class library consisting of a function called display( ). We will call this function from a client program, which we will create later. Here is code of the display( ) method, which is defined in the mytext class.
public class mytext
{
public void display ( Form fr, string s, Color c, string fname,
int size, Point pt )
{
Graphics g = fr.CreateGraphics();
Font myfont = new Font(fname, size);
SolidBrush mybrush = new SolidBrush(c);
g.DrawString(s, myfont, mybrush, pt);
}
}
The display() method simply draws text with the specified Font and Brush. On building the project a ‘fontassembly.dll’ file would get created in the ‘fontassembly\bin\Debug’ subfolder.
A shared assembly is always unique. To be uniquely identified, a shared assembly has a strong name. The combination of a file name, a public key, a version number and culture (locale details) gives an assembly a strong name, which is guaranteed to be unique. Now let’s first see what are public and private keys and then see how to build them.
Public keys, private keys and encryption
Encryption is the act of encoding files/programs so that others not privy to the decryption mechanism cannot understand the content of the text. Thus encryption is the process of hiding our data from anyone we feel should not be allowed to read it. Under the .NET platform this has special significance since here we distribute our IL code embedded in assemblies, instead of the executable machine code, which can potentially be deciphered without too much difficulty. .NET has a strong inbuilt mechanism to maintain the privacy of code. If this had not been the case, any one with the ILDASM.EXE utility would have an access to your code. Not only that, he or she would also have the opportunity to distribute it under his name. .NET achieves this security by public key encryption.
The public key and private keys are complementary entities; one is meaningless without the other. The creation of public and private keys is carried out by complicated mathematical algorithms. A document encrypted with one key can be decrypted only by using the other key. Not even the key with which the data was encrypted can be used to decrypt it back. The public key can be distributed freely without any fear of it being misused.
Building the keys
To build public and private keys we have to use the sn (short for strong name) utility. This utility generates a public/private key pair. The public key created using this utility will be used to define a strong name. To create the key pair we must type the following at command prompt:
C:\CSharp\fontassembly>sn –k mykey.snk
On executing the utility a file called mykey.snk gets created. This file contains the public and private keys.
To create a strong name, the compiler uses the public key from the mykey.snk file, hence we must provide this file to the compiler. To do so we would have to open the AssemblyInfo.cs file of the project. In this file we would have to set the AssemblyKeyFile attribute to the ‘.snk’ file path. The attribute must be either set to an absolute path to the key file or if the file is copied to the local directory of the project, only the file name must be mentioned. We need to add the following to the ‘AssemblyInfo.cs’ file.
[assembly: AssemblyKeyFile(“mykey.snk”)]
We should also change the version number of our assembly as shown below.
[assembly: AssemblyVersion(“1.0.1.1”)]
On rebuilding the program, the assembly would now use the public key from the mykey.snk file along with the name of the assembly, the version number and the culture to build a strong name. Culture is a combination of a two-letter word indicating the language and a two-letter word indicating the country code. The strong name never contains the private key. This ensures that the private key is not written in the manifest and hence is not made available to everybody. This strong name is written in the manifest of the assembly.
Along with the strong name, the compiler also generates a cryptographic hash from the names and contents of the files in the assembly. The compiler then encrypts the cryptographic hash for the assembly using the private key (available in mykey.snk). It places the encrypted hash in the manifest of the assembly. This hash would be used by the client to check the authenticity of the assembly.
So, in all, two things are written inside the manifest—the strong name and the encrypted hash of the names and contents of the files. The process of writing the encrypted hash value in the manifest is called ‘Signing of an assembly’. Now our shared assembly is ready. To make it available to all the clients we would have to install it in the Global Assembly Cache. All the shared assemblies available on a system are stored in the Global Assembly Cache. This store is located in the :\Windows\Assembly folder.
Installing the shared assembly
To install a shared assembly in the global cache we would have to use the Global Assembly Cache utility tool called gacutil along with the /i option. Here /i stands for install. This is what we must type at the command prompt to install the
assembly.
C:\CSharp\fontassembly\bin\Debug>gacutil /i fontassembly.dll
If the assembly is successfully installed, the following message would appear:
Assembly successfully added to the cache
Building the client
Let us now build a client that would use the assembly that we created above. To create the client select a ‘Windows Application’ project and name it as fontclient
When we click on the form, some text should be displayed at the position where we click. This can be achieved by calling the display( ) method from ‘fontassembly.dll’ in the Form1_MouseDown( ) handler. To have access to this method we have added a reference of the mytext class as a data member of the Form1 class. The Form1_MouseDown( ) handler is shown below.
private void myform_MouseDown ( object sender,
System.Windows.Forms.MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
Point pt = new Point ( e.X, e.Y ) ;
t.display ( this, “Hello”, Color.Red, “Comic Sans MS”, 30, pt );
}
}
Here we have first checked whether the left mouse button has been clicked. If so then we have called the display( ) method of the mytext class from the fontassembly assembly.
For the mytext class to become available we have added the statement using fontassembly ;. However this is not enough. We also need to add a reference to the library. To do this we should right click on ‘References’ in the Solution Explorer window and select ‘Add References’. On doing so the ‘Add References’ window would appear.
Execute the program and click on the form, a string “Hello” would appear at the point where mouse is clicked. The entire process of creation of a shared assembly is illustrated in the following figure.
--------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------
-------------------------
C# Assemblies
by Wrox Books
Features of Assembly
The assembly contains MSIL code (from the compilation of your code), resources, and the metadata (which is data that describes the assembly). The metadata defines the following, among other things:
Type information for the methods and public members in the assembly
The name of the assembly
Version information
Strong-name information
Culture that defines the client’s language and cultural preferences
A list of the files in the assembly
A list of referenced assemblies
The assembly is the file that is stored on the disk. As part of that file the metadata defines all the aspects of the assembly and the manifest is the part of the metadata that defines the assembly and its properties. The PE (Portable Executable) file contains metadata, as do all assemblies.Working with a .NET Assembly
The tool used to view the content of an assembly is the MSIL Disassembler (Microsoft Intermediate Language) and to examine any managed module, including any *.exe, *.dll, and *.netmodule. The syntax for running the MSIL Disassembler is as follows:
ildasm [options] filename [options]
To see a short version of the documentation for the ildasm utility use the /? option as in this example:
There are many types of files that are involved when building .NET assemblies:
Source code resides in files with the file extension .cs.
Managed modules are the compiled IL versions of the source code. The extension of the file that is built when making a module from source files is .net module.
Assemblies are either DLLs or .exe files containing managed modules, resources, and metadata.
Creating and Modifying a .NET Assembly
An assembly can be built using the tools supplied with Visual Studio .NET or with the language compilers (such as csc.exe) and linkers (such as al.exe) supplied with the .NET Framework. We will use the command-line tools in this chapter to build the assemblies.
When we build assemblies, they are built either as private or strongly named assemblies (strongly named assemblies are needed for shared deployment). The simplest assembly to build is the private assembly; all the files for the private assembly are deployed in the folder for the application. Private assemblies are not shared with other applications and are not added to the GAC.
The examples in will work with the following source files that will print "Hello World!" on the console for us:
Hello.cs
namespace HelloWorld
{>br>using System;
public class Hello
{
string StrHello = "Hello World!";
public Hello()
{
//empty constructor
}
public void SayHello()
{
Console.WriteLine (strHello)
}
}
}
The following is the welcome.cs source file:
welcome.cs
using system;
using Helloworld;
namespace Helloassembly
{
Public class welcome
{
Public Static Void Main()
{
Hello Welcome;
welcome = new Hello;
Welcome.SayHello();
}
}
}
Setting the /target: module compiler command-line switch will produce a module that can be used to create a multi-file assembly.
The following example builds the Hello.netmodule file:
csc /target:module Hello.cs
To reference another module to be included in the assembly use the /addmodule switch to make the type information available:
csc /addmodule:Hello.netmodule /t:module Welcome.cs
Once this command has been run, the Welcome.netmodule will be created. To finally link the modules together, you use the al.exe utility (the Assembly Linker), as in this example:
al Welcome.netmodule Hello.netmodule /main:WelcomeAssembly.Welcome.Main
/t:exe /out:Hello.exe
This command produces the Hello.exe output file from the two modules. The /main option tells the linker where to find the Main method for the application. Note that the options are case-sensitive.Strongly Named Assemblies and GAC
In order to be able to install an assembly in the GAC, it must be a strongly named assembly. The following steps are involved in creating a strongly named assembly:
1. Create a strong-name key file using the Strong Name tool (sn.exe) as in this example:
2. Add assembly attributes to one of the source files referencing the strong-name key file. The following example adds the AssemblyKeyFile and AssemblyVersion attributes to the Hello.cs source file.
3. Compile the library using the csc compiler. Use the /t:library switch to create a DLL, as in this command: csc /t:library Hello.cs
4. Install the module in the GAC using the gacutil.exe utility, as is shown here:
gacutil -i Hello.dll Microsoft (R) .NET Global Assembly Cache Utility. Version 1.0.3705.0
sn -k Hellokey.snk
using system.reflection;
[assembly: AssemblyKeyFile("WelcomeKey.snk")]
[assembly: AssemblyVersion("12.1.42.0")]
namespace Helloworld
{
using system;
public class Hello
{
string strHello = "Hello World!";
public Hello()
{
//empty constructor
}
public void SayHello()
{
Console.WriteLine(strHello);
}
}
}
Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.
Assembly successfully added to the cache
The -i switch installs the assembly, -l lists all the installed assemblies in the GAC, and -u uninstalls an assembly.
Creating and Implementing Satellite Assemblies
When you wish to localize the application (make the application customizable for different languages and cultures), it can be written in culture-neutral code (code that uses resources from an assembly rather than hard-coding the resources in the program) and distribute the localized modules in separate assemblies called satellite assemblies. The culture is made part of the assembly’s identity, as is the version. When the application searches for the proper assembly to load, that information will be used as the basis for the assembly-binding selection performed by the binding manager. The binding selection is performed at run time when the client’s locale and culture is known - the selection will pick the proper assembly (or best fit).
The object model for the assembly is the hub-and-spoke model where the main assembly (the culture- neutral or default assembly) is the hub and the culture-specific satellite assemblies are the spokes. This means you can deploy the application with the default culture first, and then incrementally add cultures. The locale is a setting that is defined on the client computer and specifies a culture that indicates the language that is spoken (English, for example) and a subculture that identifies the country the client is in (such as the United States). The locale defines the measurement system (metric or imperial) and number and date-formatting rules.
When creating the resources that will make up the satellite assembly, you should work with the naming convention suggested by Microsoft. It uses a culture/subculture string to indicate the locale; for example, for the English culture in Canada, the identifier would be en-CA, while the English culture in the United States would be en-US. When creating the resource files, the filename will be in this format: For example, a resource file with strings specific to the English culture might have any of the following names, depending on whether the resource is
English-language neutral or specific to a culture:.,resource
strings.en.resource
strings.en-JM.resource
strings.en-US.resource
To create the satellite assemblies, you will use the al.exe utility (Assembly Linker) to link your resource file to an assembly, as shown in this example:
al /t:library /embed:strings.en.resources /culture:en /out:MyApp.resources.dll
The /t option will direct al to build a library,
and the /embed option identifies the file to be linked.
No comments:
Post a Comment