Search Forum
(57415 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

Knowing COM Interoperability - An Illustrative Way
By Dhananjay Katre & Prashant Halari

This article provides examples of using a COM component in Microsoft.NET application and also using a Microsoft.NET component in a normal Visual Basic 6.0 application. Many authors had written about this. However, we would like to be very brief and straight to the point in more practical way.

Exposing COM components to Microsoft .NET framework

First we will look at an example of exposing a COM component in the Microsoft .NET framework. Then we will summarize the process required to expose an existing COM component under .NET environment. We will build a simple COM component called BasicMaths in Visual Basic 6.0. The project name is BasicMaths.vbp and the class name is MathsClass. The following is the code for the component.

Function Add(ByVal Operand1 As Integer, ByVal Operand2 As Integer) As Integer
    Add = Operand1 + Operand2
End Function

Function Subtract(ByVal  Operand1 As Integer, ByVal Operand2 As Integer) As Integer
    Subtract = Operand1 - Operand2
End Function

Function Multiply(ByVal  Operand1 As Integer, ByVal Operand2 As Integer) As Long
    Multiply = Operand1 * Operand2
End Function

Function Divide(ByVal Operand1 As Integer, ByVal Operand2 As Integer) As Double
    Divide = Operand1 / Operand2
End Function
The COM component has 4 methods. Once we compile the project in Visual Basic, the COM component gets registered on the machine. Now we want to use this component in Microsoft .NET application. No error handling logic has been incorporated for sake of simplicity.

Approach 1 (Using the command line)

Before we write a C# console application (client) for consuming the COM component written using Visual Basic, we need to expose the COM component to the Microsoft .NET framework. COM type definitions reside in a type library. We need to generate metadata from the type library. The resulting assembly that is created is called an interop assembly.

Microsoft .NET framework provides a tool for converting classes contained in a COM type library to metadata. The tool is called Type Library Imported (tlbimp.exe). This tool creates an interop assembly and namespace for the type information.

Issue the following command at the prompt to generate an interop assembly for the COM component BasicMaths.dll that we created above.

Type library imported to E:\Articles\Interoperability\BasicMathsNet.dll. Please change the path according to your machine settings.

The output of the above command would be the interop assembly file BasicMathsNet.dll.

We will write a simple C# file as below using notepad and compile it using the command line csc.exe The file name is TestMathsAdd.cs

using System;

public class TestMathsAdd
{
	public static void Main(string[] args)
	{
		BasicMathsNet.MathsClass objMathsClass = new  BasicMathsNet.MathsClass();
		Console.WriteLine("Addition of 2 and 3 is " + objMathsClass.Add(2,3));
	}
}

Now we will compile the file giving a reference to the interop assembly created by the tlbimp utility. Following is the command:

csc TestMathsAdd.cs /r:BasicMathsNet.dll
Microsoft (R) Visual C# .NET Compiler version 7.00.9372.1
for Microsoft (R) .NET Framework version 1.0.3328
Copyright (C) Microsoft Corporation 2001. All rights reserved.
During the process of compilation, we are adding a reference to the interop assembly BasicMathsNet.dll which we have created earlier. .

Approach 2 (Using the Visual Studio .NET)

We will see how to create the same console application using Visual Studio.NET. When the project is created, right click on the references tag in the solution explorer and select the option 'Add reference'. The following shows the screen that pops-up:

Select the COM tab. Select the COM component BasicMaths which we have created previously, as shown below

Click on OK. Visual Studio.NET automatically generates the interop assembly for you. Following is the code in the project.

using System;
using BasicMaths;
namespace TestingCOM
{
	class Class1
	{
		static void Main(string[] args)
		{
			MathsClass objMathsClass = new  MathsClass();
			Console.WriteLine("Addition of 2 and 3 is " + objMathsClass.Add(2,3));
		}
	}
}
Thus it is seen very less effort is needed for converting a COM component into the interop assembly because Visual Studio .NET does that automatically for you.

Exposing Microsoft .NET Framework components to COM clients

We will first create a Microsoft .NET component using Visual Studio .NET. The application type will be a class library. When you want to expose a Microsoft .NET component to the COM world, there are a few things that we need to take care of in the code.

· All managed types, methods, properties, fields, and events that you want to expose to COM must be public.
· Types must have a public default constructor, which is the only constructor that can be invoked through COM.
· The Microsoft .NET assembly that you create must be added into the Global Assembly Cache
· Before an assembly can be added into the Global Assembly Cache, it must be built with a strong key Approach 1 (Using the command line)

Follow the steps given below

1. Build an Assembly Key File as follows using the sn.exe tool provided by the Microsoft .NET framework. Create the file somekey.sn in the C:\ directory.

2. Code the Microsoft .NET component in the usual manner. However, that you need to put the AssemblyKeyFile attribute before the namespace as shown in the code below:

using System;
using System.Reflection;
[assembly: AssemblyKeyFile("C:\somekey.snk")]
namespace displaylibrary
{
	/// 
	/// Summary description for Class1.
	/// 
	public class Class1
	{
		public Class1()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public string ReturnName()
		{
			return "Name";
		}
	}
}
3. Use the regasm.exe utility provided in the Microsoft .NET framework to register assembly into the registry. Generate the Type library by the keying in the following command

This will generate a Type Library file named 'TypeLibrary.tlb'

4. Add this Microsoft .NET assembly into the Global Assembly Cache by using the gacutil.exe utility provided by the Microsoft .NET framework. Type the command below

Gacutil -I TypeLibrary.dll

5. Now create a Visual Basic application and you can add and use the Microsoft .NET component as you used to use the COM components.

Approach 2 (Using Visual Studio .NET)

Using Visual Studio .NET greatly simplifies the process of exposing Microsoft .NET components to the COM world.

Create a Microsoft .NET component in Visual Studio .NET. Here the project library would be of type classlibrary.

Now when you build the project, first right click on the project from the solution explorer and select the property option. You get the following screen

As seen in the figure, select the build option from the configuration properties. In the outputs option in the right side of the screen, check for the option 'Register for COM interop'. If the value is made true, then the Microsoft .NET component would be registered and it will be available as a COM component for normal Visual Basic applications.

Let us consider the Visual Basic application that will consume the above Microsoft .NET component. Following screen shows that the above Microsoft .NET component is now available in the references for the project. It is selected to add to the project and can then be used as a normal COM component.

Following code snippet shows how the component can be used in a VB application.

    Dim objDisplay As Class1
    Set objDisplay = New Class1
    MsgBox objDisplay.returnName()
Conclusion

It is apparent that existing COM components interoperate very well with new Microsoft .NET applications in many cases. The COM interoperability features of the .NET Framework are very powerful and, in nearly all cases, allow you to continue to use your existing code without migrating it to managed code. Interoperability allows you to preserve the investment that you have already made in developing and stabilizing the code, familiarizing developers with it, and learning how to deploy and operate the code safely and effectively. It is expected that the majority of existing code will be utilized through interoperability instead of being migrated. Please watch out for our second part of the same article on inter-operating with various .ocx components.