Using COM Components

Using COM Components

In this section of the chapter, you learn to encapsulate COM components for use with .NET applications. Both command-line and GUI tools are available for working with COM components. Before working with those tools, though, you should know a bit about wrapper classes.

Understanding Runtime Callable Wrappers

Code that operates within the CLR is called managed code . Managed code benefits from various services the CLR offers, such as garbage collection, memory management, and support for versioning and security.

COM components are unmanaged code because COM was designed before the CLR existed, and COM components don't use any of the services of the CLR.

How can you take a component developed before the advent of .NET and make it look like a .NET component to other .NET components? The answer is to use a proxy . In general terms, a proxy accepts commands and messages from one component, modifies them, and passes them to another component. The particular type of proxy that enables you to use COM components in a .NET application is called a runtime callable wrapper ( RCW ) . That is, it's a proxy that can be called by the CLR. Figure 11.1 shows how the pieces fit together.

Figure 11.1. RCWs enable you to use COM components in the .NET Framework.

graphics/11fig01.gif

To see how COM interoperability works, you need a COM library. Follow these steps to build a simple one:

  1. Launch Visual Basic 6.0 and create a new ActiveX DLL project.

  2. Select the Project1 node in the Project Explorer window and rename it MyCustomer .

  3. Select the Class1 node in the Project Explorer window and rename it Balances .

  4. Add this code to the Balances class:

     Option Explicit Private mintCustomerCount As Integer Private macurBalances(1 To 10) As Currency ' Create a read-only CustomerCount property Public Property Get CustomerCount() As Integer     CustomerCount = mintCustomerCount End Property ' Create a GetBalance method Public Function GetBalance(CustomerNumber As Integer)_     As Currency     GetBalance = macurBalances(CustomerNumber) End Function ' Initialize the data Private Sub Class_Initialize()     Dim intI As Integer     mintCustomerCount = 10     For intI = 1 To 10       macurBalances(intI) = Int(Rnd(1) * 100000) / 100     Next intI End Sub 
  5. Save the Visual Basic project. Then select File, Make MyCustomer.dll to create the COM component. This step also registers the COM component on your computer.

Using the Type Library Importer Tool ( tlbimp.exe )

The task of using COM components from .NET is made substantially easier by the fact that COM components, like .NET components, have metadata that describe their interfaces. For .NET components, this metadata is embedded in the assembly manifest, whereas for COM components, the metadata is stored in a type library. A type library can be either a separate file or (as with Visual Basic 6 class libraries) embedded within another file.

The .NET Framework includes a tool, called the Type Library Importer ( tlbimp.exe ), that can create an RCW from COM metadata contained in a type library. Take the following steps to see how to work with the Type Library Importer:

  1. Launch a .NET command prompt by selecting Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt.

  2. Inside the command prompt window, navigate to the folder that contains the MyCustomers.dll COM library and enter this command to run the Type Library Importer: tlbimp MyCustomer.dll /out:NETMyCustomer.dll .

  3. Open Visual Studio .NET and create a new blank solution named 315C11 at c:\inetpub\ wwwroot \ExamCram. (You might need to change the directory based on your configuration.)

  4. Add a new Visual C# ASP.NET Web Application project at the following location: http://localhost/ExamCram/315C11/Example11_1 .

  5. Place three Label controls ( name one of then lblBalance), one TextBox control ( txtCustomerNumber ), and a Button control ( btnGetBalance ) on the form.

  6. Right-click the References node in the Solution Explorer and select Add Reference.

  7. Click the Browse button in the Add Reference dialog box. Select the NETMyCustomer.dll file you created in step 2. Click OK to add the reference to the project.

  8. Switch to the form's Code view and add the following using directive:

     using NETMyCustomer; 
  9. Double-click the Button control and enter the following code in the Click and Page_Load() event handlers:

     Balances b; private void Page_Load(object sender, System.EventArgs e) {     b = new Balances();    txtCustomerNumber.Text = b.CustomerCount.ToString(); } private void btnGetBalance_Click(object sender, System.EventArgs e) {     Int16 custNumber = Int16.Parse(txtCustomerNumber.Text);     lblBalance.Text = b.GetBalance(ref custNumber).ToString(); } 
  10. Run the project. Enter a number between 1 and 10 in the Customer Number TextBox control and click the Get Balance button to see that customer's balance.

graphics/note_icon.gif

When you build the DLL using Visual Basic 6.0, it automatically registers the DLL in the Windows Registry. If you are using the code files from the CD, you must register MyCustomer.dll using regsvr32.exe , as shown here:

regsvr32 MyCustomer.dll


The Type Library Importer creates an RCW for the COM type library. This RCW is a library you can add to your .NET project as a reference. After you do that, the classes in the COM component can be used just like native .NET classes. When you use a class from the COM component, .NET makes the call to the RCW, which in turn forwards the call to the original COM component and returns the results to your .NET managed code.

Using COM Components Directly

As with ActiveX controls, the Visual Studio .NET interface provides a streamlined way to use a COM component from your .NET code. Complete the following steps to work with Direct Reference:

  1. Add a new Visual C# .NET Web Application project in the existing solution, and name it Example11_2 .

  2. Create a user interface similar to that of Example11_1 .

  3. Right-click the References node in Solution Explorer and select Add Reference. Select the COM tab in the Add Reference dialog box. Then scroll down the list of COM components until you come to the MyCustomer library. Select the MyCustomer library, click Select, and then click OK.

  4. Switch to Code view and enter this code in the class definition; be sure to attach the event handlers to their respective events:

     MyCustomer.Balances b; private void Page_Load(object sender, System.EventArgs e) {    b = new MyCustomer.Balances();    txtCustomerNumber.Text = b.CustomerCount.ToString(); } private void btnGetBalance_Click(object sender, System.EventArgs e) {     Int16 custNumber = Int16.Parse(txtCustomerNumber.Text);     lblBalance.Text = b.GetBalance(ref custNumber).ToString(); } 
  5. Set the project as the startup project for the solution and run the project. Enter a number between 1 and 10 in the Customer Number TextBox control and click the Get Balance button to see that customer's balance.

When you directly reference a COM library from the Visual Studio .NET Integrated Development Environment (IDE), the effect is almost the same as if you used the Type Library Importer to import the same library. Visual Studio .NET creates a new namespace with the name of the original library and then exposes the classes from the library in that namespace.

Although you can use either of the two methods you've seen to call a COM component from a .NET component, the following are some reasons to prefer one method over the other:

  • For a COM component that will be used in only a single Visual C# .NET project, and that you wrote yourself, use the easiest method: a direct reference from the .NET project. This method is suitable only for a truly private component that does not need to be shared by other projects.

  • If a COM component is shared among multiple projects, use the Type Library Importer so you can sign the resulting assembly and place it in the global assembly cache (GAC). Shared code must be signed.

  • If you need to control details of the created assembly, such as its name, namespace, or version number, you must use the Type Library Importer. The direct reference method gives you no control over the details of the created assembly.

graphics/note_icon.gif

You should not import methods on code that is written by another developer because you are not allowed to sign code that is written by someone else. If you need to use a COM component from another developer, you should obtain a primary interop assembly ( PIA ) from the original developer of the component. Microsoft supplies PIAs for all its own common libraries.




MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
ISBN: 789729016
EAN: N/A
Year: 2005
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net