Click here to Skip to main content
15,879,053 members
Articles / Programming Languages / Visual Basic
Article

Exposing COM interfaces of a .NET class library for Late Binding

Rate me:
Please Sign up or sign in to vote.
4.38/5 (24 votes)
30 Jun 20047 min read 256.1K   70   32
An article on how to expose COM interfaces for .NET components to be used by clients using Late Binding

Introduction

For my last project, I developed a nice library in VB.Net for Credit Card Processing. It used sockets and the message format between our servers and those of Citibank was based on a variant of ISO 8583. Calling this library from ASP.Net pages was working fine. But, my Project Manager wanted it to be called from some old VB 6 and classical ASP applications too. So, this scenario demanded that there should be some sort of COM interface to access that component. Also, our Tech. Lead wanted to use Late Binding (i.e. "CREATEOBJECT (PROG ID)") to instantiate this component / class library.

So, I was asked to build COM interface for this class library. I did some research and found some very useful articles that dealt with the same problem. However, I found them somewhat difficult to follow. However, I managed to complete my development using those articles. Now, I want to to share my own experience in a somewhat easier manner (at least I believe so) to make life easier for other developers. The only prerequisite for this article is that you should have Microsoft Visual Studio .Net and should have some basic knowledge of COM.

Problem

Obviously, I cannot present the actual class here. In stead, I will use a very simple class for demo purposes. This class is written in VB.Net as a Class Library. Now, the requirement is that it is to be accessed from clients (VB 6 , classic ASP or even ASP.Net application using Late Binding) with

VB.NET
CreateObject (PROG ID of the component).
If you follow this example, you can apply the same procedure for very complex classes too.
VB.NET
Public class demo
    Private csError As String ' stores the error message
    Public ReadOnly Property ErrorMsg() As String
        Get
            Return csError
        End Get
    End Property
    Public Function Concat(ByVal str1 As String, ByVal str2 As String) As STRING
        return Concat = str1 + " " + str2
    End function

End class 

This class demo which has a property ErrorMsg and one function Concat, built as a class library project using Visual Studio.Net, has been given a Strong Name using the strong name tool sn.exe. It is important to note that you can avoid strong naming your assembly. however, I would advise you against it. If you do not want to use the strong name, then keep your component and the calling client in the same directory.

Solution

As I found out, there are two ways to solve this problem. One is very easy while the other one is a bit hard. Unfortunately, I came to know the hard one first and discovered the second one after I had implemented my component using the hard method.

Solution 1 : To create a COM object using the COM class template of Visual Studio . Net

The easiest way to create COM objects is by using the COM class template of Visual Studio .Net. The COM class template creates a new class, then configures your project to generate the class as a COM object and registers it with the operating system automatically. All the background work will be done by Visual Studio (how nice !!).
Here are the steps involved using Visual Studio .Net:

  1. Open a New Windows Application project by clicking New on the File menu, and then clicking Project. The New Project dialog box will appear.
  2. With Visual Basic Projects highlighted in the Project Types list, select Class Library from the Templates list, and then click OK. The new project will be displayed.
  3. Select Add New Item from the Project menu. The Add New Item dialog box will be displayed.
  4. Select COM Class from the Templates list, and then click Open. Visual Basic .NET will add a new class and configure the new project for COM interop.
  5. Add code, such as properties, methods, and events to the COM class. In our case we will just copy the code for property ErrorMsg and method Concat into the class and rename the class to class demo.
  6. Select Build Solution from the Build menu. Visual Basic .NET will build the assembly and register the new COM object with the operating system automatically.

What 's next ? nothing folks. Your COM component is ready to be accessed from any VB or classic ASP page etc. using Createobject(...).

Solution 2 : Do it yourself approach

This is a little bit difficult as compared to method number 1. But, if you are a programmer who likes to go little bit deeper into details, you will be inclined to go this way. Some basic knowledge about COM is required.
Once you complete all the steps for this method, your class will look quite similar to this one.

VB.NET
Imports System.Runtime.InteropServices

<Guid("1F249C84-A090-4a5b-B592-FD64C07DAB75"), _
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface _demo
    <DispId(1)> Function Concat(Byval s1 as string, ByVal S2 As String) as string 
    <DispId(2)> readonly Property ErrorMsg() as string 

End Interface

<Guid("E42FBD03-96DF-43a7-A491-23E735B32C5C"), _
ClassInterface(ClassInterfaceType.None), _
ProgId("comDemo.demo")> Public Class demo
    Implements _demo
Private csError As String ' stores the error message
    Public ReadOnly Property ErrorMsg() As String
implements _demo.errormsg
        Get
            Return csError
        End Get
    End Property
Public Function Concat(ByVal str1 As String, ByVal str2 As String) As STRING
implements _demo.Concat
 return Concat = str1 + " " + str2
end function
end class 

STEPS INVOLVED:

1. Add the interop namespace to your class

VB.NET
Imports System.Runtime.InteropServices
2. Then develop an interface with the same name as of your original class, just add _ before it to make it different. For our example, it will be like
VB.NET
Public Interface _demo
    

End Interface 
3. Then, create a GUID for this interface. To create GUID for your COM object, click Create GUID on the Tools menu, or launch guidgen.exe to start the guidgen utility. Search for the file guidgen.exe on your machine. It is located under c:\program files\ Microsoft visual studio .net\common7\ tools directory on my computer. Run it. Then, select Registry Format from the list of formats provided by the guidgen application. Click the New GUID button to generate the GUID and click the Copy button to copy the GUID to the clipboard. Paste this GUID into the Visual Studio .Net code editor. Remove the leading and trailing braces from the GUID provided. For example, if the GUID provided by guidgen is {2C8B0AEE-02C9-486e-B809-C780A11530FE} then the GUID should appear as: 2C8B0AEE-02C9-486e-B809-C780A11530FE.
Once a guid is created, paste it into the class as
VB.NET
Guid("1F249C84-A090-4a5b-B592-FD64C07DAB75") 
Then use the interfacetype attribute to make it a Dispatch interface required by automation as
VB.NET
InterfaceType(ComInterfaceType.InterfaceIsIDispatch) 
Unless you specify otherwise, the export process converts all managed interfaces to Dual interfaces in a type library. Dual interfaces enable COM clients to choose between Early and Late Binding.You can apply the InterfaceTypeAttribute attribute to an interface to selectively indicate that the interface should be exported as a Dual interface, an IUnknown-derived interface, or a dispatch-only interface (dispinterface). All exported interfaces extend directly from either IUnknown or IDispatch, regardless of their inheritance hierarchy in managed code.

4. In the interface, expose the methods, properties etc that you want the clients to see and access. In our case, we will expose both our property and our method and will assign arbitrarily values of 1 and 2 as dispids. Our interface will look like this at this point of time

VB.NET
 <Guid("1F249C84-A090-4a5b-B592-FD64C07DAB75"), _
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface _demo
    <DispId(1)> Function Concat(Byval s1 as string, ByVal S2 As String) as string 
    <DispId(2)> readonly Property ErrorMsg() as string 

End Interface
5. In a similar fashion, you need to create a GUID for the actual class too.
VB.NET
Guid("E42FBD03-96DF-43a7-A491-23E735B32C5C") 
Next, use the interop attributes as follows
VB.NET
ClassInterface(ClassInterfaceType.None), _
ProgId("comDemo.demo")> Public Class demo
    Implements _demo 
You must have noticed that you have to specify the ProgID for the class here. This is the same ProgID that we will be using to call our component as follows;
set myobject = createobject ("comDemo.demo") ' vb6 or vbscript

implements _demo suggests that the class is implementing the interface. Note that we are using classinterfacetype.none for the classinterface attribute. Microsoft states that
"To reduce the risk of breaking COM clients by inadvertently reordering the interface layout, isolate all changes to the class from the interface layout by explicitly defining interfaces.Use the ClassInterfaceAttribute to disengage the automatic generation of the class interface and implement an explicit interface for the class, as the following code fragment shows:

VB.NET
<ClassInterface(ClassInterfaceType.None)>Public Class LoanApp
   Implements IExplicit
   Sub M() Implements IExplicit.M
…
End Class
The ClassInterfaceType.None value prevents the class interface from being generated when the class metadata is exported to a type library. In the preceding example, COM clients can access the LoanApp class only through the IExplicit interface."

6. The next step is to modify the properties and methods signatures which we want to expose. So

VB.NET
Public ReadOnly Property ErrorMsg() As String 
becomes
VB.NET
Public ReadOnly Property ErrorMsg() As String implements _demo.errormsg 
and
VB.NET
Public Function Concat(ByVal str1 As String, ByVal str2 As String) As String
becomes
VB.NET
Public Function Concat (ByVal str1 As String, ByVal str2 As String) 
  As String implements _demo.Concat
7. Once you make these changes to your class , you are all set. Just one more change is required to make it complete. Right click the project to bring the project properties, there under the Build properties check the interop check box. When building the project, this will ensure that a type library is created for the COM Interface and is registered too. If you do not want to use this option, you can use Regasm utility to do the same. For Regasm, the syntax would be
regasm demo.dll /tlb: demo.tlb
It will create the type library and will register it to for you.

That was it

You can build the project and can access it
  1. Through Late binding : using createobject("comDemo.demo") or
  2. Through Early binding: by setting reference to this component in you project

Strong Name Requirement

It is recommended that your assembly should have a strong name. For that, you can use the strong name tool sn.exe. If you would not create the strong name, then you will have to keep the component and the calling program in the same directory.

References

  1. MSDN library.
  2. Some very good articles on www.codeproject.com

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
Musa is an MCAD and MCSD - Early Achiever in .Net. He is PMP certified and holds a Bachelors Degree in Electrical Engineering and a Post Graduate Diploma in Software Development. Currently he is working as Senior Developer in New York.

Comments and Discussions

 
QuestionDeploy Error Pin
cocacolacool27-Sep-12 23:46
cocacolacool27-Sep-12 23:46 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey28-Feb-12 18:23
professionalManoj Kumar Choubey28-Feb-12 18:23 
QuestionBuild interface like idisposable interface work Pin
Paras Arora20-Jul-11 21:51
Paras Arora20-Jul-11 21:51 
Generaldll public function not visible using dumpbin (C++) Pin
MichelJoseph26-Mar-10 1:39
MichelJoseph26-Mar-10 1:39 
GeneralThanks Pin
Jipat9-Feb-10 22:04
Jipat9-Feb-10 22:04 
GeneralThank you Pin
silios12-Oct-09 22:36
silios12-Oct-09 22:36 
QuestionCall a function in vb.net from visual basic 5 Pin
rains197917-Mar-09 23:35
rains197917-Mar-09 23:35 
GeneralCan't access the property in VBA Pin
StehtimSchilf31-Oct-08 6:29
StehtimSchilf31-Oct-08 6:29 
GeneralISO 8583 Pin
ubipoc2-Jun-08 20:38
ubipoc2-Jun-08 20:38 
GeneralEvent does not work Pin
Nasenbaaer7-Nov-07 22:40
Nasenbaaer7-Nov-07 22:40 
Hi
Thanky for your tutorial. I'm doing it this way in my project too. Using a .Net Dll and register it with RegAsm.exe for my VB6 project. But I can not get any events. Can anyone give me any help please.

Perhaps:
'Demo-VB.NET Dll<br />
Public Event Test()<br />
<br />
Private Sub Timer1_Tick() handles Timer1.Tick<br />
  RaisEvent Test()<br />
End Sub


'VB6 Application<br />
Dim Obj as Object<br />
private sub Form_Load()<br />
Obj = CreateObject("Demo.clsDemo")<br />
End Sub<br />
<br />
Private Sub Obj_Test()

GeneralRe: Event does not work Pin
azazulhaq31-Mar-16 23:02
azazulhaq31-Mar-16 23:02 
GeneralGetting Error 429 Pin
richbward31-May-07 9:08
richbward31-May-07 9:08 
GeneralAdding COM interface to an existing VB.NET solution Pin
JohnZonie15-Nov-06 6:20
JohnZonie15-Nov-06 6:20 
QuestionI need you help to complete my ISO 8583 Web application Pin
Jiri Adil11-Oct-06 3:56
Jiri Adil11-Oct-06 3:56 
GeneralASP/COM Debugging Pin
NickGerrie3-Jun-06 9:33
NickGerrie3-Jun-06 9:33 
GeneralUsing in VBA with Net 2.0 Pin
Jez Lukins10-May-06 2:27
Jez Lukins10-May-06 2:27 
GeneralThis doesn't work for .Net 2.0 Pin
jayxxx25-Apr-06 7:53
jayxxx25-Apr-06 7:53 
GeneralRe: This doesn't work for .Net 2.0 Pin
Pugwash200421-Aug-06 14:54
Pugwash200421-Aug-06 14:54 
GeneralI can't call function from VC++ Pin
nemo1413-Apr-06 12:31
nemo1413-Apr-06 12:31 
GeneralAutomation error -2147024894 Pin
Datahyllan6-Oct-05 2:53
Datahyllan6-Oct-05 2:53 
GeneralRe: Automation error -2147024894 Pin
Jia-De Lin6-Jun-06 16:19
Jia-De Lin6-Jun-06 16:19 
GeneralHere are both corrected VB code and C# code Pin
wazabbe14-Aug-05 21:08
wazabbe14-Aug-05 21:08 
GeneralCalling RegAsm.exe Pin
Heath Stewart20-Jan-05 12:57
protectorHeath Stewart20-Jan-05 12:57 
GeneralRe: Calling RegAsm.exe Pin
Anonymous18-Aug-05 13:02
Anonymous18-Aug-05 13:02 
AnswerRe: Calling RegAsm.exe Pin
Heath Stewart18-Aug-05 15:56
protectorHeath Stewart18-Aug-05 15:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.