Sie sind auf Seite 1von 32

Overview of .

NET Framework
The .NET Framework is designed as an integrated environment for seamlessly developing and running applications on the internet, on the desktop as Windows Forms, and even on mobile devices(with the compact Framework).Its Primary objectives are as follows: 1. Provide OO environment across the range of applications 2. Provide an environment that minimizes the versioning conflicts(DLL Hell) that is faced by COM programmers 3. Simplify the code distribution/Installation process. 4. Provide portable environment. 5. To provide a managed environment in which code is easily verified for safe execution. To achieve these broad objectives, .NET Framework is separated into 2 parts: 1. CLR (Common Language Runtime) 2. FCL (Framework Class Library) Note: - The coming section will explain each components of the .NET framework. The below diagram displays the various components of the .NET framework.

.NET Components
.NET framework has following three main components. .NET framework class library: - An OO collection of reusable Types. Further there are numbers of various components such as Ado.Net: for connecting, with database, and Asp.Net: for creating, running, and deploying web application and web services (distributed application). Include classes for database access, graphics, and Interoperability with

unmanaged code, security and both Web and Windows forms All languages that target the .NET Framework use this common class library. CLR [common language runtime]:- This is also called the core of the .NET framework. It provides the functionality or features such as: 1. CAS (Code access security) 2. Execute managed code and provide wrappers to communicate with unmanaged code. 3. Exceptional Handling 4. Garbage collection 5. Convert MSIL code to Native code using JIT. 6. Resolve problem of DLL Hell. 7. Thread management. 8. Enforcement of type safety and use.

Usage Area: - It provides multi-language object oriented environment for programmers, whether the code is stored and executed entirely locally or remotely. It facilitates software development and minimizes versioning conflicts. Provides environment that promotes safe code execution. Allow developer to create both Windows and Web-based applications.

Understanding the .NET Framework and its Role The .NET framework is the infrastructure for building applications using .Net. The .NET framework provides a consistent OO Programming model that you can use to build all types of applications. The .NET framework provides 4 CLS- compliant languages:

Microsoft Microsoft Microsoft Microsoft

VB.Net Visual C# Visual C++.Net Visual J#.Net

The .NET framework provides the infrastructure and services per the CLI Specifications. These includes Common Language Runtime: This includes the CLI and provides the execution environment to .NET applications. All the .NET language compliers compile the source code into MSIL code, which the CLR loads and executes when you run an application. Common Type Systems: These provide the necessary data types, value and objects types, which you need to develop applications in different languages. All the .NET languages share CTS. This implies that a string in Vb.NET is same as a string in Visual C#. Type Safety: The .NET framework ensures that operation to be performed on one value or object are performed on that value or object only. Managed Code Execution: The .NET framework loads and executes the .NET applications, and manages the state of objects during program execution. This also provides automatically garbage collections.

Side-by-side execution: The .NET framework allows you to deploy multiple versions of an application on a system by using assemblies. Assemblies are the

deployment unit in the .NET framework. An assembly contains the IL code and metadata.

CLR (Common Language Runtime)


Common Language Runtime consists of various components that provide the run-time environment and run-time services for your applications. The following are the features of CLR:-

1. Load IL code of the application into the runtime 2. Compile the IL Code into the Native Code. 3. Execute the Code 4. Enforce Security 5. Type Safety 6. Memory Management 7. Thread Support 8. CAS (Code Access Security) 9. Provide exception manager, common debugger, interoperability. 10. Garbage Collection 11. Cross language Integration, especially cross Lang. inheritance.

Components of CLR The following are the components of CLR :-

1. Class Loader: This loads classes into the runtime. 2. MSIL to native code compiler: This converts MSIL code into native code. 3. Code manager: This manager the code during execution i.e provides code check,
the resources it needs during execution.

4. Garbage Collector: provide automatic memory management and avoid memory


leaks.

5. Security Engine: This enforces security restrictions and CAS. 6. Type Checker: This enforces strict type checking. 7. Thread Support: This provides multithreading support to applications. 8. Exception Manager: This provides a mechanism to handle the run-time exceptions. 9. Debug Engine: Allow you to debug different type of applications. 10. COM marshaler: This allows .NET application to exchange data with COM
applications.

11. BASE Class library: This provides the types the applications needed at runtime.

Steps to Run a program in CLR


For a program to run within the common language runtime and benefit from the managed execution environment, you need to write the source code of the program in a CLScompliant language. Step-1 The compilers of CLS-compliant languages compile the source code and generate an intermediate code, called MSIL code, and metadata. MSIL Code contains a CPU independent set of instructions, which describes how to load, store, initialize, and call. They also contains instructions to perform arithmetic and logical operations, access memory directly, control the flow of execution, handle exceptions and perform other operations.methods on objects Step-2 Before you execute the MSIL code, you need to compile it into CPU-specific instructions. To execute the code, the runtime requires information about the code that is in the metadata. The metadata describes the code and defines the types that the code contains as well as references to other types that the code uses at run time. MSIL Code and metadata both located in the .PE (portable executable) file. Step-3 When we execute .PE file, the class loader loads the MSIL code and metadata from the portable executable file into the run-time memory. Step-4 After the MSIL code and metadata are loaded into the memory, the code manager calls the entry point method, which is Main, Win Main or DllMain method. An entry-point method is the first method to be executed when you run your application. Step-5 The garbage collector performs periodic checks on the managed heap to identify the objects that are no longer required by the program and removes them from memory. Step-6 The applications running within the common language runtime can utilize the managed multithreading support. The .NET Framework allows a single process to be divided into one or more sub processes called application domains. Each application domain can contain one or more threads. The runtime monitors all the threads that have executed code within its process. Step-7 The common language runtime also allows managed code tointeroperate with unmanaged code. One of the components of the common language runtime is the COM marshaler, which performs marshaling of data when data passes between managed and unmanaged execution environments. Step-8 Then with the help of JIT the IL code is converted into Native code or we can say Intermediate set of instructions are converted into CPU set of instruction. Note:- The above steps are known as called managed execution process.

Assembly

Assembly is smallest unit of deployment. An assembly consists of one or more files (dlls, exe's, html files etc) and represents a group of resources, type definitions and implementation of those types. An assembly may also contain references to other assemblies. The assembly manifest contains the version information. An assembly is the smallest unit that you use to define the version of an application. The version of an assembly determines the version of the types and the other resources that it contains. The .NET framework allows the execution of multiple versions of the same assembly on the same machine. The side-by-side execution of assemblies overcomes the problem known as DLL Hell, which is one of the major problems associated with COM applications. Assemblies are the smallest units to which the .NET framework grants permissions. They provide security boundaries within the .NET framework. When the assembly is loaded into the runtime, the assembly sends the request to the runtime to grant the permission. The permission granted depends on the policy files that are checked by the security engine of the runtime. Assemblies are a fundamental part of programming with the .NET framework. An assembly performs the following functions: Functions or Features:

It contains the code that a CLR executes. MSIL code in a portable executable file will not be executed if it doesn't contain the associated assembly manifest. Each assembly can have only one entry point( that is DllMain, WinMain, Main ) It forms a security boundary. An assembly is a unit at which permissions are requested and granted. Type Boundary: Every type identity includes the name of the assembly in which it resides. Reference Scope Boundary: The assembly manifest contains assembly metadata that is used for resolving types and satisfying resources requests. Version Boundary: The assembly is the smallest versionable unit in the CLR, all types and resources in the same assembly are versioned as a unit. It forms a deployment unit: When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes can be retrieved on demand. Side-by-Side Execution is supported by assemblies.

Understanding Namespaces: The .NET Framework class library consists of reusable classes, which are organized in hierarchical namespace. A namespace contains logically and functionally- related classes and divides an assembly into a logical grouping of types. e.g. System.Data namespace contains all the classes that you require to build database applications, and System.IO namespace contains all the classes that you require to perform input and output operations within a program. Multiple assemblies can use the same namespace. Assemblies can be staic or dynamic. The following is the defination for static and dynamic assemblies. Static assemblies : Static assemblies can include .NET framework types (interface and classes) as well as resources for the assembly. Static assemblies are stored on disk in PE file. Dynamic assemblies : The dynamic assemblies can be created using the .NET framework and they are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. Assembly Contents

In general, a static assembly consists of four elements:

Assembly Manifest Type metadata MSIL code that implements the type. Set of resources.

Note:-There are several ways to group these elements in assembly. Two ways to group these within a single file or with different set of files. The elements of an assembly can be contained in several files. These files can be modules of compiled code (.netmodule), resources. Assembly Manifest: Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. Assembly Manifest contains the following information:

Assembly Name: A text string specifying the assembly name. Version Number: A major, minor, revision and build number. The CLR uses these numbers to enforce version policy. Culture: Information on the culture or language the assembly supports. The information should be used only to designate an assembly as a satellite Assembly containing culture- or language-specific information. Strong Name Information: The public key from the publisher if the assembly has been given a strong name. Type Reference Information: Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly.

Type Metadata:
The other component of assembly is type metadata. Metadata can be defined as data about the data; this means the metadata contains all the information about the assembly. Metadata defines the contents of the assembly. Metadata contains information such as: Classes that are there in the assembly. Interfaces, Events, Indexers that are used in the assembly. Structs and all the types' information.

MSIL Code
MSIL code is Microsoft intermediate language. The source code is compiled by .NET compiler that will convert the source code into the IL code or MSIL code that is intermediate code and then this MSIL code that resides on PE file i.e. portable executable code convert into machine code using JIT with the help of CLR.

Types of Assembly: There are three types of assembly.

Private Assembly:- These are those assemblies, which are used by single application and are stored in the application directory or a sub-directory beneath. Here the scope of this assembly is limited to the application itself and this assembly can't be shared by multiple assemblies. If you want to use this private assembly, you have to either copy this assembly or paste under the bin folder or you can create the reference of this assembly using the Add reference dialog box and use this assembly. The limitation with the private assembly is that it can't be accessed by two application. Shared Assembly:- A shared assembly can be used by multiple assemblies. A shared assembly is normally stored in GAC (Global Assembly Cache), which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful e.g. crystal report classes which will be used by all application for reports. Satellite Assembly:- In multi lingual application in .NET to support multilingual functionality you can have modules which are customized for locations. These assemblies are called as satellite assemblies. Here in these assemblies we can distribute these assemblies separately than the core modules.

GAC (Global Assembly CACHE)


An assembly that is shared by multiple applications is called a global assembly and is installed in the global assembly cache (GAC). The GAC is a machine wide cache that contains the assemblies that are shared by multiple applications. GAC is used where shared .NET assembly reside. GAC is used in the following situations: If the application has to be shared among several applications. If the assembly has some special security requirements like only administrator can remove the assembly. If the assembly is private then simple delete can remove the assembly.

Note:- Registering .NET assembly in GAC can lead to the old problem of DLL Hell. Where COM version was stored in central registry, so GAC should be used when absolutely necessary.

DLL Hell:
" DLL Hell " refers to the set of problems caused when multiple applications attempt to share a common component like a dynamic link library (DLL) or a Component Object Model (COM) class. In the most typical case, one application will install a new version of the shared component that is not backward compatible with the version already on the machine. Although the application that has just been installed works well, existing applications that depended on a previous version of the shared component might no longer work. Sometimes, the previous version not able to produce the desired results. The reason for these issues is that version information about the different components of an application is not recorded or enforced by the system. Also, changes made to the system on behalf of one application will typically affect all applications on the machine.

The solution to this problem is GAC. This Cache is a repository for all the .NET components that are shared globally on a particular machine. When a .NET component is installed onto the machine, the Global Assembly Cache looks at its version, its public key, and its language information and creates a strong name for the component. The component is then

registered in the repository and indexed by its strong name, so there is no confusion between different versions of the same component, or DLL. .NET Framework introduced something called side- by-side execution. Side by side is the ability to install and run multiple versions of the same component on the machine concurrently at the same time without interfering with each other. With components that support side-by-side, authors aren't necessarily tied to maintaining strict backward compatibility because different applications are free to use different versions of a shared component.

Strong Name in .NET Assembly


Step1: Go to Microsoft Visual Studio 2005 >>Visual Studio Tool>> Visual Studio Command prompt. This wills popup the command prompt for you.

Step2: After the command prompt run the strong tool from there Sn.exe k c:\test.snk Here k: the key specifies that we want to generate the key. test.snk: This file contains the key that is generated by the sn.exe tool

Step3: This will create the file at the following location. When you open the file that has been generated by the strong name tool. This is not a readable format because of security reasons.

Step4: Once the strong name key/value pair is generated using the strong name utility. We need to assign it to the project.

Step5: This will assign the strong name to this project. Then compile the project again to reflect the changes. The Strong Name is needed to insert the assembly into the GAC. Add/Remove an assembly from GAC: Here you can use other .NET tool to put the assembly in the GAC i.e. gacutil.exe Go to Microsoft Visual Studio 2005 >>Visual Studio Tool>> Visual Studio Command prompt >> gacutil.exe i (assembly_name) where assembly_name is the DLL name of the project. To remove the assembly run this command. gacutil.exe u (assembly_name)

ILDASM: Intermediate Language Disassembler in .Net


This tool is used to view assembly. The ILDASM converts the whole exe or dll into IL code. This tool is included in the .NET SDK and used to view the information that is there in the assembly. This basically converts the whole exe and the dll that an application have and then converts into Intermediate code. The location where you can find this tool is as follows: \Microsoft Visual Studio .NET 2005\ SDK\v2.0\Bin\ildasm.exe Steps to use ILDASM Step1:- Pick the ILDASM.exe from the path specified above Step2:- Click on the ILDASm.exe and this will popup with an ILDASM program.

Step3:- Click on file and the open and pick the exe or dll which you want to view. This will display the IL code of the exe or dll.

Note:- After step 3, you are able to view a tree structure that will display the information about the dll or exe . Step4:- On double click on the MANIFEST node, we are able to view the details of the Assembly, internal IL code.

Manifest View
Step5:- Click on the other nodes or namespaces that are at the top of the hierarchy.

Step6:- Further you can view the internals by clicking on the sub nodes. Here I am clicking on the fxTest1: void ()

Custom Attributes in .Net


The CLR's metadata facility is extensible via custom attributes. Custom attributes provide a simple and easy means for developers to annotate a type or its members. A custom attribute is essentially a class; an instance of an attribute class is attached to a type or its members and persisted in the metadata for that type. Custom attributes share some similarities with the IDL extensions described previously:

As with structured comments, the addition of an attribute does not make the type unusable from a compiler that does not understand the attribute. In general, compilers that do not understand the custom attribute will ignore it. Naturally, this characteristic is both an advantage and a disadvantage; if the compiler does not understand the attribute, then the semantic information it conveys may be lost. Because attributes are classes, it is possible to access instances of these classes at runtime to retrieve information. This ability is similar to that offered by IDL extensions that use interfaces to generate information that can be retrieved at runtime. One limitation of custom attributes is the fact that they do not generate code that is automatically called by the CLR at runtime.

Standard Attributes
Some of the attributes are already defined in the .NET framework BCL base class libraries. These attributes are known as standard attributes. There are following standard attributes exist in .NET environment:-

Obsolete:- This attribute is used to provide the information to the developer that this method is deprecated. Webmethod:- This attribute is used by web services to indicate that this method belongs to web services.

The below picture describes the object creation and property hierarchy

The application Domain is used to isolate an application from other applications. One process has its own virtual memory and does not over lap the other process's virtual memory; due to this one process can not crash the other process. As a result any problem or error in one process does not affect the other process. In .NET they went one step ahead introducing application domains. In application domain multiple applications can run in same process without influencing each other. If one of the application domains throws error it does not affect the other application domains. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages. MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries. With the .NET architecture we have a new boundary for applications: application domains . With managed IL code the runtime can ensure that access to the memory of another application inside a single process can't happen. Multiple applications can run in a single process within multiple application domains.

Application Domain in .Net

Creating Application Domain


The AppDomain class is used to create and terminate application domains, load and unload assemblies and types, and to enumerate assemblies and threads in a domain. AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE.

When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.

Example: Demonstrate Application Domain Create a C# Console Application i.e. FirstApplication

using System; using System.Collections.Generic; using System.Text; using System.Runtime.Remoting; namespace ConsoleApplication1 { class Program1 { public Program1() { Console .WriteLine( "Constructor in First Application" ); } static void Main ( string [] args) { Console .WriteLine( " Main in domain {0} called" , AppDomain .CurrentDomain.FriendlyName); display(); } static void display() { Console .WriteLine( "Display Calls" ); } } }

Here we are creating one application that have constructor and on method. We here display the value of the current application domain that this application belongs too.

Output:

G:\cSharp-Examples\ConsolesApplications\FirstApplication\FirstApplication\bin\ Debug >FirstApplication.exe Main in domain FirstApplication.exe called Display Calls Note:-The second project created is again a C# Console Application: SecondApplication. First, display the name of the current domain using the property FriendlyName of the AppDomain class. With the CreateDomain() method, a new application domain with the friendly name New AppDomain is created. Then load the assembly FirstApplication into the new domain and call the Main () method by calling ExecuteAssembly ():
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { class Program2 { static void Main ( string [] args) { AppDomain currentDomain = AppDomain .CurrentDomain; Console .WriteLine(currentDomain.FriendlyName); AppDomain secondDomain = AppDomain .CreateDomain( "New AppDomain" ); secondDomain.ExecuteAssembly( "FirstApplication.exe" ); } } }

Note:- Befor running this application exe, place the FirstApplication.exe inside the bin folder under this application directory Output: G:\cSharpExamples\ConsolesApplications\SecondApplication\SecondApplication\bin\Debug>SecondAp plication.exe SecondApplication.exe Main in domain New AppDomain called Display Calls

Code Access Security in .Net


Code access security is a feature of .NET that manages code, dependent on our level of trust. If the CLR trusts the code enough to allow it to run, it will begin executing the code. Depending on the permissions provided to the assembly, however, it might run within a restricted environment. If the code is not trusted enough to run, or if it runs but then attempts to perform an action, for which it does not have the relevant permissions, a security exception (of type Security Exception, or a subclass of it) is thrown. The code access security system means that we can stop malicious code running, but we can also allow code to run within a protected environment, where we are confident that it cannot do any damage. CAS is part of .NET security model that determines whether or not a piece of code is allowed to run and what resources it can use while running. CAS grants rights to program depending on the security configuration of the machine, for e.g. the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. Code access security is based on two concepts: Code Groups Permissions Code Groups Bring together code with similar characteristics, although the most important property is usually where the code came from. Two examples for code groups are Internet and Intranet. The group Internet defines code that is sourced from the Internet, the group Intranet defines code sourced from the LAN. Code groups have an entry requirement called membership condition. Each code group has one, and only one, membership condition. Following is the available list of code groups memberships:

1. Zone:- The region from which the code originated. A zone is one of the commonly used condition. A zone is the region of origin of a piece of code and refers to one of the following: My Computer, Internet, Intranet, Trusted, or Untrusted. 2. Site:- The Web site from which the code originated. 3. Strong Name:- A unique, verifiable name for the code. 4. Publisher:- The publisher of the code. 5. URL:- The specific location from which the code originated. 6. Hash Value:- The hash value for the assembly.

7. Skip Verification:- This condition requests that it bypasses code verification


checks.

8. Application Directory:- The location of the assembly within the application. 9. All Code:- All code fulfills this condition. 10. Custom:- A user-specified condition.
Code groups are arranged hierarchically with the All Code membership condition at the root.

Permissions Permissions are the actions we allow each code group to perform? For example, permissions include able to access the user interface and able to access local storage. The system administrator usually manages the permissions at the enterprise, machine, and user levels. Caspol.exe [Code Access Security Policy Tool] To get the list of options available with the tool, run the following command from the command prompt: caspol.exe -?

Output: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727> caspol.exe -? Microsoft (R) .NET Framework CasPol 2.0.50727.42 Copyright (c) Microsoft Corporation. All rights reserved. Help screen requested Usage: caspol <option> <args> ... caspol -m [achine] Modifier that makes additional commands act on the machine level caspol u [ser] Modifier that makes additional commands act on the user level caspol en [terprise] Modifier that makes additional commands act on the enterprise level caspol cu caspol -customuser <path> Modifier that makes additional commands act on the custom user level caspol a [ll] Set all policy levels as the active levels

Press <enter> to continue.... To view code group available on the machine. Here after running this command, we will be available to view the code groups on the machine, and next to each group is a description of the code group. Type this command: Caspol.exe -list description

Output:
Microsoft (R) .NET Framework CasPol 1.1.4322.535 Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. Security is ON Execution checking is ON Policy change prompt is ON Level = Machine Full Trust Assemblies: 1. All_Code: Code group grants no permissions and forms the root of the code group tree. 1.1. My_Computer_Zone: Code group grants full trust to all code originating on the local computer 1.1.1. Microsoft_Strong_Name: Code group grants full trust to code signed with the Microsoft strong name. 1.1.2. ECMA_Strong_Name: Code group grants full trust to code signed with the ECMA strong name. 1.2. LocalIntranet_Zone: Code group grants the intranet permission set to code from the intranet zone. This permission set grants intranet code the right to use isolated storage, full UI access, some capability to do reflection, and limited access to environment variables. 1.2.1. Intranet_Same_Site_Access: All intranet code gets the right to connect back to the site of its origin. 1.2.2. Intranet_Same_Directory_Access: All intranet code gets the right to read from its install directory. 1.3. Internet_Zone: Code group grants code from the Internet zone the Internet permission set. This permission set grants Internet code the right to use isolated storage and limited UI access. 1.3.1. Internet_Same_Site_Access: All Internet code gets the right to connect back to the site of its origin. 1.4. Restricted_Zone: Code coming from a restricted zone does not receive any permissions. 1.5. Trusted_Zone: Code from a trusted zone is granted the Internet permission set. This permission set grants the right to use isolated storage and limited UI access. 1.5.1. Trusted_Same_Site_Access: All Trusted Code gets the right to connect back to the site of its origin. Success Viewing an Assembly Code Group Assemblies are matched to code groups dependent on the membership conditions they match. You can easily view the code groups that an assembly is a member of using this command:caspol.exe resolve group firstApplication.dll Output: Running this command on an assembly on the local drive produces this output: Microsoft (R) .NET Framework CasPol 1.1.4322.535 Copyright (C) Microsoft Corporation 1998-2002. All rights reserved. Level = Enterprise Code Groups:

1. All code: FullTrust Level = Machine Code Groups: 1. All code: Nothing 1.1. Zone - MyComputer: FullTrust Level = User Code Groups: 1. All code: FullTrust Success

Using the .NET Framework, developers can both define and share types. Defining and sharing new types in a single language is not particularly challenging; allowing a newly defined type to be used in other languages is much more problematic. This type system will help developers to achieve the concepts of interoperability. Elements of the CLR Type System

Type System in .NET -1

Value Type:

A value type consists of a sequence of bits in memory, such as a 32-bit integer. Any two 32bit integers are considered equal if they hold the same numberthat is, if the sequence of bits is identical. Value types represent types that are known as simple or primitive types in many languages. They include types such as int and float in C++ and Java. Value types are often allocated on the stack, which means that they can be local variables, parameters, or return values from functions. The following Types comes under the value type:1. Boolean Values :-The bool type is used to represent true and false values. Unlike some languages that use an integer for this type (so that a value such as 0 represents false and all other values represent true), the CLR designates a specific type for this purpose. CIL Name: bool Base Framework Name: System.Boolean 2.Characters :- All characters in the CLR are 16-bit Unicode code points . The UTF-16 character set uses 16 bits to represent characters; by comparison, the ASCII character set normally uses 8 bits for this purpose. This point is important for a component model such as the .NET Framework, for which distributed programming over the Internet was a prime design goal of the architecture. 3. Integers :-The CLR supports a range of built-in integer representations. Integers vary in three ways: Their size can be 8, 16, 32, or 64 bits. This range covers the size of integers in many common languages and machine architectures. Integers can be signed or unsigned, designating whether the values they hold are positive only or positive/negative. Native integers are used to represent the most natural size integer on the execution architecture. Because the CLR is designed to run on a number of different platforms, it needs a mechanism to inform the execution engine that it is free to choose the most efficient representation on the platform that the code executes onhence the native integer type.

4. Floating-point Types: - CLR floating-point types vary between 32- and 64-bit representations and adhere to the IEEE floating-point standard 5. User-Defined Value Types: -The following are the User-Defined Types in .Net

Enumerations :-An enumeration is a special kind of value type limited to a restricted and unchangeable set of numerical values.Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. Example:using System; namespace Enumeration { struct EnumerationSample { enum Month { January = 1, February, March, April, May, June, July, August, September, October, November, December} static int Main (string[] args) { Console.WriteLine("{0} is month {1}", Month.September,(int) Month.September); return 0; }

} } Structure: -Some languages, such as Managed C++, allow users to use a keyword such as classwhen defining either value or reference types. Other languages, such as C#, use a keyword such as struct to indicate a user-defined value type and class to indicate a userdefined reference type. Structures can contain Methods (both static and instance), Fields (both static and instance) , Properties (both static and instance) and Events (both static and instance).

Boxed Types For every value type, including user-defined value types, there exist a corresponding object type, known as its boxed type. The CLR automatically generates boxed types for userdefined value types, which means that values of any value type can be boxed and unboxed:

Type System in .NET -2

Boxing a value type copies the data from the value into an object of its boxed type allocated on the garbage collected heap. UnBoxing a value type returns a pointer to the actual datathat is, the sequence of bits held in a boxed object. (In some programming languages, unboxing not only facilitates obtaining the pointer to the data members of a boxed object but also copies the data from the boxed object into a value of the value type on the stack.)

Reference Types
Reference Types combine the address of a value (known as its identity) and the value's sequence of bits. Reference types can, therefore, be compared using both identity and equality. Identitymeans that two references refer to the same object; equalitymeans that two references refer to two different objects that have the same datathat is, the same sequence of bits. References types differ from value types in the following ways:

Value types always directly inherit from System.ValueType or System.Enum , which itself inherits from System.ValueType . The types are always sealed, which means that no other types can inherit from them. Reference types, in contrast, inherit from any class other than System.ValueType or System.Enum . Reference types are always allocated on the garbage collected heap, whereas value types are normally allocated on the stack. However, that value types may be allocated on the garbage collected heapfor instance, as members of reference types. Reference types are accessed via strongly typed references. These references are updated if the garbage collector moves an object.

Note:- All types derive from System.Object base type are reference types. 1] Object Types All object types inherit, either directly or indirectly, from the CLR type System.Object class. A major facility of the Object class is its ability to enforce a singular rooted inheritance hierarchy on all types in the CLR. Although you may think that this kind of inheritance does not apply to value types, value types can be treated as a subtype of Object through boxing.

The libraries make extensive use of the Object type as the parameters to, and the return type of, many functions. The Object class provides a number of methods that can be called on all objects:

Equals: returns true if the two objects are equal. Subtypes may override this method to provide either identity or equality comparison. Equals is available as both a virtual method that takes a single parameter consisting of the other object with which this object is being compared and a static method that, naturally, requires two parameters. Finalize: is invoked by the garbage collector before an object's memory is reclaimed. Because the garbage collector is not guaranteed to run during a program's execution, this method may not be invoked. In C#, if a developer defines a destructor, then it is renamed to be the type's Finalize method. GetType: returns the type object for this object. This method gives access to the metadata for the object. A static method on the Type class can be used for the same purpose; it does not require that an instance of the class be created first. GetHashCode: returns a hash code for an object. It can be used when inserting objects into containers that require a key to be associated with each such object. ToString: returns a string that represents the object. As defined in Object , this method returns the name of the type of the objectthat is, its exact type. Subtypes may override this method to have the return string represent the object as the developer sees fit. For example, the String class returns the value of the string and not the name of the String class

2] Interface Types
Interface-based programming is the predominate paradigm. Object-oriented programmers will already be familiar with the concept of substituting a derived type for a base type. Interface implements the concept of multiple inheritances. An interface type is a partial specification of a type. This contract binds implementers to providing implementations of the members contained in the interface. Object types may support many interface types, and many different object types would normally support an interface type. By definition, an interface type can never be an object type or an exact type. Interface types may extend other interface types; that is, an interface type can inherit from other interface types. An interface type may define the following:

Methods (static and instance) Fields (static) Properties Events

Pointer Types Pointer types provide a means of specifying the location of either code or a value. The CLR supports three pointer types:

Unmanaged function pointers refer to code and are similar to function pointers in C+ + i.e. delegates. Managed Pointers are known to the garbage collector and are updated if they refer to an item that is moved on the garbage collected heap. Unmanaged pointers are similar to unmanaged function pointers but refer to values. Unmanaged pointers are not CLS compliant, and many languages do not even expose syntax to define or use them. By comparison, managed pointers can point at items located on the garbage collected heap and are CLS compliant.

Common Type System: In order that two languages communicate smoothly CLR has CTS (Common Type System). Example VB you have Integer and in C++ you have long these data types are not compatible so that interfacing between them is very complicated. In order that two different languages can communicate Microsoft introduced CTS so Integer data type in VB6 and int data type in C++ will convert it to System.int32 which is data type of CTS.CLS

Type Safety

Introduction to Generics

Many of the languages in .NET, like C#, C++, and VB.NET (with option strict on), are strongly typed languages. As a programmer using these languages, you expect the compiler to perform type-safety checks. For e.g. If you try to cast a variable of type person to type student, then the compiler will give you the message that this type of cast is invalid. But in .NET framework, compiler doesn't provide any type safety help for collections; this means the collections doesn't provide the type safety at the time of compilation

Demonstration: Inserting different type values in Arraylist Collection


using System; using System. Collections; namespace TestApp { class Test { [STAThread] static void Main (string[] args) { ArrayList templist = new ArrayList(); templist.Add(3); templist.Add(4); // templist.Add(5.0) // Runtime Exception Occurs Not CompileTime Error int listTotal = 0; foreach(int arrVal in templist) { listTotal = listTotal + arrVal; } Console.WriteLine ("List Total is {0}", listTotal); } }

Note:- Here I comment the line templist.Add(5.0). If I uncomment this line this will throw runtime exception. We know the ArrayList collections hold a collection of objects. When we are adding values in the array list this is called boxing. Here also, when we add 5.0 we are boxing a double. But when we are adding the array value, here the double value is unboxed as an int; this causes an exception to occur.

Generics: Generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, they are very different in their implementation. They allow developers to realize about type safety at compile time.System.Collections.Generics namespace contains the generic collections in .Net2.0. Demonstrate: Type Safe generic list The above example code has to be changed as the below code for generics.
List<int> aList = new List<int> (); aList.Add(3); aList.Add(4); // aList.Add(5.0); int total = 0; foreach(int val in aList) { total = total + val; } Console.WriteLine("Total is {0}", total);

Here, I am creating an instance of the generic List with the type int, given within the angle brackets (<>), as the parameterized type. This code, when executed, will produce the result "Total is 7." Now, if I uncomment the statement aList.Add(5.0), I will get a compilation error. The compiler determines that it can't send the value 5.0 to the method Add(),as it only accepts an int Constraints and Benefits of Generic Classes: The generic classes provide user to create class that can be indicated at the later stages which type to be used. This also provides some constraints. Example: Demonstrate Constraints while using Generic classes
public static T Max<T>(T op1, T op2) { If (op1.CompareTo (op2) < 0) return op1; return op2; }

Note: The code will produce compilation error. "Error 1 'T' does not contain a definition for 'CompareTo' " Assume I need the type to support the CompareTo () method. I can specify this by using the constraint that the type specified for the parameterized type must implement the IComparable interface. This can be solved by putting public static T Max<T> (T op1, T op2) where T: IComparable Note:- The above constraints can be used, where.

T [is struct] type must be a value type (a struct) T [is class] type must be reference type (a class) T [is new ()] type must have a no-parameter constructor T [is class_name] type may be either class_name or one of its sub-classes (or is below class_name in the inheritance hierarchy) T [is interface_name] type must implement the specified interface

Generic Classes and Methods


CLR Support for Generics: CLR supports and recognize generics. The important concept behind this is for instance, if you define a generic type MyList<T>, only one definition of that type is present in MSIL. When the program executes, different classes are dynamically created, one for each type for the parameterized type. If you use MyList<int> and MyList<double>, then two classes are created on the fly when your program executes. Generic Class in .NET 2.0 Demonstrate: Example of Generic Class
//******************************MyList.cs************************ #region Using directives using System; using System.Collections.Generic; using System.Text; #endregion namespace CLRSupportExample { public class MyList<T> { private static int objCount = 0; public MyList () { objCount++; } public int Count { get { return objCount;} } } } //****************************Program.cs************************* #region Using directives using System; using System.Collections.Generic; using System.Text;

#endregion namespace CLRSupportExample { class SampleClass {} class Program { static void Main (string[] args) { MyList<int> myIntList = new MyList<int>(); MyList<int> myIntList2 = new MyList<int>(); MyList<double> myDoubleList= new MyList<double>(); MyList<SampleClass> mySampleList= newMyList<SampleClass>(); Console.WriteLine(myIntList.Count); Console.WriteLine(myIntList2.Count); Console.WriteLine(myDoubleList.Count); Console.WriteLine(mySampleList.Count); Console.WriteLine(new MyList<SampleClass>().Count); Console.ReadLine(); } } }

Here we have generic class named MyList. Within the MyList class, I have a static field, objCount. I am incrementing this within the constructor so I can find out how many objects of that type is created by the user of my class. The Count property returns the number of instances of the same type as the instance on which it is called. In the Main() method, I am creating two instances of MyList<int>, one instance of MyList<double>, and two instances of MyList<SampleClass>, where SampleClass is a class I have defined. Output: 2 2 1 1 2

We have generic methods in .Net2.0. The generic methods can be associated to any class. Demonstrate: Generic Method
public class GenericMethodDemo { public static void Copy<T> (List<T> source, List<T> destination) { foreach (T obj in source) { destination.Add(obj); } } static void Main (string[] args) { List<int> lst1 = new List<int>();

Generic Methods in .NET 2.0

lst1.Add(2); lst1.Add(4); List<int> lst2 = new List<int>(); Copy (lst1, lst2); Console.WriteLine(lst2.Count); } }

Note:-The Copy() method is a generic method that works with the parameterized type T. When Copy() is invoked in Main (), the compiler figures out the specific type to use, based on the arguments presented to the Copy() method.

Overview of Inheritance in Generics classes


Generics classes are further sub divided into two types on the basis of there declaration:

1. Open-Constructed Generic:- These are those classes where the input parameters
are defined as T. E.g. MyGenericClass<T> where T is the parameter that is passed to the MyGenericClass. 2. Closed- Constructed Generic:- A generic Class that uses no parameterized types is called closed constructed generic classes. For e.g. MyGenericClass2<int> is closed constructed generic class.

Inheritance: Inheritance is the process of extending or inheriting the features or behavior of one class into another class. We can say that inheritance is the process, by which one class inherits the behavior/features /functionality of other class. Inheritance in Generic Classes:

Inheriting closed constructed generic class into open constructed generic class. example:- public class MyGenericClass2<T>: MyGenericClass1<int>{} Inheriting open constructed type is possible only if it has parameters associated to it. example:- public class MyGenericClass2<T>: MyGenericClass1<T> {} Non generic classes: Non-generic classes can be derived from closed constructed generic classes. example:- public class MyGenericClass2: MyGenericClass1<int> {} Non-generic classes: Non-generic classes can't be derived from open constructed generic classes. example:- public class MyGenericClass2: MyGenericClass1<T> {}

A connection pool is a set of database connections that are available for an application to use. Connection Pooling is the concept of using a connection pool for enhanced performance. As we know every application requires connection to database to perform operations like insert, update and delete and to fetch records from database to display. This requires a connection to be specified between the applications so that user can transfer data to and fro from the database server. Connection pooling is the concept that helps in maintaining or reusing the already open connection and hence improves site performance.

Connection pooling in .NET Applications

Connection pooling is used to enhance the performance of executing commands on a database. Before executing a command a connection to that database needs to be established. Sometimes creating and tearing down the connection is more costly then executing the command. Concept behind Connection Pooling:

When a user request a connection, it is returned from the pool rather than establishing new connection and, when a user releases a connection, it is returned to the pool rather than being released. Be sure than your connections use the same connection string each time. Connection pooling only works if the connection string is the same. If the connection string is different, then a new connection will be opened, and connection pooling won't be used. Connection pooling is extremely useful when used with applications that do not have a state. State is a presence between instances. Active Server pages are considered stateless since they do not share data between themselves. Stateless applications benefit from connection pooling since they cannot hold a connection open by themselves. The main benefit of pooling is performance. Making a connection to a database can be very time-consuming, depending on the speed of the network as well as on the proximity of the database server. When pooling is enabled, the request for a database connection can be satisfied from the pool rather than by (re)connecting to the server, (re)authenticating the connection information, and returning (again) a validated connection to the application. Multiple connections, all of which may not be of use, to the database are open, this is the flaw in the connection pooling, and developer must address this first before implementation of connection pooling.

Managing Connection Pooling Connection pooling allows you to reuse connections that are already opened, rather than creating a new one every time we need to send/retrieve the data from the database. Connection pooling behavior can be controlled by using connection string. For E.g. In Ado.NET data providers, connection string options can defines:

Number of connections pools Number of connections in a pool Lifetime of pooled connections used by each process.

Note:- Connection pooling in Ado.NET is not provided by the core components of .NET framework, this must be implemented in the Ado.NET data provider itself. Creating a Connection Pool The connection pool is associated with a specific connection string. By default, the connection pool is created when the first connection with a unique connection string connects to the database. The pool is populated with connections up to the minimum pool size. Additional connections can be added until the pool reaches the maximum pool size.

Pool remains active as long as connection remains open

If a new connection is open, the connection string doesn't match with the one which is used earlier to connect to the database, then new connection pool will be created. Connection pooling enhanced the performance and scalability of the applications. Once created connection pools are not destroyed until the active process ends or the connection lifetime is exceeded.

Example - Demonstrate Connection Pooling


In below code snipplet Connection Pool A is created and filled with connections upto the minimum pool size . SqlConnection con = null; string conStr = ""; conStr = "Data Source=localhost; initial catalog=TestDB; uid=sa; pwd=sa; Min Pool Size=50"; con = new SqlConnection(conStr); con.open();

Opening and Closing Connections Open connections just before they are needed. Opening them earlier than necessary decreases the number of connections available to other users and can increase the demand for resources. One should explicitly close the connection as soon as it is no longer in use. If one waits for garbage collection to implicitly close connection that go out of scope, the connections are not returned to the connection pool immediately. Always, close connection in the finally block, because code in the finally block always runs, regardless of whether an exception occurs. This guarantees explicitly closing of connection. For example:
Try { Con.open (); } Catch (Exception ex) { // Handle Exception } Finally { // Close the Connection If (Con! = null) Con.close (); }

Deployment in .Net
Microsoft with its .NET Framework brings in some novel, flexible and easy way to deploy the developed Windows and Web applications. The .NET Framework offers many characteristics that make it easier to deploy the applications. These features are as follows:

No-touch deployment: .NET Framework gets rid of DLL conflicts. Installing or removing of components does not affect other applications. Thus it provides a solution to DLL Hell problem. No-impact applications, which offers application isolation and purge DLL conflicts. Controlled code sharing: Sharing is explicit rather than the default. XCOPY deployment and reproduction: XCOPY deployment is appropriate to be used in certain specific simple deployment scenarios. With Self-described and self-contained components and applications there is no need for registry entries or dependencies. This facilitates to install desktop applications on client machines using a remote web server. Integration with the Windows Installer: Advertisement, publishing, repair, and install-on-demand are all on hand when deploying the application. In Visual Studio.NET the deployment tools are built on the groundwork of Windows Installer, which offers rich capabilities for swift deploying and easy maintenance of applications. Private components by default: By default the components are deployed to the application directory. Side-by-side versioning: We can run one version of the application side-by-side (The CLR can manage multiple versions of a software component to be run concurrently) with another version. We can also decide which versions to employ, and versioning policy is enforced by the common language runtime.

In Visual Studio.NET if you compile a project, the code-behind class file (.aspx.vb, or .aspx.cs) is compiled into a .dll file along with all other class files which are incorporated with the project. If a request is made for that ASP.NET page, then the .dll file is instantiated and executed. You can modify the visual elements of Web form pages without recompiling and redeploying. But you can't change the code without recompiling. Usually the .dll file is stored in the web application's bin directory. There are methods for deploying ASP.NET applications.

XCopy deployment. Setup Wizard

XCopy Deployment:
The easiest method to copy a project or application from one location to another is to employing XCopy. XCopy deployment is a trouble-free technique to install simple .NET applications. Usually this method is not employed in the Windows due to the convolution and COM/COM+ Component registrations. In the past, for registering the components we have to employ Regsvr32.exe utility etc. Typically for deploying an application we copy the application or component into the virtual directory of the Web server. With self-describing assemblies and versioning to the .NET Framework, there are no more registry entries, which facilitate to make use of XCOPY for deployment.

In ASP.NET, XCopy deployment refers to copy required files from one location to another location (Virtual directory on the Web server) by employing the drag-and-drop feature in Microsoft Windows Explorer, File Transfer Protocol (FTP), or the DOS XCopy command. XCOPY deployment is accomplished from the command prompt. You use the XCOPY command to specify the source directory and the target directory. The /s flag indicates that

subdirectories are to be copied as well. For example, the following command-line command is used to copy the MyApplication directory and all subdirectories from drive D to drive C:

XCOPY D:\MyApplication C:\MyApplication /s To deploy your application using XCOPY Verify that your application meets the requirements for XCOPY deployment. Open the command window. To locate the command window in Microsoft Windows XP, click Start, All Programs, and Accessories. Run XCOPY from the command prompt, specifying the source and destination directories and including any command-line flags, such as the /s example cited previously.

Setup Wizard VS .NET installer provides you with the functionality where you can distribute your Web application as a collection of build outputs, installer classes, and database creation scripts; it is often easier to deploy complex solutions with Windows Installer files. VS .NET provides Web setup projects that can be used to deploy Web applications. These Web setup projects differ from standard setup projects in that they install Web applications to a virtual root folder on a Web server rather than in the Program Files folder, as is the case with the applications installed using standard setup projects. The Windows Installer divides applications into the following three levels.

Product: - It is something a user can install. For example, MS Word is a product that a user can install. Feature: - A product is composed of multiple features. A feature is also the smallest unit of functionality of a product. For example, AutoCorrect functionality can be considered a feature of MS Word. Component:- A component can be considered the smallest unit that can be shared across multiple features and components. It is very important to understand that the component in Windows Installer terms is not the same as the term component in the .NET Framework. A Windows installer component can be a single file or multiple files that logically belong together. It can be an executable, a dll, or a simple text file. A collection of components can form together to provide a feature and it is also possible for a component to be shared across multiple features. While features are specific to a product and identified by a name unique only within the product, components are global across all products installed on a machine. For example, the spell checker component of MS Word can be shared across all the applications that want to implement spell-checking feature.

Creating a Web Setup Project Using VS .NET Installer Step1: First Go to File>Add Project>New Project from the main menu. In the New Project dialog box, select setup and deployment projects from the Project type's pane and then select Web Setup project in the template pane. Step2: After creating the project, you then need to add the output of the primary assembly and the content files of the ASP.NET Web application to the setup project. Right click on the particular project and then in the solution explorer and select Add->Project Output from the context menu. In the Add Project Output Group dialog box, select the application from the Project combo box and select Primary Output from the list.

Step3: After adding the project output, you then need to add the related Content Files (such as .aspx files, Images, and so on) to the project. To do this, again bring up the Add Project Output dialog box and then select Content Files from the list this time. Step4: Configuring Properties through the Properties Window: There are a number of properties that you can set through the properties window of the Web Setup project. These properties determine the runtime display and behavior of the Windows installer file. The properties window provides properties such as Author, Description, Manufacturer, Support Phone and so on that can be very useful to the users (who are installing your application) of your application to get more details about your application. Note:- Once we through with this, the .msi file are there where we can use it to install the Asp.NET Web Application.