unit v(dotnet)

39
http://www.codeproject.com/books/186100558x_16.asp Introduction In this article we are going to look at Microsoft .NET Framework. This is the newly established software development environment which helps developers to develop applications quickly and gives optimum, efficient, scalable, performance oriented applications in different languages like Visual Basic .NET, C#, ASP .NET, and Jscript .NET etc... Overview of the .NET Framework The .NET Framework is a new computing platform that simplifies application development in the highly distributed environment of the Internet. Services NET Framework provides the following services: Tools for developing software applications , run-time environments for software application to execute, server infrastructure, value added intelligent software which helps developers to do less coding and work efficiently, The .Net Framework will enable developers to develop applications for various devices and platforms like windows application, web applications, windows services and web services. Objectives The .NET Framework is designed to fulfill the following objectives: A consistent object-oriented programming environment, where object code can be stored and executed locally, executed locally but Internet-distributed, or executed remotely. A code-execution environment that minimizes software deployment and versioning conflicts. A code-execution environment that guarantees safe execution of code, including code created by an unknown or semi-trusted third party. A code-execution environment that eliminates the performance problems of scripted or interpreted environments. Developers can experience consistency across widely varying types of applications, such as Windows-based applications and Web-based applications. Build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code.

Upload: sonal-shirsat

Post on 04-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 1/39

http://www.codeproject.com/books/186100558x_16.asp

Introduction

In this article we are going to look at Microsoft .NET Framework. This is the newlyestablished software development environment which helps developers to develop

applications quickly and gives optimum, efficient, scalable, performance orientedapplications in different languages like Visual Basic .NET, C#, ASP .NET, and

Jscript .NET etc...

Overview of the .NET Framework 

The .NET Framework is a new computing platform that simplifies application

development in the highly distributed environment of the Internet.

Services

NET Framework provides the following services:

• Tools for developing software applications ,

• run-time environments for software application to execute,

• server infrastructure,

• value added intelligent software which helps developers to do less coding and

work efficiently,

The .Net Framework will enable developers to develop applications for various

devices and platforms like windows application, web applications, windows servicesand web services.

Objectives

The .NET Framework is designed to fulfill the following objectives:

• A consistent object-oriented programming environment, where object codecan be stored and executed locally, executed locally but Internet-distributed,

or executed remotely.

• A code-execution environment that minimizes software deployment andversioning conflicts.

• A code-execution environment that guarantees safe execution of code,

including code created by an unknown or semi-trusted third party.• A code-execution environment that eliminates the performance problems of 

scripted or interpreted environments.

• Developers can experience consistency across widely varying types of 

applications, such as Windows-based applications and Web-basedapplications.

• Build all communication on industry standards to ensure that code based on

the .NET Framework can integrate with any other code.

Page 2: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 2/39

Understanding the .NET Framework Architecture

The .NET Framework has two components: the .NET Framework class library andthe common language runtime.

The .NET Framework class library facilitates types (CTS) that are common toall .NET languages.

The common language runtime consists of (class loader) that load the IL code of 

a program into the runtime, which compiles the IL code into native code, andexecutes and manage the code to enforce security and type safety, and provide

thread support.

.NET Framework Architecture has languages at the top such as VB .NET C#, VJ#,VC++ .NET; developers can develop (using any of above languages) applications

such as Windows Forms, Web Form, Windows Services and XML Web Services.Bottom two layers consist of .NET Framework class library and Common Language

Runtime. This we are going to understand using this article.

Understanding the Role of .NET Framework 

The .NET Framework has two main components: the common language runtime

(CLR) and the .NET Framework class library. The common language runtime is thefoundation of the .NET Framework. CLR act as an agent that manages code at

execution time, providing core services such as memory management, threadmanagement, and remoting, while also enforcing strict type safety and facilitates

with code accuracy that ensure security and robustness. The concept of codemanagement is a fundamental principle of the CLR. Code that targets the CLR is

Page 3: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 3/39

known as managed code, while code that does not target the CLR is known asunmanaged code.

The class library, is a integral component of the .NET Framework, consists of object-

oriented collection of reusable classes (types) that we can use to developapplications ranging from traditional command-line or any graphical user interface

(GUI) applications such as Windows Forms, ASP. NET Web Forms and WindowsServices the newly invented XML Web services.

The European Computer Manufacturers Association (ECMA) standard has

defines the Common Language Specification (CLS); this enforces that softwaredevelopment languages should be interoperable between them. The code written in a

CLS should be compliant with the code written in another CLS-compliant language.Because the code supported by CLS-compliant language should be compiled into an

intermediate language (IL) code. The CLR engine executes the IL code. This ensuresinteroperability between CLS-compliant languages. Microsoft .NET Framework

supports Languages like Microsoft Visual Basic .NET, Microsoft Visual C#, MicrosoftVisual C++ .NET, and Microsoft Visual J# .NET.

The language compilers generate an Intermediate Language code, called MicrosoftIntermediate Language (MSIL), which makes programs written in the .NET languages

interoperable across languages.

The ECMA standard, Common Language Infrastructure (CLI), defines the

specifications for the infrastructure that the IL code needs for execution. The CLIprovides a common type system (CTS) and services such as type safety, managed

code execution and side by side execution.

Figure 1. ECMA Standards under Microsoft .NET Framework.

The .NET Framework provides the infrastructure and services. The CLI specifications.

These include:

Page 4: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 4/39

Common language runtime.

• The CLR includes the CLI,

• The CLR also provides the execution environment for .NET Applications.

Common type system.

• Provides the data types, values, object types. This helps developers to

develop applications in different languages. Where .NET languages share CTSmean all the types used in applications shares the same types defined under

CLI.

Type safety.

• .NET Framework performs operations on the values or objects for which .NET

Framework requires each value or object has a type and which reference tothe value or object type.

Managed code execution.

• .NET Framework manages the state of the object while executing the .NETApplications.

• .NET Framework automatically allocates memory and provides garbage

collation mechanism to de-allocate memory.

Side-by-side execution.

• .NET Framework allows different version of the same application to run on the

same machine by using assemblies of different versions.

• Assemblies consist of IL Code and Metadata. Where metadata determines the

application dependencies. By this .NET Framework Runtime executes multipleversion of assembly and solves the major problem of legacy developmentenvironment. That is the “DLL HELL”.

Page 5: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 5/39

.NET Assembly

Figure 2 Side-by-side Execution.

Understanding .NET Framework CLR 

The common language runtime facilitates the followings:

Run-time environment and

• CLR Compiles application into the runtime, compile the IL code into native

code, execute the code

Run-time services.

• Memory management,

• Type safety,

• Enforces Security,

• Exception Management.

• Thread support

• Debugging support

Understanding Architecture of .NET Framework CLR 

Page 6: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 6/39

• Class loader, which loads classes into CLR.

• MSIL to native code compiles, this converts MSIL code into native code.

• Code manager, this manages the code during execution.

• Memory allocation and Garbage collector, this performs automatic memory

management.

• Security engine, this enforces security restrictions as code level security folder

level and machine level security using tools provided by Microsoft .NET andusing .NET Framework setting under control panel.

• Type checker, which enforces strict type checking.

• Thread support, which provides multithreading support to applications.• Exception manager, which provides a mechanism to handle the run-time

exceptions handling.

• Debug engine, which allows developer to debug different types of 

applications.

• COM marshaler, which allows .NET applications to exchange data with COM

applications.

• Base class library support, which provides the classes (types) that the

applications need at run time.

Features of the Common Language Runtime

The CLR has the following Features

• Manages memory,

o Allocation of Memory

o De-Allocation of Memory (garbage collation)

• Thread execution support,

• Code execution,

• Code safety verification,

Page 7: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 7/39

• Compilation.

o MSIL to Native Code.

• Code Security based on Trust (granted permission to execute code. Codelevel, Folder level, Machine level)

These features are intrinsic to the managed code that runs on the common language

runtime.

Understanding CLR 

To execute the program and gain all the benefits of managed execution environmentwe write code in a language which is supported by CLS that is .NET Framework. The

language compiler compiles the source code into the MSIL code which consists of CPU- independent code and instructions which is platform independent. MSIL

consists of the followings:

• Instructions that enables to perform arithmetic and logical operations

Access memory directly.• Control the flow of execution,

• Handles exceptions,

MSIL code can be compiling into CPU specific instructions before executing, for which

the CLR requires information about the code which is nothing but metadata.Metadata describes the code and defines the types that the code contains as well

referenced to other types which the code uses at run time.

An assembly consists of portable executable file. At the time of executing PE file the

class loader loads the MSIL code and the metadata form the portable executable fileinto the run time memory.

Before the execution of PE file it passes the code to the native code compiler for

compilation, IL to native code compilation is done by JIT compiler. For different CPUarchitecture and compilers for the IL code in to the native instructions.

Future of CLR 

• Managed multithreading support and monitor the threads. Application domaincontains one or more threads to execute.

• Manages interoperability with unmanaged code, and COM marshaling

• A structured exception handling mechanism,

• The infrastructure and managed execution process, memory management

and garbage collection.

Architecture of CLR 

Page 8: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 8/39

• Base class library support supports all the base classes used for .net

languages to support basic functionality

• COM Marshaler supports Marshaling of data between COM objects.

• Exception management supports handling Errors at runtime using try catchfinally blocks.

• Security engine enforces security rules at runtime.

• Type checker checks for Type safe checks at runtime.

• Debug engine supports debugging at runtime.

• Code manger manages the Managed code at runtime.

• IL to native compiler compiles the MSIL code to the Native code which is

machine independent

• Garbage collector supports the Memory management and supports Clearingunused memory at runtime.

• Class loader lodes the classes at runtime

Understanding JIT compiler

JIT compiler compiles is the integral part of CLR. the MSIL code to Native code and

executes the batch of code Just in time which will be cached and next time when the

code gets executed from cache in stud of compiling again.

Page 9: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 9/39

JIT Execution process.

CLR class loader lodes MSIL code and metadata are loaded into memory; the codemanager calls the entry point method which is WinMain or DLLMain method. The JIT

compiler compiles the method to before its execution of the entry point method. Thecode manager places the objects in memory and controls the execution of the code.

The garbage collector performs periodic checks on the managed heap to identify theobjects which is not in use for the application.

At the time of program execution the type checker ensures that all objects andvalues, and the references of objects and values has its valid type. The type checker

also makes sure that only valid operations are performed on the code other wise the

exception will be thrown. The code is controlled by CLR at run time. CLR enforcessecurity in following manner.

• To control and access the system recourses like hard disk

• To control and access the network connections

• To control and access the other hard ware resources.

Managed code Execution

Managed code execution is known as the process executed by the CLR which is as

follows:

• CLR loads the MSIL & refers metadata,

• CLR executes the Native code,

• CLR provides automatic memory management.

• Managed execution also performs JIT compilations,

• Ensuring type safety,

• Enforcing security,

• Handling exceptions.

Page 10: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 10/39

Managed Execution Process

Managed code is self-explanatory code which gives information to CLR for multipleruntime services in .NET Framework.

This information is stored in MSIL code in the form of metadata inside the PE file.Mata data information will describe the types that the code contains.

Managed data is allocated and released from memory automatically by garbage

collection. Managed data can be accessible form managed code but managed codecan be accessible from managed and unmanaged data.

Memory Management

Automatic memory management means no need to write code to allocate memory

when objects are created or to release memory when objects are not required the

application.

The process of automatic memory management involves the following tasks:

Allocating memory

When a process is initialized, the runtime reserves a contiguous address spacewithout allocating any storage space for it. This reserved address space is called a

managed heap. The managed heap keeps a pointer at the location where the nextobject will be located. When an application uses the new operator to create an

object, the new operator checks whether the memory required by the object isavailable on the heap.

When the next object is created, the garbage collector allocates memory to theobject on the managed heap, Allocating memory to the objects in a managed heap

takes less time than allocating unmanaged memory. In unmanaged memory, thepointers to memory are maintained in linked-list data structures. Therefore,

allocating memory requires navigating through the linked list, finding a largememory block to accommodate the

You can access objects in managed memory faster than objects in unmanagedmemory because in managed memory allocation, objects are created contiguously in

the managed address space.

Releasing Memory

The garbage collector periodically releases memory from the objects that are nolonger required by the application.

Every application has a set of roots. Roots point to the storage location on themanaged heap. Each root either refers to an object on the managed heap or is set to

null. An application's roots consist of global and static object pointers, local variables,and reference object parameters on a thread stack. The JIT compiler and the run-

Page 11: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 11/39

time maintain the list of the application roots. The garbage collector uses this list tocreate a graph of objects on the managed heap that are reachable from the root list.

When the garbage collector starts running, it considers all the objects on the

managed heap as garbage. The garbage collector navigates through the applicationroot list, it identifies the objects that have corresponding references in the

application root list and marks them as reachable. The garbage collector alsoconsiders such objects as reachable objects. The garbage collector considers allunreachable objects on the managed heap as garbage.

The garbage collector performs a collection process to free the memory occupied bythe garbage objects. The garbage collector performs the memory copy function to

compress the objects in the managed heap. The garbage collector updates thepointers in the application root list so that the application roots correctly point to the

objects to which they were pointing earlier. The garbage collector uses a highlyoptimized mechanism to perform garbage collection. It divides the objects on the

managed heap into three generations: 0, 1, and 2. Generation 0 contains recentlycreated objects. The garbage collector first collects the unreachable objects in

generation 0. Next, the garbage collector compacts memory and promotes thereachable objects to generation 1. The objects that survive the collection process are

promoted to higher generations.

The garbage collector searches for unreachable objects in generations 1 and 2 onlywhen the memory released by the collection process of generation 0 objects is

insufficient to create the new object. The garbage collector manages memory for allmanaged objects created by the application. The garbage collection can explicitly

release these system resources by providing the cleanup code in the Dispose method

of the object. We need to explicitly call the Dispose method after you finish workingwith the object.

Implementing Finalizers

The finalization process allows an object to perform cleanup tasks automatically

before garbage collection starts.

The Finalize method ensures that even if the client does not call the Dispose

method explicitly, the resources used by the object are released from memory whenthe object is garbage collected. After the garbage collector identifies the object as

garbage during garbage collection, it calls the Finalize method on the object before

releasing memory. Finalizers are the methods that contain the cleanup code that is

executed before the object is garbage collected. The process of executing cleanupcode is called finalization. The Dispose and Finalize methods are called finalizers.

The Dispose method of an object should release all its resources in addition to the

resources owned by its parent object by calling the Dispose method of the parent

object.

We can execute the Dispose method in two ways.

o The user of the class can call the Dispose method on the object that is being

disposed, or

Page 12: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 12/39

o The Finalize method can call the Dispose method during the finalization

process.

.NET Framework Tools

Assembly Linker - Al.exe Tool

Al tool can create an assembly or resource file with the manifest in a separate file out

of modules.

Syntax: al [source] [options]

This tool allows us to create multi-file assembly outside .NET. A multi-file assembly is

useful to combine modules developed under different .NET languages into a singleapplication.

IL Assembler - Ilasm.exe Tool

When we compile managed code, the code is converted into MSIL code; this is CPUindependent language which is converted to native code.

We can use Ilasm tool to generate a portable executable (PE) file from the MSILcode. The resulting executable file is performance optimized, where the Ilasm tool

does not create intermediate object file

Syntax: Ilasm [source] filename [options]

We can specify multiple source files to produce a single PE file.

IL Disassembler - Ildasm.exe Tool

Ildasm tool is used to view PE file contains that is nothing but the MSIL code as aparameter and creates the text file that consists of managed code.

Code Access Security Policy Tool - Caspol.exe Tool

Caspol is nothing but Code Access Security Policy tool, which allows us to grant and

modify permissions granted to code groups at the user-policy, machine-policy, andenterprise-policy levels. Etc...

Syntax: caspol [options]

.NET Framework Configuration Tool - Mscorcfg.msc

With this tool we can manage and configure assemblies in to the global assemblycache. And also manage the code access security along with remoting services.

Page 13: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 13/39

This tool also creates code group policies at user level- policies, machine level-policies, and enterprise level policies to assign and remove the permissions on

assemblies developed within .NET Framework.

Introduction

Being a contributor to the Code Project for quite some time now, it is commendable

to see so many articles from various folks in the industry talk about the featuresof .NET and how a specific features work or what are some of the tips and tricks of 

the trade. This fever of .NET is very interesting to watch and rest assured that thestorms caused by .NET will be as great as the storms caused by C++ when it was

introduced. Walking down the web-site, I saw lots of articles on .NET, but I did notsee one on: What is NET? What is it made up of? Why is there so much interest in it? 

This article is a dedication to the above answers. In this article, I will give an

understanding of what is .NET and why it came into existence. We will also see someof the core building blocks of .NET and how it is layered. For a deeper insight into

each of the building blocks, you anyways have lots of good articles on the CodeProject web site. So happy reading!

Why .NET

The world of computing till date has been chaotic. We have had various languagesstruggling to interoperate with each other, developers undergoing huge learning

curves to shift from one language to another or from one application type to another,non-standard ways of modeling applications and designing solutions and huge

syntactic differences between languages. The list goes on....

Past years have seen some solace in the form of enterprise "glue" applications andstandards like COM, which put-forth a binary standard of interoperability between

application components. But in reality, this was not always true (VB COM found itvery difficult to take on VC++ COM). Also, as applications increased in their reach, it

was found that rather than re-inventing the wheel for a solution, it was better to takethe "service" of another applications specialized for a piece of work.

Thus from a paradigm where applications replicated code to provide commonservices, we have moved to a paradigm where applications are built as "collaborative

units" of components working together. This simple shift has led to the collapse of the current set of architectures and demanded a new programming model:

• A model where applications can be built as reusable components and are

sharable over the internet.

• A model that encourages applications to be shared as a "service" (read webservices).

• A model that enables true "interoperability" wherein the language used is only

a matter of choice, thus enabling organizations to take advantage of existingskill sets.

Page 14: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 14/39

Enter .NET. The .NET Framework is a new computing platform developed byMicrosoft that simplifies application development in the highly distributed

environment of the internet. .NET is much more than just a platform for developingfor the internet, but it is intended for this purpose predominantly, because here,

others methods have failed in the past.

Overview of .NET

The .NET Framework has been developed to cater to the following objectives and

requirements:

• To provide a consistent object-oriented environment to develop applications.

• To provide a code execution environment that simplifies deployment andversioning.

• To provide a code execution environment that guarantees the safety of the

code that is executing. This includes both code developed internally by anorganization or for code developed by 3rd party vendors.

To provide a code execution environment that eliminates the issues faced byscripted environments with respect to performance.

• To provide a common programming model where the choice of a

programming language becomes a matter of choice.

The .NET Framework is made up of two major components: the common languageruntime (CLR) and the framework class library (FCL). The CLR is the foundation of 

the .NET Framework and provides various services that applications can use. TheCLR also forms the “environment” that other applications run on. The FCL is a

collection of over 7000+ types that cater to all the services, and data structures thatapplications will ever need.

The following diagram shows the .NET Framework, its hierarchy and the associated

toolset. The diagram is so famous that you can spend some time memorizing itslayout!!

Page 15: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 15/39

At the base of the diagram, you see the operating system which can be(theoretically) any platform. The Common Language Runtime (CLR) is the substrate

that abstracts the underlying operating system from your code. The minute it doesthis, it means that your code has to run using the services provided by the CLR and

we get a new name called managed code. The CLR provides its services toapplications by providing a standard set of library classes that abstract all the tasks

that you will ever need. These classes are called as the Base Class Libraries. On topof this, other development platforms and applications are built (like ASP.NET,

ADO.NET and so on). Language compilers that need to generate code for the CLRmust adhere to a common set of specifications as laid down by the CommonLanguage Specification (CLS). Above this, you have all the popular .NET languages.

Visual Studio .NET, then is the "glue" that helps your generate .NET applications and

provides an IDE that is excellent for collaborative development.

In the subsequent sections, we will delve into the core layers of the .NET framework.

Note that application development layers (like ADO.NET, ASP.NET etc) anddevelopment tools (VS.NET) are not dealt with.

Common Language Runtime

The CLR is the platform on which applications are hosted and executed. The CLR alsoprovides a set of services that applications can use to access various resources (like

arrays, collections, operating system folders etc). Since this runtime "manages" theexecution of your code, code that works on the CLR is called as managed code. Any

other code, you guessed it, is called unmanaged code.

Page 16: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 16/39

Compilers and tools expose the CLR's functionality and enable you to write code thatbenefits from this managed execution environment. To enable the runtime to provide

services to managed code, language compilers must also emit metadata thatdescribes the types that we develop in .NET. This metadata is stored along with the

type file and makes it "self-describing". Using this information, the runtimeautomatically handles object layout and manages references to objects, releasing

them when they are no longer being used.

When compilers emit code to run on the CLR, they do not emit machine language

code. Rather, an intermediate language code is used called Microsoft IntermediateLanguage (MSIL). MSIL is like an object-oriented version of assembly language and

is platform independent. It has a rich set of instructions that enable efficientrepresentation of the code. When a code starts to execute, a process knowing as Just

in Time Compilation (JIT) converts the MSIL code into the native processorinstructions of the platform, which is then executed. This is shown in the following

diagram:

Note that this conversion happens only once. Subsequent calls to the code willexecute the native version only. Once the application dies down and is started again,

this process is repeated.

The following are some of the benefits of the CLR:

• Performance improvements.

• The ability to easily use components developed in other languages.

• Extensible types provided by a class library.

• New language features such as inheritance, interfaces, and overloading forobject-oriented programming; support for explicit free threading that allowscreation of multithreaded, scalable applications; support for structured

exception handling and custom attributes.

Common Language Specification

Page 17: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 17/39

Language interoperability is the ability of code to interact with code that is writtenusing a different programming language. Language interoperability can help

maximize code reuse and, therefore, improve the efficiency of the developmentprocess. Because developers use a wide variety of tools and technologies, each of 

which might support different features and types, it has historically been difficult toensure language interoperability. However, language compilers and tools that target

the common language runtime benefit from the runtime's built-in support forlanguage interoperability. To ensure that you can develop managed code that can befully used by developers using any programming language, a set of language

features and rules for using them called the Common Language Specification (CLS)

has been defined. Components that follow these rules and expose only CLS featuresare considered CLS-compliant.

To fully interact with other objects regardless of the language they wereimplemented in, objects must expose to callers only those features that are common

to all the languages they must interoperate with. If your component uses only CLSfeatures in the API that it exposes to other code (including derived classes), the

component is guaranteed to be accessible from any programming language thatsupports the CLS. Components that adhere to the CLS rules and use only the

features included in the CLS are said to be CLS-compliant components.

Common Type System

The common type system defines how types are declared, used, and managed in the

runtime, and is also an important part of the runtime's support for cross-languageintegration. The common type system performs the following functions:

• Establishes a framework that enables cross-language integration, type safety,

and high performance code execution.

• Provides an object-oriented model that supports the complete implementation

of many programming languages.• Defines rules that languages must follow, which helps ensure that objects

written in different languages can interact with each other. For example, if 

you have created a class in VB.NET, you can inherit from it in a C# program.

Framework Class Library

Windows programmers coding in C, tend to rely on the Windows API and functions in

third-party DLLs to get their job done. C++ programmers often use class libraries of their own creation or standard class libraries such as MFC. Visual Basic programmers

use the Visual Basic API, which is an abstraction of the underlying operating system

API.

In the .NET Framework, all these anachronistic API’s are done away with. Rather a

new set of functions branded as the framework class library are introduced whichcontain more than 7000 types.

To make learning and using the FCL more manageable, Microsoft has divided the FCLinto hierarchical namespaces. The FCL has about 100 namespaces in all. Each

namespace holds classes and other types that share a common purpose. For

Page 18: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 18/39

example, much of the window manager portion of the Windows API is encapsulatedin the System.Windows.Forms namespace. In this namespace classes that represent

windows, dialog boxes, menus, and other elements commonly used in GUIapplications are present. A separate namespace called System.Collections holds

classes representing hash tables, resizable arrays, and other data containers. Yetanother namespace, System.IO, contains classes for doing file I/O.

The following diagram shows the FCL classes and their associated namespaces.

Introduction

.NET Remoting is a mechanism for communicating between objects which are not inthe same process. It is a generic system for different applications to communicate

with one another. .NET objects are exposed to remote processes, thus allowing inter

process communication. The applications can be located on the same computer,different computers on the same network, or on computers across separate

networks.

Microsoft .NET Remoting provides a framework that allows objects to interact witheach other across application domains. Remoting was designed in such a way that ithides the most difficult aspects like managing connections, marshaling data, and

reading and writing XML and SOAP. The framework provides a number of services,including object activation and object lifetime support, as well as communication

channels which are responsible for transporting messages to and from remoteapplications.

Remote Objects

Page 19: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 19/39

What are remote objects? Any object outside the application domain of the callerapplication should be considered remote, where the object will be reconstructed.

Local objects that cannot be serialized cannot be passed to a different applicationdomain, and are therefore non remotable.

Any object can be changed into a remote object by deriving it from

MarshalByRefObject, or by making it serializable either by adding the[Serializable] tag or by implementing the ISerializable interface. When a client

activates a remote object, it receives a proxy to the remote object. All operations on

this proxy are appropriately indirected to enable the Remoting infrastructure tointercept and forward the calls appropriately. In cases where the proxy and remote

objects are in different application domains, all method call parameters on the stackare converted into messages and transported to the remote application domain,

where the messages are turned back into a stack frame and the method call isinvoked. The same procedure is used for returning results from the method call.

Types of .NET Remotable Objects

There are three types of objects that can be configured to serve as .NET remoteobjects. You can choose the type of object depending on the requirement of your

application.

Single Call

Single Call objects service one and only one request coming in. Single Call objects

are useful in scenarios where the objects are required to do a finite amount of work.Single Call objects are usually not required to store state information, and they

cannot hold state information between method calls.

Singleton Objects

Singleton objects are those objects that service multiple clients, and hence share

data by storing state information between client invocations. They are useful in casesin which data needs to be shared explicitly between clients, and also in which the

overhead of creating and maintaining objects is substantial.

Client-Activated Objects (CAO)

Client-activated objects (CAO) are server-side objects that are activated upon

request from the client. When the client submits a request for a server object using a

"new" operator, an activation request message is sent to the remote application. The

server then creates an instance of the requested class, and returns an ObjRef back

to the client application that invoked it. A proxy is then created on the client side

using the ObjRef. The client's method calls will be executed on the proxy. Client-

activated objects can store state information between method calls for its specific

client, and not across different client objects. Each invocation of "new" returns a

proxy to an independent instance of the server type.

Page 20: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 20/39

Domains

In .NET, when an application is loaded in memory, a process is created, and withinthis process, an application domain is created. The application is actually loaded in

the application domain. If this application communicates with another application, it

has to use Remoting because the other application will have its own domain, andacross domains, object cannot communicate directly. Different application domainsmay exist in same process, or they may exist in different processes.

Contexts

The .NET runtime further divides the application domain into contexts. A contextguarantees that a common set of constraints and usage semantics govern all access

to the objects within it. All applications have a default context in which objects areconstructed, unless otherwise instructed. A context, like an application domain,

forms a .NET Remoting boundary. Access requests must be marshaled acrosscontexts.

Proxies

When a call is made between objects in the same Application Domain, only a normallocal call is required; however, a call across Application Domains requires a remote

call. In order to facilitate a remote call, a proxy is introduced by the .NET frameworkat the client side. This proxy is an instance of the TransparentProxy class, directly

available to the client to communicate with the remote object. Generally, a proxyobject is an object that acts in place of some other object. The proxy object ensures

that all calls made on the proxy are forwarded to the correct remote object instance.In .NET Remoting, the proxy manages the marshaling process and the other tasks

required to make cross-boundary calls. The .NET Remoting infrastructureautomatically handles the creation and management of proxies.

RealProxy and TransparentProxy

The .NET Remoting Framework uses two proxy objects to accomplish its work of making a remote call from a client object to a remote server object: a RealProxy

object and a TransparentProxy object. The RealProxy object does the work of 

actually sending messages to the remote object and receiving response messagesfrom the remote object. The TransparentProxy interacts with the client, and does

the work of intercepting the remote method call made by the client.

Marshaling

Object Marshalling specifies how a remote object is exposed to the client application.It is the process of packaging an object access request in one application domain and

passing that request to another domain. The .NET Remoting infrastructure managesthe entire marshaling process. There are two methods by which a remote object can

be made available to a local client object: Marshal by value, and Marshal byreference.

Page 21: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 21/39

Marshalling objects by value

Marshaling by value is analogous to having a copy of the server object at the client.Objects that are marshaled by value are created on the remote server, serialized into

a stream, and transmitted to the client where an exact copy is reconstructed. Oncecopied to the caller's application domain (by the marshaling process), all method

calls and property accesses are executed entirely within that domain.

Marshall by value has several implications; first, the entire remote object is

transmitted on the network. Second, some or the entire remote object may have no

relevance outside of its local context. For example, the remote object may have aconnection to a database, or a handle to a window, or a file handle etc. Third, parts

of the remote object may not be serialiazable. In addition, when the client invokes a

method on an MBV object, the local machine does the execution, which means thatthe compiled code (remote class) has to be available to the client. Because the

object exists entirely in the caller's application domain, no state changes to theobject are communicated to the originating application domain, or from the

originator back to the caller.

MBV objects are, however, very efficient if they are small, and provide a repeated

function that does not consume bandwidth. The entire object exists in the caller'sdomain, so there is no need to marshal accesses across domain boundaries. Using

marshal-by-value objects can increase performance and reduce network traffic, whenused for small objects or objects to which you will be making many accesses.

Marshal by value classes must either be marked with the [Serilaizable] attribute

in order to use the default serialization, or must implement the ISerializable

interface.

Marshalling objects by reference

Marshaling by reference is analogous to having a pointer to the object. Marshal by

reference passes a reference to the remote object back to the client. This referenceis an ObjRef class that contains all the information required to generate the proxy

object that does the communication with the actual remote object. On the network,

only parameters and return values are passed. A remote method invocation requiresthe remote object to call its method on the remote host (server).

Marshal by reference classes must inherit from System.MarshalByRefObject.

Marshalling done by the .NET Framework 

Marshalling is done by the .NET Framework itself. We don’t have to write any codefor it.

Channels

The .NET Remoting infrastructure provides a mechanism by which a stream of bytesis sent from one point to the other (client to server etc.). This is achieved via a

Page 22: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 22/39

channel. Strictly speaking, it is a class that implements the IChannel interface.

There are two pre-defined .NET Remoting channels existing in

System.Runtime.Remoting.Channels, the TcpChannel and the HttpChannel. To use

the TcpChannel, the server must instantiate and register the TcpServerChannel

class, and the client, the TcpClientChannel class.

Channel selection is subject to the following rules:

• At least one channel must be registered with the remoting framework before

a remote object can be called. Channels must be registered before objects areregistered.

• Channels are registered per application domain. There can be multiple

application domains in a single process. When a process dies, all channelsthat it registers are automatically destroyed.

• It is illegal to register the same channel that listens on the same port more

than once. Even though channels are registered per application domain,different application domains on the same machine cannot register the same

channel listening on the same port. You can register the same channel

listening on two different ports for an application domain.• Clients can communicate with a remote object using any registered channel.

The remoting framework ensures that the remote object is connected to theright channel when a client attempts to connect to it. The client is responsible

for calling the RegisterChannel on the ChannelService class before

attempting to communicate with a remote object.

Serialization Formatters

.NET Remoting uses serialization to copy marshal-by-value objects, and to sendreference of objects which are marshal-by-reference, between application domains.

The .NET Framework supports two kinds of serialization: binary serialization and XMLserialization.

Formatters are used for encoding and decoding the messages before they aretransported by the channel. There are two native formatters in the .NET runtime,

namely binary (System.Runtime.Serialization.Formatters.Binary) and SOAP

(System.Runtime.Serialization.Formatters.Soap). Applications can use binary

encoding where performance is critical, or XML encoding where interoperability with

other remoting frameworks is essential.

A key point to remember is that .NET Remoting always uses binary serialization, butyou have your choice of output formats. The type of serialization (binary or XML)

determines what object data is output. The formatter determines the format in whichthat data is stored.

The data in binary format has smaller size then in XML format. The smaller sizemakes binary formatting the obvious choice for intranet applications or whenever

network performance is critical. However, not all firewalls look kindly on binaryformatted data, so if you're distributing an application that needs to use Remoting

over the Internet, you might find yourself forced to use SOAP formatting. Anotherbenefit of SOAP formatting is that it's human readable, which gives you the

Page 23: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 23/39

opportunity to examine message traffic for debugging. Fortunately, Remoting worksexactly the same regardless of which formatter you use, so you can use SOAP

formatting during initial development and debugging, and then convert to binaryformat for production release.

.NET Remoting Metadata

.NET Remoting uses metadata to dynamically create proxy objects. The proxyobjects that are created at the client side have the same members as the original

class. But the implementation of the proxy object just forwards all requests throughthe .NET Remoting runtime to the original object. The serialization formatter uses

metadata to convert method calls to payload stream and back.

The client can obtain the metadata information required to access the remote object

in the following ways:

• The .NET assembly of the server object.

The Remoting object can provide a WSDL (Web Services DescriptionLanguage) file that describes the object and its methods.

• .NET clients can use the SOAPSUDS utility to download the XML schema from

the server (generated on the server) to generate source files or an assemblythat contains only metadata, no code.

Object Activation

Object activation refers to the various ways in which a remote object can beinstantiated. Marshal by value objects have a simple activation scheme, they are

created when the client first requests them. Marshal by reference objects have twoactivation schemes:

Server Activated Objects

Server Activated Objects are created only when the client makes the first call to theremote method. In other words, when the client asks for the creation of the remote

object, only the local proxy is created on the client, the actual remote object on theserver is instantiated on the first method call. These proxies can be generated as:

...

// On the Server 

RemotingConfiguration.RegisterWellKnownServiceType(  typeof (RemoteServerObject), "Test",

WellKnownObjectMode.SingleCall);...

// On the Client

IRemoteCom obj = (IRemoteCom)Activator.GetObject(typeof(IRemoteCom),"tcp://localhost:1002/Test");

...

Page 24: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 24/39

We have two registration types, Singleton and SingleCall, which were explained

earlier. The code for both is:

RemotingConfiguration.RegisterWellKnownServiceType( typeof(RemoteServerObject),"Test", WellKnownObjectMode.SingleCall);

...

RemotingConfiguration.RegisterWellKnownServiceType( typeof(RemoteServerObject),"Test", WellKnownObjectMode.Singleton);

For Server Activated Objects, the proxy object (on the client) and the actual object(on the server) are created at different times.

Client Activated Objects

These are created on the server immediately upon the client's request. An instanceof a Client Activated Object is created every time the client instantiates one, either

by the use of new or Activator.CreateInstance(...).

...

// On the Server 

RemotingConfiguration.ApplicationName = "TestCAO";RemotingConfiguration.RegisterActivatedServiceType(typeof(RemoteObjectCAO));...

// On the Client

RemotingConfiguration.RegisterActivatedClientType(typeof(RemoteObjectCAO),  "tcp://localhost:1002/TestCAO");obj = new RemoteObjectCAO();

...

In all these examples, "localhost" can be replaced with an actual remote machine'sIP address.

When to use which kind of activation depends upon different scenarios. Some of 

them are:

• Singleton object reference to the same server object, and any changes made

to that object by one client are visible by all of the object's clients. Think of the Windows Desktop, where a change made by one program is visible by all

client programs. Persistent data is held on the server, and is accessible by allclients.

• Use the SingleCall model to provide a stateless programming model (the

traditional Web services request/response model), or any time you have noneed to maintain a persistent object state on the server.

• Use client activation if the object needs to maintain persistent per-client stateinformation.

Object Lifetime and Leases

Page 25: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 25/39

A Server Activated Object that has been registered as SingelCall has a very simple

and limited lifetime. It lives for a single call only. Thereafter, it is marked for removal

by the Garbage Collector.

The other two types, Singleton and Client Activated Objects, have their lifetimes

managed by a service introduced by the .NET Framework, the Leased Based

Manager. On the server, the application domain's lease manager determines when aserver-side object should be marked for deletion. Each application domain has itsown lease manager object. For objects that have object references that are

transported outside the application, a lease is created. The lease has a lease time;when the lease reaches zero, it expires, and the object is disconnected from the .NET

Remoting Framework. Once all the references to the object within the AppDomain

have been freed, the object will be collected when the next garbage collectionoccurs. A sponsor is another object that plays a role in the life time. When a lease

has expired, one or more of the lease's sponsors are invoked by the Lease Manager,where they are given the opportunity to renew the lease. If none of the sponsors

decides to renew the lease, the lease manager removes the lease and the object is

garbage collected.

The default settings for the lease manager are five minutes for initial time-to-live,

poll every ten seconds, and add an additional two minutes for every remote call by aclient. All these values are configurable, we can override MarshalByRefObject

InitializeLifetimeService() to define our own values in the remotable object.

The InitializeLifetimeService method can be overridden as follows:

public override object InitializeLifetimeService(){

ILease lease = (ILease)base.InitializeLifetimeService();

  if (lease.CurrentState == LeaseState.Initial)

{

  // set times very short for demonstration purposes

lease.InitialLeaseTime = TimeSpan.FromSeconds(25);lease.SponsorshipTimeout = TimeSpan.FromSeconds(25);lease.RenewOnCallTime = TimeSpan.FromSeconds(20);

}  return lease;}

Under this scheme, the remote object's (server-side object) lifetime is independentof the client object's lifetime. The decoupling of the server and the client lifetimes is

a very flexible design. Consider, a remote object that is costly to instantiate can begiven a long lifetime lease, or can be kept alive by a sponsor. In addition, a remote

object that holds scarce or important resources can be given short lifetimes, and bereclaimed by the Garbage Collector quickly. More importantly, this decoupling

guarantees that the remote object will have a finite lifetime, regardless of networkconditions or the existence of any clients.

Renewing Leases (Increasing Life Times)

Page 26: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 26/39

While objects have a default lease period, there are many ways to extend the leaseperiod to keep the object alive, in case the client wants to maintain state in the same

server object.

• The server object can set its lease time to infinity, which instructs Remotingnot to collect it during garbage collection cycles.

• The client can call the RemotingServices.GetLifetimeService method toget the lease of the server object from the lease manager of the AppDomain.From the Lease object, the client can then call the Lease.Renew method to

extend the lease.

• The client can register a sponsor for the specific lease with the lease managerof the AppDomain. When the remote object's lease expires, the lease

manager calls back to the sponsor to request a lease renewal.

• If the ILease::RenewOnCallTime property is set, then each call to the remote

object renews the lease by the amount of time specified by the

RenewOnCallTime property.

Once the object has been marshaled, the lease goes from the initial to the active

state, and any attempt to initialize the lease properties will be ignored (an exceptionis thrown). InitializeLifetimeService is called when the remote object is

activated. After activation, the lease can only be renewed.

The .NET Remoting implementation gives you two ways to renew the lease on a

remote object. The client can call ILease.Renew directly, or the client can contact a

sponsor and ask the sponsor to renew the lease.

The sponsor object listens for queries from the host system's lease manager, andresponds accordingly. Sponsors register with the lease manager by obtaining a

reference to the lease and calling ILease.Register. The lease manager will

periodically query the sponsor to see if it wants to renew the lease. If the sponsor

wants to renew the lease, it returns a renewal TimeSpan value in response to theserver's query.

Sponsors are preferable to client ILease.Renew loops, for several reasons. First, the

server's lease manager keeps track of when the object's lease is about to expire, and

will query the sponsor as needed in order to ensure the opportunity to extend thelease before time runs out. It also is more efficient, both in bandwidth and

processing time. In general, where there are multiple clients for a single remoteobject (as in the case of a singleton), it is more efficient for the lease manager to

query a single object for renewal rather than to have each client continually pingingthe server. This is also true in the case of client activated objects because it reduces

the network traffic to just the minimum required to keep the object alive.

You can have the client itself implement the Isponsor interface, or you can create a

sponsor object that maintains leases for one or more remote objects and clients.Here, I am specifying the code to implement Isponsor by the client itself.

Implement the Isponsor in the remotable client class:

class RemoteClient: System.MarshalByRefObject, Isponsor

Page 27: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 27/39

The Isponsor interface requires that you implement a single method, Renewal. The

return value is the amount of time, expressed as a TimeSpan, to extend the lease.

Our Renewal method will extend the lease for an additional 30 seconds. Here's the

code, which you should add to the remote client:

public TimeSpan Renewal (ILease lease)

{  return TimeSpan.FromSeconds(30);}

Finally, register the RemoteClient object with the server's lease manager. Insert the

code below where the server's object instance is being created:

// Instantiate the object

RemoteableClass MyRemotObject = new RemoteableClass();// register as a sponsor 

ILease lease = (ILease)RemotingServices.GetLifetimeService(MyRemotObject);lease.Register(this);

How to Implement Remoting

In the following discussion, we will discuss how we can implement remoting in ourapplications. The code given in the discussion is just to show what is necessary in the

code. You can get the whole code from the source code files.

Create a Remotable Object

A remotable object is an object that inherits from MarshalByRefObject.

Create a new C# class library project. Add a class called MyRemotableObject, and

put in the following code. Add a reference to System.Runtime.Remoting in the

project, otherwise the TcpChannel will not be found. Compile the class to make sure

you have everything correct.

MyRemotableObject.csnamespace RemotableObjects{  public class MyRemotableObject : MarshalByRefObject

{public MyRemotableObject(){}

  public void SetMessage(string message){

Cache.GetInstance().MessageString = message;}

}}

Create a Server to Expose the Remotable Object

Page 28: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 28/39

We need to create a server object that will act as a listener to accept remote objectrequests. For this example, we will use the TCP/IP channel. We first create an

instance of the channel, and then register it for use by clients at a specific port. Theservice can be registered as WellKnownObjectMode.SingleCall, which results in a

new instance of the object for each client, or as WellKnownObjectMode.Singleton,

which results in one instance of the object used for all clients.

It is not necessary to create the server listener if you are planning to use IIS. Forobvious reasons, IIS only supports the use of the HttpChannel. Create a virtual

directory for your application, and then put code to register your service in theApplication_Start event.

For our example, we'll go ahead and create a server listener, in case you don't have

IIS. Since the service needs to be bound to an available port, for our example, Ichose 8080, which is a port that I know to be unused on my computer. You may

need to choose a different port depending upon what ports you have available. To

see a list of the used ports on your computer, open a command prompt, and issuethe command "netstat --a". It may produce a long listing, so make sure the

command prompt buffer sizes are set to allow scrolling. Compile the class to makesure you have everything correct.

Create a new C# Windows Application project. Add a Windows Form calledfrmRServer, and paste in the following code. Add a reference to

System.Runtime.Remoting in the project, otherwise the TcpChannel will not be

found. In addition, add a reference to the project containing the

MyRemotableObject, otherwise the code will not compile because it won't know how

to find a reference to MyRemotableObject. Here, I am giving a part of the code. You

can get the complete code from the source code files.

Collapse

namespace RemotableObjects{  public class frmRServer : System.Windows.Forms.Form, IObserver

{  private System.Windows.Forms.TextBox textBox1;  private MyRemotableObject remotableObject;  private System.ComponentModel.Container components = null;  public frmRServer()

{InitializeComponent();remotableObject = new MyRemotableObject();

  // using TCP protocol

TcpChannel channel = new TcpChannel(8080);ChannelServices.RegisterChannel(channel);RemotingConfiguration.RegisterWellKnownServiceType(

  typeof(MyRemotableObject),"HelloWorld",WellKnownObjectMode.Singleton);

RemotableObjects.Cache.Attach(this);}

}}

Create a Client to Use the Remotable Object

Page 29: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 29/39

The client will be very simple. It will connect to the server, create an instance of theobject using the server, and then execute the SetString method.

Create a new C# Windows Application project. Add a Windows Form called

frmRCleint, and paste in the following code. Add a reference to the project

containing the SampleObject, otherwise the code will not compile because it won't

know how to find a reference to SampleObject. Compile the class to make sure youhave everything correct. Here, only part of code is given just to show the concept.You can get whole code from the source given:

Collapse

namespace RemotableObjects{  public class frmRCleint : System.Windows.Forms.Form

{  private System.Windows.Forms.TextBox textBox1;

MyRemotableObject remoteObject;  private System.ComponentModel.Container components = null;  public frmRCleint()

{

InitializeComponent();  // using TCP protocol

// running both client and server on same machines

TcpChannel chan = new TcpChannel();ChannelServices.RegisterChannel(chan);

  // Create an instance of the remote object

remoteObject = (MyRemotableObject) Activator.GetObject(  typeof(MyRemotableObject),"tcp://localhost:8080/HelloWorld");

}  private void textBox1_TextChanged(object sender, System.EventArgs e)

{remoteObject.SetMessage(textBox1.Text);

}}

}

Running the Application

To run the application, compile the Remoteable Object Project object. Compile serverapplication and run it. Compile the client application and run it. Two dialogue boxes

will appear: one for the Remoting server, and one for the Remoting client. TheRemoting server will listen for the requests. And the Remoting client is ready to pass

the message to the server. Now, type any string in the client dialogue box, and theclient will send it to the server through Remoting, and the server will display the

string in the dialog box of the server application. This is a simple demonstration of easy and understandable Remoting.

Object Configurations

There are two ways to configure remote objects. One is by code, and the other is byusing a configuration file, both on the server and the client. The advantage of using a

configuration file is we don’t have to compile the code every time we change theconfiguration, so we can change the configuration of the application at any time

Page 30: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 30/39

without disturbing the code or executables. By convention, the configuration filename has the format executablename.config.

Configuration files

A typical configuration file includes the following, among other, information:

• Host application information

• Name of the objects

• URI of the objects

• Channels being registered (multiple channels can be registered at the sametime)

• Lease time information for the server objects

Here is an example the configuration filename:

Server remoting configuration (server.exe.config ):

<configuration><system.runtime.remoting><application name="server"><service><activated type="remote.ServiceClass, remote"/></service><channels><channel ref="http" port="8080"><serverProviders><formatter ref="binary" typeFilterLevel="Full"/></serverProviders><clientProviders><formatter ref="binary"/></clientProviders></channel>

</channels></application></system.runtime.remoting></configuration>

Client remoting configuration (client.exe.config )<configuration><system.runtime.remoting><application name="client"><client url = "http://localhost:8080"><activated type="remote.ServiceClass, remote"/></client><channels><channel ref="http" port="0">

<serverProviders><formatter ref="binary" typeFilterLevel="Full"/></serverProviders><clientProviders><formatter ref="binary"/></clientProviders></channel></channels></application></system.runtime.remoting></configuration>

Page 31: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 31/39

To use these configuration files in our Remoting test application, place those files(server.config and client.config) in the directory that contains the server.exe and

client.exe programs.

Using application configuration files greatly simplifies the code required to set up aremoting application. For example, the single line shown here takes the place of all

the configuration code in the server.cs program's Main method:

RemotingConfiguration.Configure("server.config");

The configuration files shown set the client activation--each client gets its ownobject. If you want to configure for Singleton mode, change the <service> section of 

the server's configuration file so that it reads:

<service><wellknowntype="remote.ServiceClass, remote"objectUri="ServiceURI"mode="Singleton"

/></service>

And change the <client> section of the client's configuration file so that it reads:

<client url = "http://localhost:8080"><wellknowntype="remote.ServiceClass, remote"url="http://localhost:8080/ServiceURI"

/></client>

Configuration through code

 Server TcpServerChannel channel = new TcpServerChannel(rs.mPort);ChannelServices.RegisterChannel(channel);RemotingConfiguration.RegisterWellKnownServiceType(  typeof(RemoteServerObject), "Test",

WellKnownObjectMode.SingleCall);

Client TcpClientChannel chan = new TcpClientChannel();ChannelServices.RegisterChannel(chan);IRemoteCom obj = (IRemoteCom)Activator.GetObject(typeof(IRemoteCom),

"tcp://localhost:1002/Test");

Hosting .NET Remoting Objects

.NET Remoting objects can be hosted in:

• Managed executables

Page 32: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 32/39

NET Remoting objects can be hosted in any regular .NET EXE or a managedservice.

• IIS

Remoting objects can be hosted in the Internet Information Server (IIS). By

default, Remoting objects hosted in IIS receive messages through the HTTPchannel. For hosting Remoting objects under the IIS, a virtual root has to becreated, and a "remoting.config" file has to be copied to it. The executable or

DLL containing the remote object should be placed in the bin directory underthe directory the IIS root points to. It is important to note that the IIS root

name should be the same as the application name specified in theconfiguration files. The Remoting configuration file is automatically loaded

when the first message arrives in the application.

• .NET Component Services

NET Remoting objects can be hosted in the .NET component services

infrastructure to take advantage of the various COM+ services likeTransactions, JIT, and Object pooling.

MyRemotableObject remoteObject;private System.ComponentModel.Container components = null;public frmRCleint(){

InitializeComponent();  // using TCP protocol

// running both client and server on same machines

TcpChannel chan = new TcpChannel();ChannelServices.RegisterChannel(chan);

  // Create an instance of the remote object

remoteObject = (MyRemotableObject) Activator.GetObject(

  typeof(MyRemotableObject),"tcp://localhost:8080/HelloWorld");}private void textBox1_TextChanged(object sender, System.EventArgs e){

remoteObject.SetMessage(textBox1.Text);}

Running the Application

To run the application, compile the Remotable Object Project object. Compile theserver application and run it. Compile the client application and run it. Two dialog

boxes will appear, one for the Remoting server and one for the Remoting client. The

Remoting server will listen for the requests. And the Remoting client is ready to passthe message to the server. Now, type in any string in the client dialog box, and theclient will send it to the server through Remoting, and the server will display the

string in the dialog box of the server application. This is a simple demonstration of 

easy and understandable Remoting.

overview of .NET and COM interoperability

Page 33: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 33/39

Summary

This paper provides the technical overview of .NET and COM interoperability. Itdescribes how .NET components can communicate with existing COM components

without migrating those COM components into .NET components, thus helping the

migration cost and business systems. This paper also provides an overview of marshalling. The intended audience is a development team that wishes to interactwith COM and .NET applications. (This paper assumes that the reader has the

fundamental knowledge of COM and .NET)

Introduction

From the time Microsoft engineers started working on the ideas behind COM in 1998,

COM went through quite an evolution. Once .NET was released everything wasabout the CLR. Those business systems made lot of investments on those COM

developments and they may not be willing to invest more money to build theircomponents into .NET. Also this will make a severe impact in productivity.

Fortunately, switching from COM to .NET involves no such radical loss of productivity.

The concept of providing bridge between .NET and COM components is .NET-COMinteroperability. Microsoft .NET Framework provides system, tools, and strategies

that enable strong integration with past technologies and allow legacy code to be

integrated with new .NET components. It provides a bridge between the .NET andCOM and vice versa.

There are two key concepts that make it much easier to move from COMdevelopment to .NET development, without any loss of code base or productivity.

• Interaction with COM components from .NET

• Interaction with .NET components from COM

Before going further, this paper will describe about the basic communicationfundamentals of COM and .NET components.

Communication between Object and Client

COM is a binary reusable object which exposes its functionality to other components.When a client object asks for instances of server object, the server instantiates those

objects and handout references to the client. So, a COM component can act as abinary contract between caller and callee. This binary contract is defined in a

document known as Type library. The Type library describes to a potential client theservices available from a particular server. Each COM components will expose a set

of interfaces through which the communication between COM components willoccurs.

The following diagram shows the communication between a client and a COM object.

Page 34: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 34/39

Fig.1 Communication between client and a COM object 

In the above figure the IUnknown and IDispatch are the interfaces and

QueryInterface, AddRef, Release, etc., are the methods exposed by those

interfaces.

The communication between the .NET objects occurs through Objects, there are nosuch interfaces for communication. So, in .NET component, there is no type libraries,

instead they deal with assemblies. Assembly is a collection of types and resourcesthat are built to work together and form a logical unit of functionality. All the

information related to the assembly will be held in assembly metadata. Unlike thecommunication between COM components, the communication between .NET

components is Object based.

Calling COM components from .NET Client

Generally COM components will expose interfaces to communicate with other

objects. A .NET client cannot directly communicate with a COM component becausethe interfaces exposed by a COM component may not be read by the .NET

application. So, to communicate with a COM component, the COM component shouldbe wrapped in such a way that the.NET client application can understand the COM

component. This wrapper is known as Runtime Callable Wrapper (RCW).

The .NET SDK provides Runtime Callable Wrapper (RCW) which wraps the COM

components and exposes it into to the .NET client application.

Page 35: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 35/39

Fig.2 calling a COM component from .NET client 

To communicate with a COM component, there should be Runtime Callable Wrapper

(RCW). RCW can be generated by using VS.NET or by the use of TlbImp.exe utility.Both the ways will read the type library and uses

System.Runtime.InteropServices.TypeLibConverter class to generate the RCW.

This class reads the type library and converts those descriptions into a wrapper

(RCW). After generating the RCW, the .NET client should import its namespace. Now

the client application can call the RCW object as native calls.

When a client calls a function, the call is transferred to the RCW. The RCW internally

calls the native COM function coCreateInstance there by creating the COM objectthat it wraps. The RCW converts each call to the COM calling convention. Once theobject has been created successfully, the .NET client application can access the COM

objects as like native object calls.

Calling .NET components from COM Client

When a COM client requests a server, first it searches in the registry entry and then

the communication starts. Calling a .NET component from a COM component is not atrivial exercise. The .NET objects communicate through Objects. But the Object

based communication may not be recognized by the COM clients. So, tocommunicate with the .NET component from the COM component, the .NET

component should be wrapped in such a way that the COM client can identify this.NET component. This wrapper is known as COM Callable Wrapper (CCW). The COM

Callable Wrapper (CCW) will be used to wrap the .NET components and used tointeract with the COM clients.

CCW will be created by the .NET utility RegAsm.exe. This reads metadata of the .NETcomponent and generates the CCW. This tool will make a registry entry for the .NET

components.

Page 36: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 36/39

Fig.3 calling a .NET component from COM client 

Generally COM client instantiates objects through its native methodcoCreateInstance. While interacting with .NET objects, the COM client creates .NET

objects by coCreateInstance through CCW.

Internally, when coCreateInstance is called, the call will redirect to the registry

entry and the registry will redirect the call to the registered server, mscoree.dll . Thismscoree.dll will inspect the requested CLSID and reads the registry to find the .NET

class and the assembly that contains the class and rolls a CCW on that .NET class.

When a client makes a call to the .NET object, first the call will go to CCW. The CCW

converts all the native COM types to their .NET equivalents and also converts the

results back from the .NET to COM.

Programming model comparison of .NET-COM

interoperability

The following table compares the .NET and COM based component programmingmodels.

.NET COM

Object based communication Interface based communicationGarbage Collector to manage memory Reference count will be used to manage

memory

Type Standard objects Binary Standard objects

Objects are created by normal new

operator

Objects are created bycoCreateInstance

Exceptions will be returned HRESULT will be returned

Page 37: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 37/39

Object info resides in assembly files Object info resides in Type library

Before the application starts to communicate, there are some technical constraints

associated with this. When an object is transmitted to a receiver which is in aseparate machine/process (managed/unmanaged) space, the object may need toundergo a transformation according to the native type to make it suitable for use by

the recipient. That is the object will be converted into a recipient readable form. Thisprocess of converting an object between types when sending it across contexts is

known as marshaling. The next section of the paper will gives an overview of marshalling in .NET.

.NET Marshalling

Thus .NET runtime automatically generates code to translate calls between managedcode and unmanaged code. While transferring calls between these two codes, .NET

handles the data type conversion also. This technique of automatically binding withthe server data type to the client data type is known as marshalling. Marshaling

occurs between managed heap and unmanaged heap. For example, Fig.4 shows acall from the .NET client to a COM component. This sample call passes a .NET string

from the client. The RCW converts this .NET data type into the COM compatible datatype. In this case COM compatible data type is BSTR. Thus the RCW converts the

.NET string into COM compatible BSTR. This BSTR will be passed to the object and

the required calls will be made. The results will be returned to back to the RCW. The

RCW converts this COM compatible result to .NET native data type.

Fig.4 Sample diagram for marshalling

Logically the marshalling can be classified into 2 types.

1. Interop marshalling

2. COM marshalling

If a call occurs between managed code and unmanaged code with in the same

apartment, Interop marshaler will play the role. It marshals data between managedcode and unmanaged code.

Page 38: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 38/39

In some scenarios COM component may be running in different apartment threads.In those cases i.e., calling between managed code and unmanaged code in different

apartments or process, both Interop marshaler and COM marshaler are involved.

Interop marshaler

When the server object is created in the same apartment of client, all data

marshaling is handled by Interop marshaling.

Fig.5 Sample diagram for same apartment marshalling

COM marshaler

COM marshaling involved whenever the calls between managed code andunmanaged code are in different apartments. For eg., when a .NET client (with the

default apartment settings) communicates with a COM component (whicheverdeveloped in VB6.0), the communication occurs through proxy and stub because

both the objects will be running in different apartment threads. (The defaultapartment settings of .NET objects are STA and the components which are developed

by VB6.0 are STA). Between these two different apartments COM marshaling willoccurs and with in the apartment Interop marshaling will occurs. Fig.6 shows this

kind of marshaling.

This kind of different apartment communication will impact the performance. The

apartment settings of the managed client can be changed by changing theSTAThreadAttribute / MTAThreadAttribute / Thread.ApartmentState property. Both

the codes can run in a same apartment, by making the managed code’s thread toSTA. (If the COM component is set as MTA, then cross marshaling will occurs.)

Fig.6 Sample diagram for cross apartment marshalling

Page 39: UNIT v(Dotnet)

7/30/2019 UNIT v(Dotnet)

http://slidepdf.com/reader/full/unit-vdotnet 39/39

In the above scenario, the call with in different apartments will occur by COMmarshaling and the call between managed and unmanaged code will occur by Interop

marshaling.

Conclusion

Thus the communication between .NET applications and COM applications occurs

through RCW and CCW.

As you have seen, COM applications can implement .NET types to achieve typecompatibility or a .NET type can implement COM interfaces to achieve binary

compatibility with related coclasses.

Although the managed clients can interact with the unmanaged objects, themanaged client expects that the unmanaged object should act exactly the same as

managed object.

When developing against the unmanaged component through COM interoperability,managed code developers will not be able to use some features of .NET likeparameterized constructors, static methods, inheritance, etc., migrating an existing

component or writing a managed wrapper will make the component easier to use formanaged code developers. In some cases, the developer wants to migrate parts of 

the application to .NET so that application can take advantage of the new featuresthat the .NET Framework offers. For example, ASP .NET provides advanced data

binding, browser-dependent user interface generation, and improved configurationand deployment. The designer should evaluate when the value of bringing these new

features in to the application outweigh the cost of code migration.

Chapter 1. Introducing C# and the .NET Framework 

C# is a programming language from Microsoft designed specifically to target the .NET

Framework. Microsoft's .NET Framework is a runtime environment and class library that

dramatically simplifies the development and deployment of modern, component-basedapplications.

When the .NET Framework and C# language compiler were shipped in final form in

January 2002, both the platform and programming language had already garnered much

industry attention and widespread use among Microsoft-centric early adopters. Why thislevel of success? Certainly, the C# language and the .NET Framework address many of 

the technical challenges facing modern developers as they strive to develop increasingly

complex distributed systems with ever-shrinking schedules and team sizes.