Click here to Skip to main content
15,879,326 members
Articles / Web Development / HTML

C# Com

Rate me:
Please Sign up or sign in to vote.
4.78/5 (36 votes)
22 Oct 2014CPOL5 min read 318.5K   6.1K   137   48
Accessing a C# .NET DLL in VB6 using Com+ or Com Interop

Introduction

This example will help you understand how to implement and use a C# DLL in VB 6.0 code. As C# is an object-oriented language, we can use the object-oriented features to create proper classes in C# DLL. We can use COM Interop or follow the COM Plus Approach to refer to such DLLs in our old VB 6.0 applications. It's like delegating our business logic to this DLL. In this article, I tried to show two different approaches to refer to a C# DLL in VB 6.0. The code is attached herewith; you can directly refer to it to understand the following instructions or try to create your own code from the instructions.

To Create COM Interop

By using COM Interop, we create a DLL that can be private or shared. This DLL can be referred to in a VB 6.0 application. A VB 6.0 application refers to a Type Library of this DLL, i.e., a file with the .tlb extension that is created using the VS tool utility. For a client of a COM object to have access to the object, the client needs a description of it, how to locate it and how to call its methods and properties. For a "real" unmanaged COM class, this description is available in the form of a Type Library. A Type Library is a binary description of the GUIDs, classes, and interfaces (methods, properties, and parameters) that the COM class supports.

.NET assemblies don't include information in Type Library compatible format. So, it is necessary for the programmer to run one of two .NET-supplied utilities to extract the assembly description of a class into a Type Library file. One utility is tlbexp.exe, the .NET Type Library Exporter. This command-line utility takes as input the name of an assembly DLL file to be converted to a Type Library. The programmer can also specify the name of a Type Library file to be created.

C#
tlbexp ComInteropExample.DLL /out:ComInteropExample.tlb 

Once a Type Library has been created, it can be referenced by a COM client to obtain the information necessary for the COM client to bind to the interfaces of the COM class and activate the COM class at runtime. Another command-line utility for creating a Type Library from an assembly is regasm.exe, the .NET Assembly Registration utility. In addition to creating a Type Library, this utility also creates the Windows Registry entries necessary for making the assembly visible as a COM object to clients, as shown below:

C#
regasm ComInteropExample.DLL /tlb: ComInteropExample.tlb

Note that there is also a property in the Project Properties for a .NET class library DLL called "Register for COM Interop." Setting this property to True instructs the IDE to automatically register the assembly for COM Interop each time you build it, so you don't have to perform this step manually.

Instructions for Creating a COM Interop DLL in a Visual Studio 2005 Project

  1. Create a new Class Library project in VS 2005, project name: ComInteropExample
  2. Open AssemblyInfo.cs in VS 2005; this is in the Properties folder of the project. Set Com Visible to "True:"
    C#
    [assembly: ComVisible(true)] 
  3. Go to Poject Properties -> Build. Check the option Register for Com Interop to "Selected."
  4. Go to class file, e.g., ComInteropClass.cs and add:
    C#
    namespace using System.Runtime.InteropServices
    Note that there is no need to add a reference to the InteropServices DLL in Application references.
  5. For interface iInterface:
    C#
    define GUID as [Guid("EC87B398-B775-4e6f-BE2C-997D4594CFAA")] 
    [InterfaceType(ComInterfaceType.InterfaceIsDispatch)]
    Note that to create GUID, go to tools -> create GUID -> set GUID format to registry format, copy GUID and add it into your code using the syntax. Write Interface methods as:
    C#
    [DispId(1)] int PerformAddition(int a, int b); 
    [DispId(2)] int PerformDeletion(int a, int b); 
    
    [Guid("EC87B398-B775-4e6f-BE2C-997D4594CFAA")] 
    [InterfaceType(ComInterfaceType.InterfaceIsDispatch)]
     
    public interface iInterface 
    { 
        [DispId(1)] int PerformAddition(int a, int b); 
        [DispId(2)] int PerformDeletion(int a, int b); 
    }
  6. For class ComInteropClass, add statements:
    C#
    above class [Guid("5674D47E-6B2A-456e-85C4-CB7AA6AIF24A")] 
    
    [ClassInterface(ClassInterfaceType.None)] 
    [ProgId("ComInteropClass")] 
    
    public class ComInteropClass:iInterface
    
    [Guid("0C216A19-E1B7-4b05-86D3-4C516BDDC041")] 
    [ClassInterface(ClassInterfaceType.None)] 
    [ProgId("ComInteropClass")] 
    
    //this name is used in VB code for late binding Dim the
    //Object As Object Set theObject = CreateObject("ComInteropClass")
     
    public class ComInteropClass:iInterface 
    { 
        #region iInterface Members public int PerformAddition(int a, int b) 
        { 
            // throw new Exception(
                "The method or operation is not implemented."); 
            try 
        { 
            return a + b; 
        } 
    
            catch 
            { 
                return 0; 
            } 
        }
        public int PerformDeletion(int a, int b) 
        { 
            //throw new Exception(
                "The method or operation is not implemented."); 
            try 
            { 
                return a - b; 
            } 
            catch 
            { 
                return 0; 
            } 
         } 
         #endregion 
    } 
  7. Register the assembly using the SDK command prompt of VS 2005. Go to the release folder of your project:
    C#
    regasm ComInteropExample.DLL /tlb: ComInteropExample.tlb

Refer to this TLB in VB. The VB code is provided with the ZIP file, so please refer to it. It can be used for late binding. If the strong key is not assigned, the assembly will be private, so copy the assembly into the folder where you want to use it. To make the assembly public, assign the strong key to the assembly using the SN tool of VS 2005.

To Create COM+

C#
[assembly: ApplicationName("ComPlusExample")] 
[assembly:Description("ComPlus Assmebly")] 
[assembly:ApplicationActivation(ActivationOption.Server)] 
[assembly:ApplicationAccessControl(false)]
  1. Create a new C# .NET class library project in Visual Studio 2005.
  2. Open the AssemblyInfo.cs file in VS2005. Set the following option:
    C#
    [assembly: ComVisible(true)] 
  3. Go to the References folder -> right click -> Add references (in .NET tab). Add:
    C#
    reference : System.EnterpriseServices
  4. Open a class file (ComPlusClass.cs) and refer to Enterprise Service as:
    C#
    using System.EnterpriseServices 
  5. Add the following statements below namespaces:
  6. Create an interface, e.g., iInterface:
    C#
    public interface iInterface 
    { 
        int PerformAddition(int a,int b); 
        int PerformSubtraction(int a,int b); 
    }
  7. Create the class implementing interfaces ServicedComponent and iInterface.
  8. To track events in COM+ for this class, add the following statements:
    C#
    [EventTrackingEnabled(true)] 
    [Description("Serviced Component")] 
    [EventTrackingEnabled(true)] 
    [Description("Interface Serviced Component")]
    
        Collapse [EventTrackingEnabled(true)] 
                 [Description("Serviced Component")] 
                 [EventTrackingEnabled(true)] 
                 [Description("Interface Serviced Component")] 
    
    public class ComPlusClass:ServicedComponent,iInterface 
    {
        #region iInterface Members
    
        public int PerformAddition(int a, int b) 
        { 
             // throw new Exception(
                 "The method or operation is not implemented."); 
             try 
             { 
                 return a + b; 
             } 
                 catch 
             { 
                 return 0; 
             } 
        }
    
        public int PerformSubtraction(int a, int b) 
        { 
            //throw new Exception(
                "The method or operation is not implemented."); 
            try 
            { 
                return a - b; 
            } 
                catch 
            { 
                return 0; 
            }
            #endregion 
        }
    }
  9. Build the Application. Assign the strong key to the Application using the VS 2005 command prompt. Go to Start-> Program files-> Visual Studio 2005-> Visual Studio tools -> SDK command prompt.
    C#
    sn -k ComPlusClass.snk 
    Add this strong key to Application properties -> Signing -> Strong key
  10. To register the assembly:
    • Use VS tool to register the assembly as:
      C#
      regasm ComPlusExample.DLL 
    • Create a Type Library using the tool:
      C#
      tlbexp ComPlusExample.DLL 
    • Register it in COM+ as:
      C#
      regsvcs ComPlusExample.DLL 
  11. To view this registered COM+, go to Control Panel -> Administrative Tools -> Compoent Services. In Component Services -> Computers -> My Computer -> Com + Applications, right click on it. You can create MSI for it.

Summary

Refer to the TLB of the assembly from the Release folder to use in VB6 applications. Please let me know if you have any questions. I have tried to make this article a readable one and I will try to improve it with your invaluable suggestions. Thank you.

History

  • 25th May, 2007 - Original version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow to register com add in in local machine with class library project. Pin
Sourabh111128-Nov-16 6:12
Sourabh111128-Nov-16 6:12 
QuestionUsing Visual Studio Setup Prj Pin
Member 1026278229-Oct-14 17:07
Member 1026278229-Oct-14 17:07 
AnswerRe: Using Visual Studio Setup Prj Pin
User-Rock1-Nov-14 2:17
User-Rock1-Nov-14 2:17 
GeneralThird party Dll import Error Pin
NaveenSoftwares18-Oct-10 18:56
NaveenSoftwares18-Oct-10 18:56 
GeneralMy vote of 3 Pin
UncleAlbert0130-Jul-10 4:46
UncleAlbert0130-Jul-10 4:46 
General[Message Deleted] Pin
TravisStr8-Dec-09 5:08
TravisStr8-Dec-09 5:08 
GeneralMessage Closed Pin
8-Dec-09 6:07
User-Rock8-Dec-09 6:07 
General[Message Deleted] Pin
TravisStr8-Dec-09 6:20
TravisStr8-Dec-09 6:20 
Generalautomation error the system cannot find the file specified urent Pin
gnsrinu1@gmail.com25-Jul-09 7:54
gnsrinu1@gmail.com25-Jul-09 7:54 
I used this concept in my application. It is working fine on my development system.
After that i try to run my application on some other machine Where vb 6.0 and .NET 2.0 framework is installed. The application showing the following error "automation error the system cannot find the file specified".

i registered the dll on the testing machine by using regasm.

I placed the dll and tlb files in same path as develpment machine.

dim obj as Operation.addition
set obj = new operation.addition -------------> here it is showing the errir "automation error the system cannot find the file specified"
dim str as string
msgbox(obj.add(10,20))

It is very urgent to me.
Can anbody help me out from ths situation.
GeneralRe: automation error the system cannot find the file specified urent Pin
User-Rock25-Jul-09 20:13
User-Rock25-Jul-09 20:13 
GeneralRe: automation error the system cannot find the file specified urent Pin
gnsrinu1@gmail.com25-Jul-09 20:23
gnsrinu1@gmail.com25-Jul-09 20:23 
GeneralRe: automation error the system cannot find the file specified urent Pin
gnsrinu1@gmail.com26-Jul-09 22:37
gnsrinu1@gmail.com26-Jul-09 22:37 
GeneralRe: automation error the system cannot find the file specified urent Pin
shivaramkr28-Sep-11 20:20
shivaramkr28-Sep-11 20:20 
Generalautomation error the system cannot find the file specified Pin
gnsrinu1@gmail.com25-Jul-09 7:51
gnsrinu1@gmail.com25-Jul-09 7:51 
QuestionRe: I need help with passing arrays as parameters Pin
mla15423-Apr-09 9:18
mla15423-Apr-09 9:18 
AnswerRe: I need help with passing arrays as parameters Pin
Member 432084414-Jul-09 21:42
Member 432084414-Jul-09 21:42 
QuestionStuck ! The System Cannot Find the file specified. Pin
wupaz26-Feb-09 10:14
wupaz26-Feb-09 10:14 
AnswerRe: Stuck ! The System Cannot Find the file specified. Pin
Member 432084414-Jul-09 22:00
Member 432084414-Jul-09 22:00 
QuestionRe: Great article - Could someone help me with the next step? Pin
mla15424-Feb-09 10:30
mla15424-Feb-09 10:30 
AnswerRe: Great article - Could someone help me with the next step? Pin
mla15424-Feb-09 11:08
mla15424-Feb-09 11:08 
AnswerRe: Great article - Could someone help me with the next step? Pin
yangbing100811-Apr-09 15:00
yangbing100811-Apr-09 15:00 
AnswerRe: Great article - Could someone help me with the next step? Pin
mla15413-Apr-09 4:04
mla15413-Apr-09 4:04 
GeneralRe: spelling error in article Pin
mla15423-Feb-09 9:16
mla15423-Feb-09 9:16 
GeneralRe: spelling error in article Pin
User-Rock24-Feb-09 0:42
User-Rock24-Feb-09 0:42 
GeneralExample works for VS 2008 also Pin
GKindel11-Jan-09 11:02
GKindel11-Jan-09 11:02 

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.