Exposing COM Interfaces of a .NET Class Library for Late Binding

xiaoxiao2021-03-06  110

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 (IE "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 can not 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

CreateObject (PROG ID OF THE Component) .IF You Follow this Example, You CAN Apply The Same Procedure for Very Complex Classes TOO.

Public Class Demo

Private cSerror As String 'Stores The Error Message

Public Readonly Property ErrorMSG () AS String

Get

Return CSerror

End Getend Property

Public Function Concat (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, The 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 CLASSIO. 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:

Open a New Windows Application project by clicking New on the File menu, and then clicking Project. The New Project dialog box will appear. 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. Select Add New Item from the Project menu. The Add New Item dialog box will be displayed. 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. 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. 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 ASPPage 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.

Imports system.Runtime.InteropServices

InterfacePe (CominterFacetype.InterfaceiSidispatch)>

Public Interface_Demo

Function Concat (Byval S1 As String, Byval S2 As String) AS String

Readonly Property ErrorMSG () AS STRING

End interface

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 str2 as string) AS STRING

Implements_demo.concat

Return Concat = STR1 "" STR2

END FUNCTION

END CLASS

Steps Involved:

Add the interop namespace to your class

Imports system.Runtime.InteropServices22.interopservices2. The development. For Your Original Class, Just Add_Before It To Make It Different. For Our Example, IT Will Be Like

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 To

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

GUID ("1F249C84-A090-4A5B-B592-FD64C07DAB75") THEN USE TheInterfaceType Attribute To Make IT A

Dispatch interface required by Automation As

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

InterfacePeattribute Attribute To An Interface To Selectively Indicate That The Interface Should Be Exported AS AS AST INTER

Dual Interface, AN

Iunknown-deerived 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

InterfacePe (CominterFacetype.InterfaceiSidispatch)>

Public Interface_Demo

Function Concat (Byval S1 As String, Byval S2 As String) AS String

Readonly Property ErrorMSG () AS STRING

End Interface5. In a Similar Fashion, you need to create a

GUID for the actual class too.

Guid ("E42FBD03-96DF-43A7-A491-23E735B32C5C") Next, Use the Interop Attributes as Follows

ClassInterface (ClassInterFacetype.none), _

PROGID ("Comdemo.demo"> Public Class Demo

Implements_demo you must has noticed That you have to specify the

PROGID for the class here. This is the hand

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:

Public Class LoanApp

Implements IexPlicit

SUB M () imports ipplicit.m

...

End ClassThe 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 property and methods signals which we want to express. So

Public Readonly Property ErrorMSG () AS String Becomes

Public Readonly Property ErrorMsg () AS String Implements_Demo.ErrorMsg and

Public Function Concat (Byval str2 as string) AS StringBecomes

Public Function Concat (Byval str2 as string)

As String implements _demo.Concat7. 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 useRegasm utility to do the same. For Regasm, the SYNTAX WOULD BE

REGASM DEMO.DLL / TLB: DEMO.TLBIT WILL CREATE The TYPE LIBRARY AND WILL REGISTER IT to for you.

That Was ITYOU CAN Build The Project and Can Access IT

THROUGH LATE BINDING: Using CreateObject ("comdemo.demo") or through early binding: by setting reason to this component in you project

Strong name request

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.

转载请注明原文地址:https://www.9cbs.com/read-124614.html

New Post(0)