Sunday, September 13, 2009

Grant access to your Assembly from COM objects

This is a very common occasion where we need to expose a .NET assembly to COM applications, so that the COM application can communicate with .NET assemblies. Here I am going to create a .NET Assembly and expose it from COM.

Your COM Exposed .NET class :

Let us create the Class which I need to expose to COM.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ComVisibleObject
{
[Guid("EB7F73B0-AF1F-4595-8CE8-849D3745E862")]
public interface IComVisibleObject
{
string GetString();
void SetString(string value);
}

[Guid("DF8B1227-68EC-4F76-8C79-D20574C21B56")]
[ComVisible(true)]
public class ComVisibleObjectEx : IComVisibleObject
{
private string element = string.Empty;

public string GetString()
{
return element;
}

public void SetString(string value)
{
element = value;
}

}
}

Here I have created an Interface called IComVisibleObject which might be used to create the class. Please note, it is not mandatory to create the interface.

To Uniquely Identify each class we placed GuidAttribute to each of them. The class ComVisibleObjectEx is exposed to COM using ComVisibleAttribute set to true.

After your class is created in Class Library, Right click on Project - > Go to Properties and select Register for COM interop.
Again Under the signing Tab Select Sign the Assembly. In the Choose key file combobox select New. Choose Filename, Username and password.. The Strong name key will be created automatically.

Now Build the project. Say the dll produced is ComVisibleObject.dll. Use GacUtil to put it in Global Assembly Cache. Use this :
gacutil -i ComVisibleObject.dll

If its successful it will confirm "Assembly successfully added to the cache”.

To add it from COM applications, you need to register assembly using regasm tool.Use

regasm ComVisibleObject.dll
After registration is successful, it will say "‘Types registered successfully".

Now let us create your COM application. For simplicity I use vbs. You can easily create an original VB application to test this as well

Dim object
set object = CreateObject(”ComVisibleObject.ComVisibleObjectEx”)
MsgBox(”Created the object.”)
defaultText = object.GetString()
MsgBox(”Default text length : ” & Len(defaultText))
object.SetString(”My new string”)
newText = object.GetString()
MsgBox(”New text is ” & newText)

Finally save the file as Example.vbs.
Open Command prompt and type

cscript Example.vbs

You will see the messageboxes show the text.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!