Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft C# Professional Projects - Premier Press.pdf
Скачиваний:
177
Добавлен:
24.05.2014
Размер:
14.65 Mб
Скачать

ADVANCED C# CONCEPTS

Chapter 34

 

809

 

 

 

 

 

 

.NET Interoperability

.NET provides interoperability features that allow you to work with existing unmanaged code (that is, code running outside the CLR) in COM components as well as Win32 DLLs. .NET CLR enables interoperability by hiding the complexity associated with calls between managed and unmanaged code. The run time automatically generates code to translate calls between the two environments.

When you call a COM object from .NET, the run time generates an RCW (runtime callable wrapper). The RCW acts as a surrogate for the unmanaged object (refer to Figure 34-2).The RCW handles all interaction between the .NET client and the COM component. It takes care of creating and binding the COM object, translating and marshaling data between environments, and managing the lifetime of the wrapped COM object.

FIGURE 34-2 COM DLL-to-RCW conversion

Even when you call a .NET component from COM, the run time generates a wrapper object called CCW (COM callable wrapper). The run time reads the type information for the component from its assembly metadata and generates a CCW. The CCW, like the RCW, acts as a proxy between the unmanaged COM object and the managed .NET component. The CCW takes care of handling all interaction between the COM client and the managed object.

COM+ Services

.NET components can participate in COM+ applications and share context, transactions, synchronization boundaries, and so forth with COM+ components.

.NET components that participate in COM+ applications are called serviced components. A serviced component is the mechanism that enables context sharing between COM+ and .NET Framework classes.

Serviced components must be registered in the COM+ catalog, typically by using the regsvcs tool provided with the .NET Framework SDK. You can specify the

810

Part IX

BEYOND THE LABS

 

 

 

exact service requirements for your .NET component by annotating your managed code with service related attributes.

Calling Unmanaged APIs from .NET

.NET also supports calling unmanaged code in Win32 DLLs. This interoperability, referred to as platform invocation or simply P/Invoke, allows managed code to call into C-language-type API functions. It also handles the marshaling of data types between managed and unmanaged types, finds and invokes the function in the DLL, and facilitates transition from managed to unmanaged code.

COM Interoperability

COM interoperability provides access to existing COM components without modifying the original component. When you need to incorporate a COM code in to your managed application, import the relevant COM types using the COM Interop (TlbImp.exe) utility.

The TlbImp (type library impor ter) utility is a command-line tool that is shipped along with .NET Framework SDK. It converts a COM type library into .NET Framework metadata. The type library importer also does the following:

COM coclasses are converted to C# classes with a zero parameter constructor.

COM structs are converted into C# structs with public fields.

COM interop also allows you to access managed objects. For this purpose, COM interop provides a utility (RegAsm.exe) that exports the managed types into a type library and registers the component as a COM component. At run time, the CLR marshals data between COM objects and managed objects as needed.

C# Client Interop

I will now discuss the steps to be followed to use C# code to interoperate with COM objects.

C# provides support for the following:

Creating COM objects

Determining whether a COM interface is implemented by an object

ADVANCED C# CONCEPTS

Chapter 34

811

 

 

 

 

Calling methods on COM interfaces

Implementing objects and interfaces that can be called by COM clients

Creating a COM Class Wrapper

In order to access COM objects and interfaces from C# code, you need to include a .NET Framework definition for the COM interfaces in your C# code. You can easily accomplish this by using the type library importer utility.

Declaring a COM Coclass

COM coclasses are represented as classes in C#. These classes must have the ComImport attribute associated with them. A coclass is declared as shown in the code snippet that follows:

// declare CalcManager as a COM coclass

[ComImport, Guid(“E436EBB3-524F-11CE-9F53-0020AF0BA770”)] class CalcManager

{

//code to do something

}

The C# compiler will add a constructor without any parameters that you can call to create an instance of the COM coclass.

Creating a COM Object

Creating an instance of the COM coclass using the new operator is equivalent to using CoCreateInstance. The above class can be instantiated as given here:

class MainClass

{

public static void Main()

{

CalcManager calc = new CalcManager ();

}

}

812

Part IX

BEYOND THE LABS

 

 

 

Declaring a COM Interface

COM interfaces are represented in C# as interfaces with ComImport and Guid attributes. They cannot include any interfaces in their base interface list, and they must declare the interface member functions in the order that the methods appear in the COM interface.

Developing COM+ Applications

When developing COM+ applications, the principal tasks include designing COM components to encapsulate application logic, creating the COM+ application, and administering the application through deployment and maintenance.

Designing COM Components

The following steps describe a general procedure for good component design:

1.Define the COM classes and implementation classes.

2.Group the classes into components.

3.Integrate the components into a COM+ application.

Creating the COM+ Application

After designing the COM components, the developer integrates the components into a COM+ application and configures the application. The following steps describe the process:

1.Integrate the components into a COM+ application. You can integrate the components into an existing COM+ application or create a new application for the components. Specify the correct set of attributes for each of the classes. These attributes express the component’s dependencies on any services its implementation might rely on, such as transactions, queued components, security, object pooling, and JIT activation.

2.Set up the security framework, that is, define roles and association of roles to classes, interfaces, and methods.

3.Configure environment-specific attributes on classes and applications.

4.Export the application for redistribution and deployment.

ADVANCED C# CONCEPTS

Chapter 34

813

 

 

 

 

Administering COM+ Applications

Typically, a developer delivers a partially configured COM+ application to the system administrator. The administrator then customizes the application for one or more specific environments. For example, the system administrator adds user accounts in roles and server names in an application. The administrator’s tasks include the following:

1.Install the configured COM+ application on an administrative machine.

2.Provide the environment-specific attributes, such as role members and object pool size.

3.Export the fully configured COM+ application.

4.Create an application proxy.

After an application is fully configured for a specific environment, the administrator can then deploy it on test or production machines. This involves installing the fully configured COM+ application on one or more machines.

Accessing a COM+ Component from C# Code

If you want to access an existing COM+ application from C# code, you do not need to modify the existing COM+ application, despite the fact that the execution model of the component is very different.

Following is an example of accessing a DLL from C# code. You can access the DLL in two ways, early binding and late binding. I will first take you through the early binding example.

Accessing a COM Component Using Early Binding

In order to use an existing COM component, you need to create a RCW using the type library importer (TlbImp.exe) utility, as follows.

Assume you have a COM component with a method Add that takes two parameters and returns their sum.

‘CompAdd.Dll

(class1)

Public Function Add(A As Long, B As Long) As Long

Add = A + B

End Function

814

Part IX

BEYOND THE LABS

 

 

 

Run the TlbImp.exe utility to create a RCW as shown in Figure 34-3.

FIGURE 34-3 Creating an RCW with TlbImp utility

The preceding command generates a wrapper DLL, called CompAddRcw.dll. You can view this DLL using a utility called IlDasm.exe.

Now you need to write code to call the wrapper DLL (CompAddRcw.dll) to access the actual DLL (CompAdd.dll). The code for calling the DLL is given as follows.

//code to access CompAdd.dll using CompAddRcw;

using System; namespace AddEarlyBind

{

class EarlyBinding

{

public static void Main()

{

CompAddRcw.Class1 objAdd = new CompAddRcw.Class1(); long lRes;

int ix=100; int iy=200;

lRes= objAdd.Add( ref ix, ref iy); Console.WriteLine(lRes);

}

}

}

Compile the program with /r: switch and execute it to call the COM component.

ADVANCED C# CONCEPTS

Chapter 34

815

 

 

 

 

Accessing a COM Component Using Late Binding

To implement late binding, you need to use System.Reflection namespace, which enables access to the types contained in any assembly. This can be accomplished as follows:

1. Get the interface IDispatch using

Type.GetTypeFromProgID(“Project1.Class1”).

2. Create instance using the type ID Activator.CreateInstance(objAddType).

3.Create an array of arguments.

4.Invoke the method using the function objAddType.InvokeMember.

The code for implementing the same is as follows.

using System.Reflection; using System;

namespace AddLateBind

{

class LateBinding

{

public static void Main()

{

//Get IDispatch Interface

Type objAddType = Type.GetTypeFromProgID(“Project1.Class1”); //Create Instance

object objAdd = Activator.CreateInstance(objAddType); //Make Array of Arguments

object[] myArguments = { 100, 200 }; object obj;

//Invoke Add Method

obj = objAddType.InvokeMember(“Add”, BindingFlags.InvokeMethod, null, objAdd, myArguments);

Console.WriteLine(obj);

}

}

}

816

Part IX

BEYOND THE LABS

 

 

 

The method Type.GetTypeFromProgID is used to load the type information of the COM object. The call to Activator.CreateInstance returns an instance of the COM object. Finally, InvokeMember function is used to call the method of COM object.

A Complete Example

The following example describes the process of creating a DLL in C# and accessing it from C# code. I shall first take you through the steps to create a DLL.

Creating the DLL

1.On the File menu, point to the New option.

2.In the displayed list, click the Project option. The New Project dialog box is displayed.

3.In the Project Types: pane of the New Project dialog box, select the Visual C# option.

4.In the Templates: pane, select the Class Library option.

5.Type the name of the application as Math in the Name: text box and the desired location in the Location: text box.

6.Click the OK button.

7.Add a method with the following definition.

public long Add(long Val1, long Val2)

{

return Val1 + Val2;

}

8. Add a property, Extra, as shown in the following code.

public bool Extra

{

get

{

return bTest;

}

set

{

bTest=Extra;

ADVANCED C# CONCEPTS

Chapter 34

 

817

 

 

 

 

 

 

}

}

9.Change the name of Class1 to MathComp. Also change the name of the constructor.

10.Build the component.

Building the Client

1.On the File menu, point to the New option.

2.In the displayed list, click the Project option. The New Project dialog box is displayed.

3.In the Project Types: pane of the New Project dialog box, select the Visual C# option.

4.In the Templates: pane, select the Console Application option.

5.Type the name of the application as MathClient in the Name: text box and the desired location in the Location: text box.

6.Click the OK button.

7.On the Project menu, click the Add Reference option.

8.Browse and select the Math.dll you created and add it to the current project (refer to Figure 34-4).

FIGURE 34-4 The Add Reference dialog box