You are on page 1of 22

Crystal Reports

In .net when you want to create reports, crystal reports is used. Crystal reports is a reporting tool
actually created by Seagate and now it is under the control of Business Objects. Crystal reports is
integrated with .net and it is also available as a separate software. Current version of crystal reports is
11i. crystal report file has the extension .rpt. To add a crystal report to the project, right click on
project in solution explorer and choose add new item. Within the new item dialog box, select
CrystalReport, provide a name to the report and click on add button. This will add a crystal report to
the project and crystal report gallery will be displayed. Within the gallery select Using the Report
Wizard and Standard report expert and click on ok button to start crystal report wizard.

Creating A Simple Crystal Report


To create a simple crystal report that retrieves data from single table, won’t group the data, you have to
follow the following steps.
1. Create a connection to the database and select table from which you want to retrieve data for
the report. To create a connection to the database, expand Create New Connection in
Available DataSources and then expand OLEDB that displays a list of OLEDB providers.
Select a provider for your database, provide connection string information to connect to the
database and click on finish button. To select a table, expand the connection, user and then
tables, select a table and click on button with the caption ” >” to add it to selected tables list
and finally click on next button.
2. Select the columns in table to be displayed in the report and click on next button.
3. Select the columns on which you want to group the data in report. If you don’t want to group the
data then click on next button without selecting a column.
4. When you are not selecting a column for grouping the data then next step is to specify record
selection condition. If you want to display every record from the table, then click on next button
without specifying a condition.
5. Select a style for your report and click on finish button.

A crystal report contains the following 5 sections.


1. Report Header : Displayed at the top of first page in the report.
2. Page Header : Displayed at the top of every page in the report.
3. Details : Displays the data retrieved from the table.
4. Page Footer : Displayed at the bottom of every page in the report.
5. Report Footer : Displayed at the bottom of the last page in the report.

Creating Crystal Report From Multiple Tables


To create a crystal report from more than one table, follow the following steps.

1. Create a connection to the database, select the tables from which you want to create the report
and click on next button.
2. Specify the relationship between tables for join and click on next button.
3. Select the columns in table to be displayed in the report and click on next button.
4. Select the columns on which you want to group the data in report. If you don’t want to group the
data then click on next button without selecting a column.
5. When you are not selecting a column for grouping the data then next step is to specify record
selection condition. If you want to display every record from the table, then click on next button
without specifying a condition.
6. Select a style for your report and click on finish button.

Grouping Data In Crystal Report


To group data in crystal report, follow the following steps.

1. Create a connection to the database, select the tables from which you want to create the report
and click on next button.
2. Specify the relationship between tables for join and click on next button.
3. Select the columns in table to be displayed in the report and click on next button.
4. Select the columns on which you want to group the data in report and click on next button.
5. Select the columns on which you want to calculate summaries at the end of every group in the
report and click on next button.
6. Select whether to display every group or only top 5 groups or only bottom 5 groups and click on
next button.
7. Select a chart type if you want to create a chart for the report and other wise click on next button
by selecting NoChart.
8. Specify record selection condition to filter the records. If you want to display every record from
the table, then click on next button without specifying a condition.
9. Select a style for your report and click on finish button.

A crystal report contains the following 7 sections when data is grouped within the report.
1. Report Header : Displayed at the top of first page in the report.
2. Page Header : Displayed at the top of every page in the report.
3. Group Header : Displayed at the top of every group in the report.
4. Details : Displays the data retrieved from the table.
5. Group Footer : Displayed at the bottom of every group in the report.
6. Page Footer : Displayed at the bottom of every page in the report.
7. Report Footer : Displayed at the bottom of the last page in the report.

Creating CrossTab Report


If a table itemsales is as follows

Item Month Sales


RAM JAN 100000
RAM FEB 50000
RAM MAR 100000
MB JAN 200000
MB FEB 150000
MB MAR 150000
HD JAN 300000
HD FEB 200000
HD MAR 170000

Then the crosstab report for this table may look as follows.

RAM MB HD Total
JAN 100000 200000 300000 600000
FEB 50000 150000 200000 400000
MAR 100000 150000 170000 420000
Total 250000 500000 670000 1420000

To create a crosstab report for the above table follow the following steps.

1. Create a connection to the database and select table itemsales and click on next button.
2. Select the column item into columns list, column Mon in to Rows list and the column sales into
summary list and click on next button.
3. Select a chart type if you want to create a chart for the report and otherwise click on next button
by selecting nochart.
4. Specify a record selection condition to filter the records. If you don’t want to filter the records,
then click on next button without specifying a condition.
5. Select a style for the report and click on finish button.

Displaying The Report


To display a crystal report, you have to use CrystalReportViewer control. This control has a property
ReportSource. Use this property to specify the path of the crystal report file you want to display. In
general crystal report files are placed in same folder as exe file of the project, so that it is easy to get
the path of report files to display.

Dynamically Filtering Data in Report


To dynamically filter the data in a crystal report, use SelectionFormula property of
CrystalReportViewer control. Just before displaying the report, display a form to accept the values
required for condition for filtering data in report and write the condition using SelectionFormula
property. To refer to a column of the table in selectionformula, you have to write it as
{TableName.ColumnName}. while writing the condition on character column, enclose the value in
single quotes(‘) and while writing the condition on date column, enclose the date value in # symbols.
Setup And Deployment
After project development is completed, you have to create setup and provide the setup to the client on
a CD or website so that client can install it. This process of creating setup and making it available on a
CD or website is called as setup and deployment. To create setup for your project, follow the following
steps.
1. Open the project for which you have to create setup in visual studio.net
2. Add a new project to same solution as your project by selecting setup project template in new
project dialog box.
3. setup project contains FileSystem that by default contains three folders, Application Folder,
Users Desktop and Users Programs Menu.
4. Application Folder is used to specify the files to be copied to the application folder of your
project during installation. Following files have to be added to application folder.
a. Exe file and other dependent files required for the project. For this right click within
the application folder and choose add project output. This displays a dialog box. In this
dialog box select every option and click on ok button.
b. DLL files of Private Assemblies. For this right click within the application folder and
choose Add Assembly option. This displays a dialog box. In this dialog box select the
DLL file of private assembly referred by your project and click on open button.
c. Report Files. In general the reports created in project will be placed in same folder as
exe file of the project. As exe file is in application folder, report files must also be
included in application folder. For this right click in the application folder and choose Add
File option. In the open file dialog box select the report files and click on open button.
d. Database files of Desktop Databases. Similar to report files, database files related to
desktop databases like MS Access will also be placed within the same folder as exe file
of the project. For this also right click in application folder and choose Add File option.
5. Users Desktop folder is used to specify the shortcuts to be created on desktop during
installation. To create a shortcut for exe file of the project, right click within users desktop folder
and choose Create Shortcut option. This displays a dialog box. In this dialog box open
Application Folder, select Primary Output and click on ok button, provide a name to the
shortcut and press enter.
6. Users Programs Menu folder is used to specify the shortcuts to be created in programs in start
menu. To create a folder for your project in programs menu, right click on users programs menu
folder and choose Add Folder option, provide a name to it and press enter. After creating a
folder to add a shortcut for exe file of the project, right click in the folder and choose create
shortcut option and follow the same procedure as in case of users desktop.
7. For the filesystem of setup project, you can add additional folders like System, Program Files,
Windows, Font and Global Assembly Cache. To add any of these folders to file system, right
click on File System on Tatget Machine in File System and choose Add Special Folder
followed by the folder you want to add.
8. System, Program Files and Windows folders are used specify the files related to your project
that have to be copied to these folders on target system. To add files to these folders, right click
within the folder and choose Add File option.
9. Font folder is used to specify the font files to be copied to fonts folder on target machine. When
you use special fonts in your project then those font files must be available on target machine.
To add font files to the Font folder, right click within the font folder and choose Add File option.
10. Global Assembly Cache folder is used to specify the DLL files of shared assemblies referred
by your project so that they are automatically placed in GAC during installation. To add DLL files
of shared assemblies to GAC folder, right click within the GAC folder and choose Add
Assembly option. In the dialog box displayed, select the DLL file and click on open button.
11. Along with file system, setup project also contains Registry, File Types, User Interface,
Custom Actions and Launch Conditions along with File System. All these can be opened by
right clicking on setup project in solution explorer and choosing view option.
12. Registry is used to specify any entries you want to add to the windows registry related to your
application.
13. File Types is used to specify any new file extensions introduced with your application so that
they are identified and automatically opened in your application when user double clicks on that
file as a file with extension .Doc is automatically opened in MS Word.
14. User Interface is used to specify the screens to display during installation and images and
options to provide on these screens.
15. Custom Actions is used to specify any custom actions you want to perform during installation
like accepting a product key.
16. Launch Conditions is used to specify the minimum system requirements to install your
application.
17. Finally open configuration manager by right clicking on solution in solution explorer and then
choosing configuration manager. Within configuration manager set configuration for both the
projects to Release and check the check box under build and close the configuration manager.
18. Build the solution using the shortcut Ctrl + Shift + B to complete the creation of setup. Setup will
be created within the same folder as your project.
Windows Control Library
Windows control library is used to create a windows control that can be used in windows
applications. A windows control can be created in three ways.
1. Extending Existing Control
2. Composite Control
3. Creating From Scratch

1. Extending Existing Control : in this method, a new control is created by adding your own
properties, methods and events to an existing control. The following example creates a new control by
extending text box control by adding two properties to it, EnterColor and RestrictTo. EnterColor is
used to specify the background color for the text box when it has focus and RestrictTo property is used
to specify whether to restrict the text box to only Alphabets, only Digits, both Alphabets and digits.

Example :
1. Create a new project by selecting windows control library project template and by specifying
the name as MyTextBox.
2. Open the properties of user control and set its Name property to MyTextBox.
3. Open User control’s .Designer.Vb file and change the base class of user control class from
usercontrol to TextBox.
4. Compile the application with the shortcut Ctrl + Shift + B and delete all the statements that
cause error. This is because base class is changed.
5. Open the code window of user control and create a property with the name EnterColor as
follows.

Color EColor;
public Color EnterColor
{
get { return EColor; }
set { EColor = value; }
}

6. To provide functionality for the property EnterColor, write the following code in Enter and
Leave events of the user control. Because background color has to be changed whenever it got
focus and lost focus.

private void MyTextBox_Enter(object sender, EventArgs e)


{
this.BackColor = EColor;
}
private void MyTextBox_Leave(object sender, EventArgs e)
{
this.BackColor = Color.White;
}

7. To create the property RestrictTo, we have to create an enumeration and is created with the
name Restrictions as follows.

public enum Restrictions


{
None,
Alphabets,
Digits,
Both
}

8. Create the property RestrictTo as follows.

Restrictions Restrict;
public Restrictions RestrictTo
{
get { return Restrict; }
set { Restrict = value; }
}

9. Write the following code in KeyPress event of the user control to provide functionality for the
property RestrictTo.

private void MyTextBox_KeyPress(object sender, KeyPressEventArgs e)


{
switch (Restrict)
{
case Restrictions.Alphabets:
if (char.IsLetter(e.KeyChar) == false && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
}
break;
case Restrictions.Digits:
if (char.IsDigit(e.KeyChar) == false && e.KeyChar != (char)Keys.Back)
{
e.Handled = true;
}
break;
case Restrictions.Both:
if (char.IsLetterOrDigit(e.KeyChar) == false && e.KeyChar !=(char)Keys.Back)
{
e.Handled = true;
}
break;
}
}
10. Change the solution configuration to Release from solution configuration combo box in toolbar
and compile the application using shortcut Ctrl + Shift + B to generate a DLL file within the
release folder of bin folder of the project.

Using Windows Control Created Using Windows Control Library


To use the windows control created using windows control library, first you have to add it to the toolbox.
Once it is added to the toolbox, you can use it same as other controls. To add it to the toolbox, right
click on toolbox and choose ChooseItems that open a dialog box. Within the dialog box click on
browse button, select DLL file of your control and click on open button followed by ok button.

Composite Control
Creating a new control from multiple existing controls is called as composite control. The following
example creates a new control that can accept user name, password and allow the user to login.

Example :
1. Create a new project by selecting Windows Control Library project template and by specifying
the name as Security.
2. Within the properties of User control change its name to Security and design it with two labels,
two text boxes and two button controls.

3. While designing the user control, place all controls to the top left corner of the user control and
resize the user control to occupy only those controls so that it will not occupy more space on the
form.
4. Write the following code in Resize event of the user control to restrict the user from resizing the
control.

private void UserControl1_Resize(object sender, EventArgs e)


{
this.Width = TxtUname.Left + TxtUname.Width + 5;
this.Height = BtnLogin.Top + BtnLogin.Height + 5;
}
5. Create two properties UserName and Password as follows to provide access to Text boxes
TxtUname and TxtPwd.
public string UserName
{
get { return TxtUname.Text; }
set { TxtUname.Text = value; }
}
public string Password
{
get { return TxtPwd.Text; }
set { TxtPwd.Text = value; }
}

6. Create two events LoginClick and CloseClick as follows to provide access to the buttons
BtnLogin and BtnClose.

public event EventHandler LoginClick;


protected void OnLoginClick(object sender, EventArgs e)
{
LoginClick(sender, e);
}
private void BtnLogin_Click(object sender, EventArgs e)
{
OnLoginClick(sender, e);
}

public event EventHandler CloseClick;


protected void OnCloseClick(object sender, EventArgs e)
{
CloseClick(sender, e);
}
private void BtnClose_Click(object sender, EventArgs e)
{
OnCloseClick(sender, e);
}

7. Change the solution configuration to Release from solution configuration combo box in toolbar
and compile the application using shortcut Ctrl + Shift + B to generate a DLL file within the
release folder of bin folder of the project.

Creating From Scratch


Creating a new control from scratch is to completely design the control on your own using 3D
graphics available in .net and creating every property, method and event on your own. This is very
difficult process and in general in real time only first two methods are used.
Windows Services
A windows service is a windows application that runs in the background of windows without visible to
the user. For example, antivirus is a windows service. After antivirus is installed in the system, it will run
in the background of windows without visible to the user and when a file containing virus is copied to the
system, then gives a warning message about virus. In the same way when a pen drive is connected to
the system, then it is automatically detected, required drivers are installed and creates a drive to access
the files in pen drive and all this is done by a windows service.

When you want to create your own windows service, then windows service template is used while
creating the project. A windows service project contains a service that is inherited from ServiceBase
class that is available within the namespace System.ServiceProcess. ServiceBase class contains
overridable methods OnStart(), OnStop(), OnPause(), OnContinue() and OnShutDown() that can be
overridden in your service. The code written in these methods will be automatically executed when the
service was started, stopped, paused, continued and shutdown.

FileSystemWatcher
FileSystemWatcher component is used to monitor a folder and raise events when a change was made
to the specified folder. It is invisible at runtime and is available in components tab of the toolbox. It has
the following important properties.

Sno Property Name Description


1 EnableRaisingEvents Indicates whether filesystemwatcher raises events
when a change was made to specified folder.
2 IncludeSubDirectories Indicates whether to monitor subdirectories in
specified folder.
3 Path Used to specify the path of the folder to monitor.

FileSystemWatcher has the following important Events.

Sno Event Name Description


1 Created Will be raised when a new file/folder was created
2 Renamed Will be raised when a file/folder was renamed
3 Deleted Will be raised when a file/folder was deleted.
Example : The following example creates a windows service that monitor a folder “MyFolder”
available in “D” Drive and writes entries to a text file whenever a change was made to that
folder.

1. Create a new project by selecting Windows Service template in new project dialog box and by
specifying the name as MyService and within the properties of the service change Name and
ServiceName properties to MyService.
2. Place a FileSystemWatcher component on the service and change its name to Fsw.
3. Within the code add the reference to System.IO namespace and then create a FileStream and
StreamWriter as follows.

static FileStream Fs;


static StreamWriter Sw;

4. Write the following code within OnStart method of the service.

protected override void OnStart(string[] args)


{
Fs = new FileStream(@"D:\MyService.Txt", FileMode.OpenOrCreate,FileAccess.Write);
Sw = new StreamWriter(Fs);
Sw.BaseStream.Seek(0, SeekOrigin.End);
Sw.WriteLine("MyService Started At " + DateTime.Now.ToString());
Sw.Flush();
}

5. Write the following code within OnStop method of the service.

protected override void OnStop()


{
Sw.BaseStream.Seek(0, SeekOrigin.End);
Sw.WriteLine("MyService Stopped At " + DateTime.Now.ToString());
Sw.Flush();
Sw.Close();
Fs.Close();
}

6. Write the following code within OnPause and OnContinue methods of the service.

protected override void OnPause()


{
Fsw.EnableRaisingEvents = false;
}
protected override void OnContinue()
{
Fsw.EnableRaisingEvents = true;
}
7. Write the following code in Created event of File System Watcher.

private void Fsw_Created(object sender, FileSystemEventArgs e)


{
Sw.BaseStream.Seek(0, SeekOrigin.End);
Sw.WriteLine("A New File/Folder " + e.FullPath + " Was Created On " +
DateTime.Now.ToString());
Sw.Flush();
}

8. Write the following code within Renamed event of the File System Watcher.

private void Fsw_Renamed(object sender, RenamedEventArgs e)


{
Sw.BaseStream.Seek(0, SeekOrigin.End);
Sw.WriteLine("A File/Folder Was Renamed From " + e.OldFullPath + " To "
+ e.FullPath + " On " + DateTime.Now.ToString());
Sw.Flush();
}

9. Write the following code within Deleted event of the File System Watcher.

private void Fsw_Deleted(object sender, FileSystemEventArgs e)


{
Sw.BaseStream.Seek(0, SeekOrigin.End);
Sw.WriteLine("A File/Folder " + DateTime.Now.ToString() + " Was Deleted
On " + DateTime.Now.ToString());
Sw.Flush();
}

10. Add installer to the windows service by right clicking on design of the service and choosing Add
Installer. This will add two components ServiceInstaller and ServiceProcessInstaller to the
windows service.

11. ServiceInstaller is used to install the windows service and for this set the following two
properties.
DisplayName : MyService
StartType : Automatic

12. ServiceProcessInstaller is used write entries to windows registry and for this set the following
property.
Account : LocalSystem

13. Change the Solution Configuration to Release and build the solution using the shortcut Ctrl +
Shift + B to generate an exe file for the project in release folder of bin folder of the project.
Installing Windows Service
To install the windows service, use the command line tool installutil that has the following syntax.

Installutil /i pathofexefileofservice

To uninstall the windows service use the following syntax of installutil command line tool.

Installutil /u pathofexefileofservice
MultiThreading
The process of executing more than one task at a time is called as multi tasking. Operating systems like
windows and linux are multi tasking operating systems as they can execute more than one task at a
time. An application can also execute multiple tasks at a time and an example for this is MS Word. In
MS Word, while typing the document, in the background it performs other tasks like spelling and
grammar, autocorrect and autotext. Multi tasking is possible only with multithreading. Most of the PCs
contain only one processor that can execute only one task at a time. But with multi tasking multiple
tasks are executed at a time and it is possible only with timesharing concept.

When you want to perform, multiple tasks at a time in a .net application, then you need to create one
method for every task you have to perform, create one thread for every method and start all the threads
at a time. All the classes required to implement multithreading are available in the namespace
System.Threading. This namespace provides a class Thread using which you can create a thread.
Thread class has Start() method that is used to start a thread. Constructor of the Thread class takes
address of the method to be executed by the thread as argument.

Suspending A Thread
While working with multiple threads, sometimes you may want to suspend a thread. To suspend a
thread, Thread class provides two methods, Sleep() and Join(). Sleep() method is used to suspend a
thread for specified interval of time. This method is a shared method and it takes one argument i.e. the
time interval in milliseconds for which the thread has to be suspended.

Join() method is used to suspend a thread until another thread completes its task. For example, if two
threads A and B are executing and you want to suspend thread B until thread A was completed, then
within the method executed by thread B , write the statement A.Join(). Join() method is an instance
method and it doesn’t take any arguments.

Aborting A Thread
When you want to completely stop executing a thread without completing its task, then call the Abort()
method of the thread. Abort() method is an instance method and it doesn’t take any arguments.
Thread Priority
While creating multiple threads in the application, sometimes you may want to give more priority for a
particular thread and to specify priority for a thread, Priority property of the thread is used and to set a
value to this property, ThreadPriority enumeration is used and has the following values.
ThreadPriority.AboveNormal
ThreadPriority.BelowNormal
ThreadPriority.Highest
ThreadPriority.Lowest
ThreadPriority.Normal
Assemblies
In visual studio 6.0, application deployment is based on DLL files and this DLL based deployment has
the following drawbacks that are called as DLL hell.

1. Side by side execution of two different versions of same component on a system is not possible.
Because DLL file doesn’t contain version information and when you install a new version, it
automatically overwrites the old version.
2. To use a DLL based component, you must first register in windows registry and it is not possible
to use a DLL based component directly from a CD or network resource. Hence it is not possible
to use DLL based components on other operating systems.

To eliminate the drawbacks of DLL based deployment, in .net Assembly based deployment was
introduced. An assembly contains version information. Hence during the installation of a new version, it
will not overwrite the old version and hence you can run two different versions of a component on a
system side by side. You can use an assembly directly from a CD or network resource without
registering it in windows registry. Another advantage of assemblies is they will be loaded in to memory
as and when required and not every time the .net application was run. Hence memory resources can be
efficiently managed with assemblies.

The fundamental building block of a .net application is an assembly. An assembly will contain metadata
i.e. that data about the assembly, application’s MSIL code and object types available within the
assembly. When we are creating a .net application using either vb.net or C#.net, assembly will be
created in the form of a single portable executable(PE) file, specifically an exe or dll.

An assembly may be a single module assembly or multi module assembly. A project may be divided in
to modules and each module may be developed by a separate developer and finally all these modules
are combined in to a single assembly. By default VS.net will create single module assemblies and it is
not possible to create multi module assemblies from VS.net. To create a multi module assembly,
command line tools vbc.exe, csc.exe or AL.exe is used. Advantages of multi module assemblies are
1. A big portion of unused code can be separated in to a module so that it will never be loaded in to
memory.
2. When a project is divided in to modules, developer of one module may be interested in VB.net
while another developer in C#.net. This is possible only with multi module assemblies.
In a multi module assembly, there will be one main module, which will be taken in to consideration by
the CLR. This main module will contain references to other modules and resource files in the assembly.
Main module will be saved with the extension .exe or .dll and other modules in the assembly will be
saved with the extension .netmodule.

Resource Files
Along with the modules, an assembly can also contain resources like bitmaps and xml documents.
These resources can be directly embedded in to assembly or can be stored in a file and can be
referenced by the assembly. Relationship between assembly, module and resource files is represented
using UML diagram as follows.

1..* 1..*
.Net Type
1..* 1..* Module
* *

Assembly 1..* 1..* Resource


* *
Resource File

Creating Multi Module Assemblies


The following example creates one module in vb.net and one module in c#.net and both are combined
to form a single module assembly.
1. Open notepad and type the following code in vb.net syntax and save it with the name Main.vb in
D:\.

Namespace Test
Module Module1
Sub Main()
Console.WriteLine(“From Main Module”)
Dim C as new Class1
Console.WriteLine(C.ToString())
End Sub
End Module
End Namespace

2. Within notepad write the following code in c# syntax and save it with the name CsModule.Cs in
D:\.
Namespace Test
{
Class Class1
{
Public override string ToString()
{
Return “From CS Module”;
}
}
}

3. Compile the module created in c# CsModule.Cs *to CsModule.Netmodule with the help of the
command line tool CSC.exe as follows at the command prompt.

CSC /target : module D:\CsModule.Cs

4. Copy the CsModule.Netmodule to D:\


5. Compile the Main.vb file by adding CsModule.Netmodule with the help of VBC.exe file as
follows at command prompt to generate Main.exe file.

VBC /addmodule : D:\CsModule.Netmodule D:\Main.vb

The Main.exe is now a multi module assembly that contains two modules, one created in vb.net and
another created in c#.

Structure of Module in An Assembly

Main Module

PE CLR MSIL
Header Header Manifest Metadata Resources
code

Sub Module

PE CLR MSIL
Header Header Metadata Resources
code
PE Header : Contains smallest windows version on which the assembly can be executed.
CLR Header : Contains the version of CLR for which assembly was targeted.
Manifest : This is available only in main module of the assembly and it Contains references to sub
modules and resource files available in the assembly.
Metadata : Contains classes, structures, enumerations, interfaces and delegates created in the
assembly and it doesn’t contain any code of these members.
MSIL Code : Contains MSIL code for the members of classes, structures, enumerations, interfaces and
delegates that available in assembly.
Resources : Contains any resources that are embedded in to the module and this section is optional.

Observing the Contents of An Assembly


To open and see the contents of an assembly, you can use the command line tool ildasm.exe
(Intermediate Language Disassembler). Type the command ildasm at the command prompt that
opens ildasm window. In this window in file menu choose open, select the exe or dll file in open file
dialog box and click on open button, which will open the assembly in ildasm.

Types of Assemblies
Assemblies are classified in to private assemblies, shared assemblies and satellite assemblies.
Another classification of the assemblies is static and dynamic assemblies. Static assembly is an
assembly whose reference is added to the project at design time it self and dynamic assembly is an
assembly whose reference is added to the project at runtime i.e. during execution of the project.

Private Assemblies
An assembly that is private to one particular application is called as private assembly. When an
assembly is a private assembly, referred by three different .net applications and all these applications
are run at a time then three different copies the private assembly will be loaded in to memory, one for
each application. This wastes the memory resources.
Shared Assemblies
An assembly that is shared by more than one application is called as shared assembly. When an
assembly is shared assembly, referred by three different .net applications and all these applications are
run at a time then only one copy of the assembly is loaded in to memory and is shared by all three
applications. This saves the memory resources. By default every assembly created in .net is a private
assembly. To convert a private assembly to shared assembly, the following two steps have to be
followed.
1. Signing the assembly
2. Placing assembly in Global Assembly Cache (GAC)
Signing the Assembly
When an assembly is associated a with a strong name key file then that assembly is called as signed
assembly. To sign the assembly, follow the following two steps.
1. Create a strong name key file
2. Associate strong name key file to the assembly

Creating Strong Name Key File


To create a strong name key file, use the command line tool Sn.exe that has the following syntax.
Sn –k MyKey.snk
This will create a strong name and writes it to the MyKey.snk file.

Associating Strong Name Key File To Assembly


To associate the strong name key file generated using Sn command line tool, first open the project,
which you want to convert to shared assembly in VS.net and open solution explorer. Within the solution
explorer click on show all files button and then double click and open AssemblyInfo.vb or
AssemblyInfo.cs file and write the following entry in that file.
<Assembly : AssemblyKeyFile(“KeyFilePath”)> // C#.Net
[Assembly : AssemblyKeyFile(“KeyFilePath”)] // VB.Net

After creating and associating strong name key file to the assembly build the solution with shortcut Ctrl
+ Shift + B to make the generated assembly as signed assembly.

Placing Assembly In GAC


To place an assembly in to GAC, use the command line tool GACUTIL.exe that has the following
syntax.

Gacutil /i Pathoftheassembly

GAC is nothing but a folder with the name assembly in windows folder. Once the assembly is placed in
GAC, it will become a shared assembly. If you want to remove the assembly from GAC, use the
following syntax of Gacutil command line tool.

Gacutil /u Pathoftheassembly
Signing the Assembly In .net 2005
In .net 2005 you can sign the assembly from within VS.net without using any command line tools and
has the following steps.
1. Open the project which you want to convert to shared assembly in VS.net and then open the
properties of project.
2. Within the properties of the project select Signing tab and then check the check box Sign the
assembly that activates a combo box.
3. Within the combo box select new to create a new strong name key file. This will open a dialog
box asking you to enter a name for the strong name key file and password to provide security.
Provide a name and password and click on ok button.
4. Close properties window, save the project and build the solution to generate a signed assembly
for the project.
After signing the assembly, place it in GAC in order to convert it to shared assembly.

Secret Behind Strong Naming


Strong name is not a name and is a pair of keys called private key and public key. String name is
used by the CLR to uniquely identify the assembly and provide security for the assembly from
tampering by others. When a strong name is associated to the assembly, then a hash algorithm is
applied on current content of the assembly to generate a hash value and this hash value is encrypted
by using private key to get digital signature and will be stored in manifest of the main module and
public key is stored in metadata of the main module.

While executing the assembly, the digital signature available in manifest will be decrypted with the help
of public key available in metadata to get original hash value of the assembly and at the same time
hash algorithm is applied on the assembly to get hash value based on current content of the assembly.
If both of these hash values are matched then assembly was not tampered and will be executed.
Otherwise causes error and will not execute the assembly.

You might also like