Exposing COM Components to the .NET Framework

This section summarizes the process needed to expose an existing COM component to managed code. For details about writing COM servers that tightly integrate with the .NET Framework, see Design Considerations for Interoperation.

Existing COM components are valuable resources in managed code as middle-tier business applications or as isolated functionality. An ideal component has a primary interop assembly and conforms tightly to the programming standards imposed by COM.

To expose COM components to the .NET Framework

  1. Import a type library as an assembly.

    The common language runtime requires metadata for all types, including COM types. There are several ways to obtain an assembly containing COM types imported as metadata.

  2. Create COM types in managed Code.

    You can inspect COM types, activate instances, and invoke methods on the COM object the same way you do for any managed type.

  3. Compile an interop project.

    The Windows Software Development Kit (SDK) provides compilers for several languages compliant with the Common Language Specification (CLS), including Visual Basic 2005, C#, and C++.

  4. Deploy an interop application.

    Interop applications are best deployed as strong-named, signed assemblies in the global assembly cache.

1.Importing a Type Library as an Assembly

Generating Metadata

COM type libraries can be stand-alone files that have a .tlb extension, such as Loanlib.tlb. Some type libraries are embedded in the resource section of a .dll or .exe file. Other sources of type library information are .olb and .ocx files.

After you locate the type library that contains the implementation of your target COM type, you have the following options for generating an interop assembly containing type metadata:

  • Visual Studio

    Visual Studio automatically converts COM types in a type library to metadata in an assembly. For instructions, see How to: Add References to Type Libraries and Walkthrough: Embedding Type Information from Microsoft Office Assemblies (C# and Visual Basic).

  • Type Library Importer (Tlbimp.exe)

    The Type Library Importer provides command-line options to adjust metadata in the resulting interop file, imports types from an existing type library, and generates an interop assembly and a namespace. For instructions, see How to: Generate Interop Assemblies from Type Libraries.

  • System.Runtime.InteropServices.TypeLibConverter class

    This class provides methods to convert coclasses and interfaces in a type library to metadata within an assembly. It produces the same metadata output as Tlbimp.exe. However, unlike Tlbimp.exe, the TypeLibConverter class can convert an in-memory type library to metadata.

  • Custom wrappers

    When a type library is unavailable or incorrect, one option is to create a duplicate definition of the class or interface in managed source code. You then compile the source code with a compiler that targets the runtime to produce metadata in an assembly.

    To define COM types manually, you must have access to the following items:

    • Precise descriptions of the coclasses and interfaces being defined.

    • A compiler, such as the C# compiler, that can generate the appropriate .NET Framework class definitions.

    • Knowledge of the type library-to-assembly conversion rules.

    Writing a custom wrapper is an advanced technique. For additional information about how to generate a custom wrapper, see Customizing Standard Wrappers.

For more information about the COM interop import process, see Type Library to Assembly Conversion Summary.

How to add reference to type lib

Visual Studio generates an interop assembly containing metadata when you add a reference to a type library. If a primary interop assembly is available, Visual Studio uses the existing assembly before generating a new interop assembly.

To add a reference to a type library in Visual Studio

  1. Install the COM DLL or EXE file on your computer, unless a Windows Setup.exe file performs the installation for you.

  2. From the Project menu, select References.

  3. Select the COM tab.

  4. Select the type library from the Available References list, or browse for the .tlb file.

  5. Click OK.

  6. Right-click the newly added reference, and and then click Properties.

  7. In the Properties window, make sure that the Embed Interop Types property is set to True. This causes Visual Studio to embed type information for COM types in your executables, eliminating the need to deploy primary interop assemblies with your application.

To add a reference to a type library for command-line compilation

  1. Generate an interop assembly as described in How to: Generate Interop Assemblies from Type Libraries.

  2. Use the /link (C# Compiler Options) or /link (Visual Basic) compiler option with the interop assembly name to embed type information for COM types in your executables.

1.How to generate interop assemblies from type lib

The Type Library Importer (Tlbimp.exe) is a command-line tool that converts the coclasses and interfaces contained in a COM type library to metadata. This tool creates an interop assembly and namespace for the type information automatically. After the metadata of a class is available, managed clients can create instances of the COM type and call its methods, just as if it were a .NET instance. Tlbimp.exe converts an entire type library to metadata at once and cannot generate type information for a subset of the types defined in a type library.

To generate an interop assembly from a type library

  • Use the following command:

    tlbimp <type-library-file>

    Adding the /out: switch produces an interop assembly with an altered name, such as LOANLib.dll. Altering the interop assembly name can help distinguish it from the original COM DLL and prevent problems that can occur from having duplicate names.

The following command produces the Loanlib.dll assembly in the Loanlib namespace.

 tlbimp Loanlib.dll

The following command produces an interop assembly with an altered name (LOANLib.dll).

 tlbimp LoanLib.dll /out: LOANLib.dll 
 
Actually ,when you use reflector to check inside of the PIA dll. you will find out it contain only the type information of COM.
for example Microsoft.Office.Interop.Outlook.dll.
So . we just say . we use PIA to call the COM .

If you embed type information in an application that references COM objects, you can eliminate the need for a primary interop assembly (PIA). Additionally, the embedded type information enables you to achieve version independence for your application. That is, your program can be written to use types from multiple versions of a COM library without requiring a specific PIA for each version. This is a common scenario for applications that use objects from Microsoft Office libraries. Embedding type information enables the same build of a program to work with different versions of Microsoft Office on different computers without the need to redeploy either the program or the PIA for each version of Microsoft Office.

In this walkthrough, you will perform the following tasks:

  • Create an application that uses Automation objects from Microsoft Office and embeds the type information from the Microsoft Office COM libraries.

  • Publish and run the application with multiple versions of Microsoft Office without a PIA.

NoteNote

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

This walkthrough requires the following:

  • A computer on which Visual Studio and Microsoft Excel are installed.

  • A computer on which .NET Framework 4 and a different version of Excel are installed.

To create an application that works with multiple versions of Microsoft Office

  1. Start Visual Studio on a computer on which Excel is installed.

  2. On the File menu, point to New and then click Project.

  3. In the New Project dialog box, in the Project Types pane, make sure that Windows is selected. Select Console Application in the Templates pane. In theName box, type CreateExcelWorkbook, and then click OK. The new project is created.

  4. If you are using Visual Basic, right-click the CreateExcelWorkbook project and then click Properties. Click the References tab. Click the Add button. If you are using Visual C#, in Solution Explorer, right-click the References folder and then click Add Reference.

  5. On the .NET tab, click the most recent version of Microsoft.Office.Interop.Excel. For example, Microsoft.Office.Interop.Excel 14.0.0.0. Click OK.

  6. In the list of references for the CreateExcelWorkbook project, select the reference for Microsoft.Office.Interop.Excel that you added in the previous step. In the Properties window, make sure that the Embed Interop Types property is set to True.

    NoteNote

    The application created in this walkthrough runs with different versions of Microsoft Office because of the embedded interop type information. If theEmbed Interop Types property is set to False, you must include a PIA for each version of Microsoft Office that the application will run with.

  7. If you are using Visual Basic, double-click the Module1.vb file. If you are using Visual C#, double-click the Program.cs file. Replace the code in the file with the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;

namespace CreateExcelWorkbook
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] values = {4, 6, 18, 2, 1, 76, 0, 3, 11};

            CreateWorkbook(values, @"C:\SampleFolder\SampleWorkbook.xls");
        }

        static void CreateWorkbook(int[] values, string filePath)
        {
            Excel.Application excelApp = null;
            Excel.Workbook wkbk;
            Excel.Worksheet sheet;

            try
            {
                    // Start Excel and create a workbook and worksheet.
                    excelApp = new Excel.Application();
                    wkbk = excelApp.Workbooks.Add();
                    sheet = wkbk.Sheets.Add() as Excel.Worksheet;
                    sheet.Name = "Sample Worksheet";

                    // Write a column of values.
                    // In the For loop, both the row index and array index start at 1.
                    // Therefore the value of 4 at array index 0 is not included.
                    for (int i = 1; i < values.Length; i++)
                    {
                        sheet.Cells[i, 1] = values[i];
                    }

                    // Suppress any alerts and save the file. Create the directory 
                    // if it does not exist. Overwrite the file if it exists.
                    excelApp.DisplayAlerts = false;
                    string folderPath = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                    wkbk.SaveAs(filePath);
            }
            catch
            {
            }
            finally
            {
                sheet = null;
                wkbk = null;

                // Close Excel.
                excelApp.Quit();
                excelApp = null;
            }
        }
    }
}

8.Save the project.

9.Press CTRL+F5 to build and run the project. Verify that an Excel workbook has been created at the location specified in the example code: C:\SampleFolder\SampleWorkbook.xls.

To publish the application to a computer on which a different version of Microsoft Office is installed

  1. Open the project created by this walkthrough in Visual Studio.

  2. On the Build menu, click Publish CreateExcelWorkbook. Follow the steps of the Publish Wizard to create an installable version of the application. For more information, see Publish Wizard.

  3. Install the application on a computer on which .NET Framework 4 and a different version of Excel are installed.

  4. When the installation is finished, run the installed program.

  5. Verify that an Excel workbook has been created at the location specified in the sample code: C:\SampleFolder\SampleWorkbook.xls.

see also :

http://msdn.microsoft.com/en-us/library/d4w8x20h.aspx

http://www.ityoudao.com/Web/Csharp_590_2114.html

http://blog.csdn.net/daoyuly/article/details/3927550

http://www.cnblogs.com/yangzhj/archive/2011/11/18/2254223.html 

原文地址:https://www.cnblogs.com/malaikuangren/p/2636929.html