Friday, January 30, 2009

How to upload File on FTP Server in .Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace PubishApps
{
/************************************************
* Topic : How to upload File on FTP Server in .Net
* Reference Required: System.Net.
* Author : kalit sikka
* Summary: using FtpWebRequest Class in System.Net namespace to upload files on local machine to FTP Server.
* **********************************************/
public struct FTPCredentials
{
public string FTPHostID;
public string UserName;
public string Password;
public FTPCredentials(string HostID, string User, string Password)
{
this.FTPHostID = HostID;
this.UserName = User;
this.Password = Password;
}
}
public class DataUploadOnFTP
{
private string FTPHostID = string.Empty;
private string UserName = string.Empty;
private string Password = string.Empty;
private string FullPathOfInputFile = string.Empty;
private string FileName = string.Empty;
///
/// Constructor
///

/// FTP Credentials
/// Full path on Input File
public DataUploadOnFTP(FTPCredentials Credentials, string FullPathOfFileToUpload)
{
FTPHostID = Credentials.FTPHostID;
UserName = Credentials.UserName;
Password = Credentials.Password;
this.FullPathOfInputFile = FullPathOfFileToUpload;
// Getting only File Name from complete address
this.FileName = System.IO.Path.GetFileName(FullPathOfFileToUpload);
}
///
/// Method to upload file to FTP Server.
///

///
public bool UploadFileOnFTP()
{
try
{
string FTPHost = "ftp://" + FTPHostID;
string FTPFilePath = Path.Combine(FTPHost, FileName);
FtpWebRequest oFTP = (FtpWebRequest)FtpWebRequest.Create(FTPFilePath);
oFTP.Credentials = new NetworkCredential(UserName, Password);
oFTP.KeepAlive = true;
oFTP.UseBinary = true;
oFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(FullPathOfInputFile);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = oFTP.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
return true;
}catch(Exception e)
{
return false;
}
}
}
}

Introduction to .Net Framework

The Microsoft .Net Framework is a platform that provides tools and technologies you need to build Networked Applications as well as Distributed Web Services and Web Applications. The .Net Framework provides the necessary compile time and run-time foundation to build and run any language that conforms to the Common Language Specification (CLS).The main two components of .Net Framework are Common Language Runtime (CLR) and .Net Framework Class Library (FCL).
The Common Language Runtime (CLR) is the runtime environment of the .Net Framework , that executes and manages all running code like a Virtual Machine. The .Net Framework Class Library (FCL) is a huge collection of language-independent and type-safe reusable classes. The .Net Framework Class Libraries (FCL) are arranged into a logical grouping according to their functionality and usability is called Namespaces. In the following sections describes how to .Net Framework manages the code in compile time and run time.
Microsoft .Net Languages Source Code are compiled into Microsoft Intermediate Language (MSIL). MSIL we can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). Microsoft Intermediate Language (MSIL) is a CPU independent set of instructions that can be converted to the native code. Metadata also created in the course of compile time with Microsoft Intermediate Language (MSIL) and stored it with the compiled code . Metadata is completely self-describing . Metadata is stored in a file called Manifest, and it contains information about the members, types, references and all the other data that the Common Language Runtime (CLR) needs for execution.
The Common Language Runtime (CLR) uses metadata to locate and load classes, generate native code, provide security, and execute Managed Code. Both Microsoft Intermediate Language (MSIL) and Metadata assembled together is known as Portable Executable (PE) file. Portable Executable (PE) is supposed to be portable across all 32-bit operating systems by Microsoft .Net Framework.
During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System. The native code is Operating System independent and this code is known as Managed Code , that is, the language's functionality is managed by the .NET Framework . The Common Language Runtime (CLR) provides various Just In Time (JIT) compilers, and each works on a different architecture depends on Operating Systems, that means the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems. In the following section you can see how Common Language Runtime (CLR) functions.

Common Language Runtime
The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between Operating Systems and the applications written in .Net languages that conforms to the Common Language Specification (CLS). The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. The Managed Code compiled only when it needed, that is it converts the appropriate instructions when each function is called. The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time.
During the execution of the program ,the Common Language Runtime (CLR) manages memory, Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS), code safety verifications, and other system services. The CLR ( Common Language Runtime ) defines the Common Type System (CTS), which is a standard type system used by all .Net languages. That means all .NET programming languages uses the same representation for common Data Types , so Common Language Runtime (CLR) is a language-independent runtime environment . The Common Language Runtime (CLR) environment is also referred to as a managed environment, because during the execution of a program it also controls the interaction with the Operating System. In the coming section you can see what are the main functions of Common Language Runtime (CLR).
The Common Language Runtime (CLR) is a an Execution Environment . Common Language Runtime (CLR)'s main tasks are to convert the .NET Managed Code to native code, manage running code like a Virtual Machine and also controls the interaction with the Operating System.
Common Language Runtime (CLR) manages Thread executions, Memory Management that is allocation of Objects and Buffers , Garbage Collection (GC) - Clean up the unused Objects and buffers , Exception Handling, Common Type System (CTS) that is all .NET language that conforms to the Common Language Specification (CLS) have the same primitive Data Types, Code safety verifications - code can be verified to ensure type safety, Language integration that is Common Language Runtime (CLR) follow a set of specification called Common Language Specification (CLS) , this will ensure the interoperability between languages, Integrated security and other system services.

.Net Framework Class Library (FCL)
The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture. The .Net Framework Class Library (FCL) includes a huge collection of reusable classes, interfaces, and value types that expedite and optimize the development process and provide access to system functionality.
The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of types for the purpose of identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.
Common Language Specification
Common Language Specification (CLS) is a set of basic language features that .Net Languages needed to develop Applications and Services, which are compatible with the .Net Framework. When there is a situation to communicate Objects written in different .Net Complaint languages, those objects must expose the features that are common to all the languages. Common Language Specification (CLS) ensures complete interoperability among applications, regardless of the language used to create the application.
Common Language Specification (CLS) defines a subset of Common Type System (CTS). Common Type System (CTS) describes a set of types that can use different .Net languages have in common, which ensure that objects written in different languages can interact with each other. Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. Moreover Common Language Specification (CLS) standardized by ECMA.
Common Type System
Common Type System (CTS) describes a set of types that can be used in different .Net languages in common . That is , the Common Type System (CTS) ensure that objects written in different .Net languages can interact with each other. For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level .
These types can be Value Types or Reference Types . The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.
Microsoft Intermediate Language
MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate Language (IL) or Common Intermediate Language (CIL). During the compile time , the compiler convert the source code into Microsoft Intermediate Language (MSIL) .Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that can be efficiently converted to the native code. During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System.
When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Metadata. The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable executable (PE) file . Microsoft Intermediate Language (MSIL) includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations
Just In Time Compiler
The .Net languages , which is conforms to the Common Language Specification (CLS), uses its corresponding runtime to run the application on different Operating Systems . During the code execution time, the Managed Code compiled only when it is needed, that is it converts the appropriate instructions to the native code for execution just before when each function is called. This process is called Just In Time (JIT) compilation, also known as Dynamic Translation . With the help of Just In Time Compiler (JIT) the Common Language Runtime (CLR) doing these tasks.
The Common Language Runtime (CLR) provides various Just In Time compilers (JIT) and each works on a different architecture depending on Operating System. That is why the same Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems without rewrite the source code. Just In Time (JIT) compilation preserves memory and save time during application initialization. Just In Time (JIT) compilation is used to run at high speed, after an initial phase of slow interpretation. Just In Time Compiler (JIT) code generally offers far better performance than interpreters.
Managed Code
Managed Code in Microsoft .Net Framework, is the code that has executed by the Common Language Runtime (CLR) environment. On the other hand Unmanaged Code is directly executed by the computer's CPU. Data types, error-handling mechanisms, creation and destruction rules, and design guidelines vary between managed and unmanaged object models.
The benefits of Managed Code include programmers convenience and enhanced security . Managed code is designed to be more reliable and robust than unmanaged code , examples are Garbage Collection , Type Safety etc. The Managed Code running in a Common Language Runtime (CLR) cannot be accessed outside the runtime environment as well as cannot call directly from outside the runtime environment. This makes the programs more isolated and at the same time computers are more secure . Unmanaged Code can bypass the .NET Framework and make direct calls to the Operating System. Calling unmanaged code presents a major security risk.
.Net Metadata
Metadata in .Net is binary information which describes the characteristics of a resource . This information include Description of the Assembly , Data Types and members with their declarations and implementations, references to other types and members , Security permissions etc. A module's metadata contains everything that needed to interact with another module.
During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference.
.Net Assembly
Microsoft .Net Assembly is a logical unit of code, it contains code that the Common Language Runtime (CLR) executes. Assembly is really a collection of types and resource information that are built to work together and form a logical unit of functionality. During the compile time Metadata is created, with Microsoft Intermediate Language (MSIL), and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. Manifest contains information about itself. This information is called Assembly Manifest, it contains information about the members, types, references and all the other data that the runtime needs for execution.
Every Assembly you create contains one or more program files and a Manifest. There are two types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can have only one entry point (that is, DllMain, WinMain, or Main). We can create two types of Assembly, private Assembly and shared Assembly . A private Assembly is used only by a single application, and usually it is stored in that application's install directory. A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC).
.Net Assembly Manifest
An Assembly Manifest is a file that containing Metadata about .NET Assemblies. Assembly Manifest contains a collection of data that describes how the elements in the assembly relate to each other. It describes the relationship and dependencies of the components in the Assembly, versioning information, scope information and the security permissions required by the Assembly.
The Assembly Manifest can be stored in Portable Executable (PE) file with Microsoft Intermediate Language (MSIL) code. You can add or change some information in the Assembly Manifest by using assembly attributes in your code. The Assembly Manifest can be stored in either a PE file (an .exe or .dll) with Microsoft Intermediate Language (MSIL) code or in a standalone PE file that contains only assembly manifest information. Using ILDasm, you can view the manifest information for any managed DLL.
.Net Namespaces
Namespaces are the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification.
The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes. These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL ) by using the full Namespaces of the class .In .Net languages every program is created with a default Namespaces . Programmers can also create their own Namespaces in .Net languages.
Garbage Collection
The .Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap.
The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.
Threads
Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process. Thread is like a process, at least one thread exists within each process. Single Thread (normal programs) in computer science means that only one task can execute and at the same time the other tasks have to wait for the completion of the current task like in a queue. Single thread resulted in systems idle time and application performance.
Multithreading allows multiple process to execute concurrently within a single program .That is more than one task in a program can execute at the same time and each thread run independently of its own. If multiple threads can exist within a process, typically share the state information of a process, and share memory and other resources directly. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to save the thread context until it is scheduled.
In multiple threaded programming we can use system's idle time, so it leads improved application performance . Also we can set priority in each Threads . Threads with higher priority are executed in preference to threads with lower priority. It is recommended that you use as few threads as possible, thereby minimizing the use of Operating System resources . Check the following links to see how Multi Threaded applications works in VB.NET .

Object-Oriented Programming Concepts and .NET

Classes, Objects, and Structures in .NET


Object-Oriented Programming (OOP) is a software development paradigm that suggests developers to split a program in building blocks known as objects. The OOP paradigm allows developers to define the object’s data, functions, and its relationship with other objects.

Microsoft created the .NET Framework using OOP, and knowing this concepts has helped me to understand the .NET Framework and to design and develop better software components. The purpose of this article is to describe the basic OOP concepts using real world scenarios and to provide some code samples that demonstrate how to work with OOP and .NET.
Class

The most common definition states that a class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template. Another great example are house plans and blueprints. The plans and blueprints define the number of rooms, the size of the kitchen, the number of floors, and more. In this real world sample, the house plans and blueprints are the class and the house is the object. In OOP you program a class as a template for a specific object or groups ob objects that will always have the same features.
Class members

A class has different members, and developers in Microsoft suggest to program them in the following order:
Namespace: The namespace is a keyword that defines a distinctive name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.
Class declaration: Line of code where the class name and type are defined.
Fields: Set of variables declared in a class block.
Constants: Set of constants declared in a class block.
Constructors: A method or group of methods that contains code to initialize the class.
Properties: The set of descriptive data of an object.
Events: Program responses that get fired after a user or application action.
Methods: Set of functions of the class.
Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application.
Access keywords

Access keywords define the access to class members from the same class and from other classes. The most common access keywords are:
Public: Allows access to the class member from any other class.
Private: Allows access to the class member only in the same class.
Protected: Allows access to the class member only within the same class and from inherited classes.
Internal: Allows access to the class member only in the same assembly.
Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.
Static: Indicates that the member can be called without first instantiating the class.

The following sample code illustrates a sample class in C#:
/// C#
///Imported namespaces
using System;

/// Namespace: Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp {

///Class declaration
public class employee {

///Fields
private string _name;
private int _salary;

///Constants
private const int anualBonus = 1000;

///Constructor
public employee(){
}

///Properties
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public int Salary {
get {
return _salary;
}
set {
_salary = value;
}
}

/// Event handlers
public event EventHandler OnPromotion {
add {
}
remove {
}
}

/// Methods
public void DuplicateSalary() {
_salary = _salary*2;
}

}
}

Listing 1. Sample class implementation in C#

The following sample code illustrates a sample class in VB.NET:
' VB.NET
'Imported namespaces
Imports System

' Namespace: Consider using CompanyName.Product.ComponentType
Namespace DotNetTreats.OOSE.OOP_VBNET

'Class declaration
Public Class employee

'Fields
Private _name As String
Private _salary As Integer

'Constants
Private Const anualBonus As Integer = 1000

'Constructors
Public Sub New()
MyBase.New
End Sub

'Properties
Public Property Name As String
Get
Return _name
End Get
Set
_name = value
End Set
End Property

Public Property Salary As Integer
Get
Return _salary
End Get
Set
_salary = value
End Set
End Property

' Event handlers
Public Event OnPromotion As EventHandler

'Methods
Public Sub DuplicateSalary()
_salary = (_salary * 2)
End Sub

End Class

End Namespace

Listing 2. Sample class implementation in VB.NET

Object

Objects are the building blocks of OOP and are commonly defined as variables or data structures that encapsulate behavior and data in a programmed unit. Objects are items that can be individually created, manipulated, and represent real world things in an abstract way.
Object composition

Every object is composed by:
Object identity: Means that every object is unique and can be differentiated from other objects. Each time and object is created (instantiated) the object identity is defined.
Object behavior: What the object can do. In OOP, methods work as functions that define the set of actions that the object can do.
Object state: The data stored within the object at any given moment. In OOP, fields, constants, and properties define the state of an object.
Structures

Not everything in the real world should be represented as a class. Structures are suitable to represent lightweight objects. Structures can have methods and properties and are useful for defining types that act as user-defined primitives, but contain arbitrary composite fields. The .NET Framework defines some structures such as System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.

The following code sample represents a structures in C#:
/// C#
struct Point {
private int _x;
private int _y;

Point(int x, int y){
this._x = x;
this._y = y;
}

public int X {
get {
return _x;
}
set {
_x = value;
}
}

public int Y {
get {
return _y;
}
set {
_y = value;
}
}
}

Listing 3. Sample structure implementation in C#

The following code sample represents a structure in VB.NET:
' VB.NET
Structure Point
Private _x As Integer
Private _y As Integer

Sub New(ByVal x As Integer, ByVal y As Integer)
MyBase.New
Me._x = x
Me._y = y
End Sub

Public Property X As Integer
Get
Return _x
End Get
Set
_x = value
End Set
End Property

Public Property Y As Integer
Get
Return _y
End Get
Set
_y = value
End Set
End Property
End Structure

Listing 4. Sample structure implementation in VB.NET

Conclusion

OOP is full of abstract concepts, and the best approach to understand them is practical and not only theoretical. I learned more OOP after making some designs and after implementing some components. The concepts presented in this article might clarify the meaning, but I strongly recommend to go and have fun playing around with OOP. In this article, I examined the concept of classes, objects, and structs. The second part will examine the concepts of inheritance, abstraction, and polimorphism.

Thursday, January 29, 2009

How to make connection with Access Database that has database password

Summary:This Program will connect to a Microsoft Access database with database password with ADO.net.SolutionJet OLEDB:Database Password attribute in the connection string is use to specify the password.using System;using System.Configuration;using System.Text;using System.Data;using System.Data.OleDb;
private void connectButton_Click(object sender, System.EventArgs e){ StringBuilder result = new StringBuilder( );
// Build the connections string incorporating the password. String connectionString = ConfigurationSettings.AppSettings["MsAccess_Secure_ConnectString"]+ "Jet OLEDB:Database Password=" + passwordTextBox.Text + ";";
result.Append("ConnectionString: " + Environment.NewLine + connectionString + Environment.NewLine + Environment.NewLine);
OleDbConnection conn = new OleDbConnection(connectionString); try { conn.Open( );
// Retrieve some database information. result.Append( "Connection State: " + conn.State + Environment.NewLine + "OLE DB Provider: " + conn.Provider + Environment.NewLine + "Server Version: " + conn.ServerVersion + Environment.NewLine);
conn.Close( ); result.Append("Connection State: " + conn.State); } catch(System.Data.OleDb.OleDbException ex) { conn.Close( ); result.Append("ERROR: " + ex.Message); }
resultTextBox.Text = result.ToString( );}DiscussionA Microsoft Access database password requires that users enter a password to obtain access to the database and database objects. This is also known as share-level security. A password does not allow groups or users to have distinct levels of access or permissions. Anyone with the password has unrestricted access to the database.The Set Database command from the Tools > Security menu is used to set up a database password.The OLE DB provider for Microsoft Jet has several provider-specific connection string attributes in addition to those defined by ADO.NET. To open a database secured by a Microsoft Access database password, use the Jet OLEDB:Database Password attribute in the connection string to specify the password. This corresponds to the OLE DB property DBPROP_JETOLEDB_DATABASEPASSWORD.

Common Language Runtime in .Net

Summary:
This article will give brief description about Common Language Runtime and its components.
Common Language Runtime (CLR)
The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between Operating Systems and the applications written in .Net languages that conforms to the Common Language Specification (CLS). The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. The Managed Code compiled only when it needed, that is it converts the appropriate instructions when each function is called. The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time.
During the execution of the program ,the Common Language Runtime (CLR) manages memory, Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS), code safety verifications, and other system services. The CLR ( Common Language Runtime ) defines the Common Type System (CTS), which is a standard type system used by all .Net languages. That means all .NET programming languages uses the same representation for common Data Types , so Common Language Runtime (CLR) is a language-independent runtime environment . The Common Language Runtime (CLR) environment is also referred to as a managed environment, because during the execution of a program it also controls the interaction with the Operating System.

Major CLR components: the Virtual Execution System (VES)
The major components of the CLR include the class loader, verifier, JIT compilers, and other execution support, such as code management, security management, garbage collection, exception management, debug management, marshaling management, thread management, and so on..NET PE files lay on top of the CLR and execute within the CLR's Virtual Execution System (VES), which hosts the major components of the runtime. Your .NET PE files will have to go through the class loader, the type verifier, the JIT compilers, and other execution support components before they will execute.
Class Loader
When you run a standard Windows application, the OS loader loads it before it can execute. At the time of this writing, the default loaders in the existing Windows operating systems, such as Windows 98, Windows Me, Windows 2000, and so forth, recognize only the standard Windows PE files. As a result, Microsoft has provided an updated OS loader for each of these operating systems that support the .NET runtime. The updated OS loaders know the .NET PE file format and can handle the file appropriately.
When you run a .NET application on one of these systems that have an updated OS loader, the OS loader recognizes the .NET application and thus passes control to the CLR. The CLR then finds the entry point, which is typically Main( ), and executes it to jump-start the application. But before Main( ) can execute, the class loader must find the class that exposes Main( ) and load the class. In addition, when Main( ) instantiates an object of a specific class, the class loader also kicks in. In short, the class loader performs its magic the first time a type is referenced.
The class loader loads .NET classes into memory and prepares them for execution. Before it can successfully do this, it must locate the target class. To find the target class, the class loader looks in several different places, including the application configuration file (.config) in the current directory, the GAC, and the metadata that is part of the PE file, specifically the manifest. The information that is provided by one or more of these items is crucial to locating the correct target class. Recall that a class can be scoped to a particular namespace, a namespace can be scoped to a particular assembly, and an assembly can be scoped to a specific version. Given this, two classes, both named Car, are treated as different types even if the version information of their assemblies are the same.
Once the class loader has found and loaded the target class, it caches the type information for the class so that it doesn't have to load the class again for the duration of this process. By caching this information, it will later determine how much memory is needed to allocate for the newly created instance of this class. Once the target class is loaded, the class loader injects a small stub, like a function prolog, into every single method of the loaded class. This stub is used for two purposes: to denote the status of JIT compilation and to transition between managed and unmanaged code. At this point, if the loaded class references other classes, the class loader will also try to load the referenced types. However, if the referenced types have already been loaded, the class loader has to do nothing. Finally, the class loader uses the appropriate metadata to initialize the static variables and instantiate an object of the loaded class for you.
Verifier
Scripting and interpreted languages are very lenient on type usages, allowing you to write code without explicit variable declarations. This flexibility can introduce code that is extremely error-prone and hard to maintain, and that is often a culprit for mysterious program crashes. Unlike scripting and interpreted languages, compiled languages require types to be explicitly defined prior to their use, permitting the compiler to ensure that types are used correctly and the code will execute peacefully at runtime.
The key here is type safety, and it is a fundamental concept for code verification in .NET. Within the VES, the verifier is the component that executes at runtime to verify that the code is type safe. Note that this type verification is done at runtime and that this is a fundamental difference between .NET and other environments. By verifying type safety at runtime, the CLR can prevent the execution of code that is not type safe and ensure that the code is used as intended. In short, type safety means more reliability.
Let's talk about where the verifier fits within the CLR. After the class loader has loaded a class and before a piece of IL code can execute, the verifier kicks in for code that must be verified. The verifier is responsible for verifying that:
The metadata is well formed, meaning the metadata must be valid.
The IL code is type safe, meaning type signatures are used correctly.
Both of these criteria must be met before the code can be executed because JIT compilation will take place only when code and metadata have been successfully verified. In addition to checking for type safety, the verifier also performs rudimentary control-flow analysis of the code to ensure that the code is using types correctly. You should note that since the verifier is a part of the JIT compilers, it kicks in only when a method is being invoked, not when a class or assembly is loaded. You should also note that verification is an optional step because trusted code will never be verified but will be immediately directed to the JIT compiler for compilation.
JIT Compilers
JIT compilers play a major role in the .NET platform because all .NET PE files contain IL and metadata, not native code. The JIT compilers convert IL to native code so that it can execute on the target operating system. For each method that has been successfully verified for type safety, a JIT compiler in the CLR will compile the method and convert it into native code.
One advantage of a JIT compiler is that it can dynamically compile code that is optimized for the target machine. If you take the same .NET PE file from a one-CPU machine to a two-CPU machine, the JIT compiler on the two-CPU machine knows about the second CPU and may be able to spit out the native code that takes advantage of the second CPU. Another obvious advantage is that you can take the same .NET PE file and run it on a totally different platform, whether it be Windows, Unix, or whatever, as long as that platform has a CLR.
For optimization reasons, JIT compilation occurs only the first time a method is invoked. Recall that the class loader adds a stub to each method during class loading. At the first method invocation, the VES reads the information in this stub, which tells it that the code for the method has not been JIT-compiled. At this indication, the JIT compiler compiles the method and injects the address of the native method into this stub. During subsequent invocations to the same method, no JIT compilation is needed because each time the VES goes to read information in the stub, it sees the address of the native method. Because the JIT compiler only performs its magic the first time a method is invoked, the methods you don't need at runtime will never be JIT-compiled.
The compiled, native code lies in memory until the process shuts down and until the garbage collector clears off all references and memory associated with the process. This means that the next time you execute the process or component, the JIT compiler will again perform its magic.
If you want to avoid the cost of JIT compilation at runtime, you can use a special tool called ngen.exe, which compiles your IL during installation and setup time. Using ngen, you can JIT-compile the code once and cache it on the machine so that you can avoid JIT compilation at runtime (this process is referred to as pre-JITting). In the event that the PE file has been updated, you must PreJIT the PE file again. Otherwise, the CLR can detect the update and dynamically command the appropriate JIT compiler to compile the assembly.
Execution Support and Management
By now, you should see that every component in the CLR that we've covered so far uses metadata and IL in some way to successfully carry out the services that it supports. In addition to the provided metadata and generated managed code, the JIT compiler must generate managed data that the code manager needs to locate and unwind stack frames. The code manager uses managed data to control the execution of code, including performing stack walks that are required for exception handling, security checks, and garbage collection. Besides the code manager, the CLR also provides a number of important execution-support and management services. A detailed discussion of these services is beyond the scope of this book, so we will briefly enumerate a few of them here:
By the way, you can write a custom JIT compiler or a custom code manager for the CLR because the CLR supports the plug-and-play of these components.
Garbage collection
Unlike C++, where you must delete all heap-based objects manually, the CLR supports automatic lifetime management for all .NET objects. The garbage collector can detect when your objects are no longer being referenced and perform garbage collection to reclaim the unused memory.
Exception handling
Prior to .NET, there was no consistent method for error or exception handling, causing lots of pain in error handling and reporting. In .NET, the CLR supports a standard exception-handling mechanism that works across all languages, allowing every program to use a common error-handling mechanism. The CLR exception-handling mechanism is integrated with Windows Structured Exception Handling (SEH).
Security support
The CLR performs various security checks at runtime to make sure that the code is safe to execute and that the code is not breaching any security requirements. In addition to supporting code access security, the security engine also supports declarative and imperative security checks. Declarative security requires no special security code, but you have to specify the security requirements through attributes or administrative configuration. Imperative security requires that you write the code in your method to specifically cause security checks.
Debugging support
The CLR provides rich support for debugging and profiling. There is an API that compiler vendors can use to develop a debugger. This API contains support for controlling program execution, breakpoints, exceptions, control flow, and so forth. There is also an API for tools to support the profiling of running programs.
Interoperation support
The CLR supports interoperation between the managed (CLR) and unmanaged (no CLR) worlds. The COM Interop facility serves as a bridge between COM and the CLR, allowing a COM object to use a .NET object, and vice versa. The Platform Invoke (P/Invoke) facility allows you to call Windows API functions.
This is by no means an exhaustive list. The one thing that we want to reiterate is that like the class loader, verifier, JIT compiler, and just about everything else that deals with .NET, these execution-support and management facilities all use metadata, managed code, and managed data in some way to carry out their services.
Locations of visitors to this page