Plotting PIA

Primary Interop Assembly Mapping and ClearCase Integration for .NET

Greg Nudelman

October 30, 2009

15 Min Read
ITPro Today logo in a gray background | ITPro Today

asp:Feature

LANGUAGES:ALL

ASP.NETVERSIONS: 1.x

 

Plotting PIA

Primary Interop Assembly Mapping and ClearCaseIntegration for .NET

 

By Greg Nudelman

 

There exist numerous good Best Practices documents thatdescribe all the stages of building and deploying a .NET application. However,it is still difficult to find cohesive real-world guidance to the entireprocess of creating, mapping, and deploying Primary Interop Assemblies (PIAs).This article will show you how to create PIAs, as well as examine threealternative methods for mapping them to your .NET solution: in the applicationtree, as COM objects, and in the Framework directory. I ll examine the pros andcons of each approach and show that the best mapping for easy deployment andClearCase integration can be achieved by mapping PIAs in the .NET Frameworkdirectory using an absolute file path.

 

What Is PIA?

PIA stands for Microsoft Primary Interop Assembly. PIAsare essentially stubs that have little functionality by themselves, butprovide a sort of window into other objects and methods. PIAs are used to mapCOM objects and native unmanaged Windows code to managed code run by the.NET Common Language Runtime. For example, accessing Microsoft Excelfunctionality from a .NET application usually requires creating and mappingPIAs. Visit http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/whypriinterop.aspfor more background information on PIAs.

 

Creating PIAs

Specifically, the work described herein was performedusing .NET Framework 1.1 on Windows 2000 Server Service Pack 4 with MicrosoftOffice 2000. Given the appropriate adjustments to system directory mappings,the methods described in this article also work well for .NET Framework 1.0.

 

To create a PIA from an existing DLL, the followingprocess can be used. The complete process is demonstrated here usingEasybaro.dll, a handy third-party control provided by Bokai Corp. (http://www.bokai.com) and used to createbarcode images. Examples that create Microsoft Excel PIA are shown, as well.

 

1. Run Regsvr32 Utility

This tool registers and un-registers (regsvr32 /u) oldnon-managed DLLs in the Windows Registry. This step is usually doneautomatically by the install package for the third-party DLLs and is not neededif the third-party install utility works correctly. When Regsvr32.exe is run,it attempts to load the component and call its DLLSelfRegister function. Ifthis attempt is successful, Regsvr32.exe displays a dialog box indicatingsuccess. If the attempt is unsuccessful, Regsvr32.exe returns an error message,which may include a Win32 error code. For a complete list of Win32 error codes,visit http://www.microsoft.com/technet/treeview/default.asp?url=/technet/support/eventserrors.asp.

 

Easybaro PIA.Run the following at the Command Prompt:

 

C:>C:WINNTsystem32regsvr32.exe

"C:Clearcasetest_dev_viewTest_ApplicationSource_Code

TestApplicationWebbinEasybaro.dll"

 

The output of this command should be a succeeded dialogbox.

 

Excel PIA. Thisstep is not required for generating Microsoft Excel PIA (DLL registration wasperformed during the Microsoft Office installation).

 

2. Run SN: Strong Name Tool

This tool generates a strong name key for the new PIA DLL.More information can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cptools/html/cpgrfstrongnameutilitysnexe.asp.

 

Easybaro PIA. Runthe following at the Command Prompt:

 

C:>"C:Program FilesMicrosoft Visual Studio .NET 2003

SDKv1.1Binsn.exe" -k "C:Clearcasetest_dev_view

Test_ApplicationSource_CodeTestApplicationWebbinkey.snk"

 

The output of this command is a key pair file key.snk that is written to theC:Clearcasetest_dev_viewTest_ApplicationSource_CodeTestApplicationWebbindirectory.

 

Excel PIA. Thecommand is exactly the same for Excel PIA. Be sure you generate a differentkey.snk for every PIA you are making.

 

3. Run Tlbimp: Type Library Importer Tool

This tool is a type library importer; it makes abridge-marshaling utility that helps execute conversion of the non-managedcode. Tlbimp uses the strong key generated in step 2 above to create an InteropAssembly that contains run-time metadata for the types defined within theoriginal type library.

 

More information can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cptools/html/cpgrftypelibraryimportertlbimpexe.asp.

 

Easybaro PIA.Run the following at the Command Prompt (note that the whole command should beon one line):

 

C:>"C:Program FilesMicrosoft Visual Studio .NET 2003

SDKv1.1Bintlbimp" "C:Clearcasetest_dev_view

Test_ApplicationSource_CodeTestApplicationWebbin

Easybaro.dll" /keyfile:"C:Clearcasetest_dev_view

Test_ApplicationSource_CodeTestApplicationWebbin

key.snk" /out:"C:Clearcasetest_dev_viewTest_Application

Source_CodeTestApplicationWebbinInterop.Easybaro.dll"

 

The output of this command is the new Interop.Easybaro.dllPIA that is imported from the original Easybaro.dll. The new PIA will bewritten to the out/ directory, C:Clearcasetest_dev_viewTest_ApplicationSource_CodeTestApplicationWebbin.

 

Steps 1-3 generate a working Interop.Easybaro.dll PIAthat can be added as a resource to any .NET project. The methods and classescontained in the original Easybaro.dll are now available to be called from the.NET code, and can be examined in step 4.

 

Excel PIA. Togenerate the Microsoft Office Excel PIAs, this command must be run using theCommand Prompt on C:Program FilesMicrosoft OfficeOfficeEXCEL9.OLB libraryas follows (note that the whole command should be on one line):

 

C:>"C:Program FilesMicrosoft Visual Studio .NET 2003

SDKv1.1Bintlbimp" "C:Program FilesMicrosoftOffice

OfficeEXCEL9.OLB"/keyfile:"C:Clearcasetest_dev_view

Test_ApplicationSource_CodeTestApplicationWebbin

key.snk"/out:"C:Clearcasetest_dev_viewTest_Application

Source_CodeTestApplicationWebbinExcel.dll"

 

This command prints out Type library imported toExcel.dll . In fact, it creates not one, but three new Interop Assemblies, allof which are required for using Excel in the .NET Framework. After the commandcompletes, the following three DLLs are placed in the /out directory (in thiscase,C:Clearcasetest_dev_viewTest_ApplicationSource_CodeTestApplicationWebbin):

  • Excel.dll

  • Office.dll

  • VBIDE.dll

 

To avoid confusion, we recommend that you rename theseDLLs as:

  • Interop.Excel.dll

  • Interop.Office.dll

  • Interop.VBIDE.dll

 

4. Ildasm: MSIL Disassembler

This tool can be used to examine the contents of the newmanaged code Interop DLL that was created in step 3. This step is strictlyoptional, but can be educational. More information can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cptools/html/cpconmsildisassemblerildasmexe.asp.

 

Easybaro PIA.Run the following at the Command Prompt:

 

C:>"C:Program FilesMicrosoft Visual Studio .NET 2003

SDKv1.1BinIldasm.exe" "C:Clearcasetest_dev_view

Test_ApplicationSource_CodeTestApplicationWebbin

Interop.Easybaro.dll"

 

This command launches a new IL DASM UI window thatdescribes the Interop.Easybaro.dll s classes and API.

 

Excel PIA.Assuming the working directory in step 3 wasC:Clearcasetest_dev_viewTest_ApplicationSource_CodeTestApplicationWebbin,the three new Interop Assemblies were created there. To examine the methods andobjects available in the new PIA, run the following at the Command Prompt:

 

C:>"C:Program FilesMicrosoft Visual Studio .NET 2003

SDKv1.1BinIldasm.exe" "C:Clearcasetest_dev_view

Test_ApplicationSource_CodeTestApplicationWebbin

Interop.Excel.dll"

 

This command launches a new IL DASM UI window thatdescribes the Interop.Excel.dll s classes and API.

 

Office 2003 offers alternative visual tools for PIAgeneration and mapping. Although this is beyond the scope of this article,interested parties should examine the following links for more information:

 

Mapping PIAs

After PIAs are created, they must be placed somewhere onthe server machine and mapped to the .NET application to import Excelfunctionality into the .NET project. In the previous step, we created threeInterop Assemblies required for importing Excel:

  • Interop.Excel.dll

  • Interop.Office.dll

  • Interop.VBIDE.dll

 

We also created Interop.Easybaro.dll, which is needed toimport Bokai s Easybaro.dll. To save space, this article shows mapping examplesfor Interop.Excel.dll only. Note that the other two Interop Assemblies,Interop.Office.dll and Interop.VBIDE.dll, should always be mapped together withthe Excel PIA. Interop.Easybaro.dll PIA does not require any supporting files,and can be mapped in exactly the same way as Interop.Excel.dll.

 

In the Test_Application example, the Excel functionalityis required for the Common Project. Under this configuration, assuming thecode is written in C#, PIA mappings are contained in the Common.csproj ProjectConfiguration file. If the project code is written in VB.NET, the mappingswould be contained in the Common.vbproj file instead. The rest of the PIAmapping and configuration details described in this article should be exactlythe same regardless of the programming language. The directory structure forTest_Application is shown in Figure 1.

 


Figure 1: The directory structure forthe Test_Application example.

 

This article examines the pros and cons of differentmethods of PIA mappings, PIA integration with the ClearCase code repository,and how the PIA mappings affect the ability to distribute .NET code to otherdevelopment machines. This article demonstrates how to map PIAs in three ways:

1)     Inthe application tree.

2)     AsCOM objects.

3)     Inthe Framework directory.

 

Method 1: Map PIAs in the Application Tree

Using method 1, Interop.Excel.dll PIA built as describedabove is placed directly into the Commonobj directory. Then the PIA referenceis set up using Visual Studio | Solution Explorer | Common | References (seeFigure 2). Right-click on the References folder and select Add Reference.

 


Figure 2: Visual Studio | SolutionExplorer | Common | References.

 

In the resulting Add Reference dialog box, click Browse,find and select the Interop.Excel.dll PIA file, then click Select. You shouldsee a dialog box like the one shown in Figure 3.

 


Figure 3: Adding a reference toInterop.Excel.dll PIA in the Commonobj directory.

 

Click OK to save the PIA mappings in the Common.csprojfile. After mapping the Interop Assembly as described above, the mapping in theCommon.csproj file looks something like this:

 

 Name ="Interop.Excel"    AssemblyName = "Interop.Excel"  HintPath ="objInterop.Excel.dll" />   Under Visual Studio | Solution Explorer | Common |References, the reference appears as Interop.Excel . As a final step,CommonobjInterop.Excel.dll file and the two companion Interop Assemblies,Interop.Office.dll and Interop.VBIDE.dll are added to the ClearCase coderepository, and the Common.csproj file that contains the PIA mappings ischecked back into ClearCase.   This method presents a neat solution because it aggregatesall the necessary DLL files in the folder of the .NET project in which they areused. However, this method also presents several significant problems.   To begin with, to compile the Common .NET project, all theInterop libraries in the Commonobj directory must be made writable (they mustbe hijacked or permanently checked-out from the ClearCase archive). Withevery compilation of the files in the Common project, these Interop librariesare copied by the .NET Framework into Web/bin folder, and the timestamps ofthese copied DLLs are updated. Because of this, all three Interop DLLs in theWeb/bin folder must be re-deployed to QA and production environments with everycode release.   Additional problems occur when the code is first installedon a virgin development machine. In this case, the compilation of the Commonproject results in numerous errors of the type:   can t find method/class X, are you missing an assemblyreference?   These errors occur because the PIA mappings cannot beautomatically established by .NET. The same behavior is observed any time thecode base is completely updated from ClearCase on the same development machine.In this case, all the PIA mappings are similarly lost, with the resultingpredictable can t find method/class errors.   To resolve these problems, the developer must delete andthen recreate all the PIA mappings after every complete code update using theprocess described above. As a result of these drawbacks, mapping PIAs in theapplication tree is a less than ideal solution.  Method 2: Map PIAs as COM Objects Because method 1 fails to provide a satisfactory solution,I researched an alternative way to map my Interop.Excel.dll and related InteropAssemblies directly as COM objects. To do this, open the Add Reference dialogbox as described above and choose the COM tab. Scroll down and highlight justone object, Microsoft Excel 9.0 Object Library, and click Select; the resultingAdd Reference dialog box is shown in Figure 4.  
Figure 4: Adding a reference toMicrosoft Excel 9.0 Object Library.   Click OK to complete the addition of the COM mapping tothe Common project. After completing this step, the COM mapping in theCommon.csproj file looks like this:   Name = "Excel"  Guid = "{00020813-0000-0000-C000-000000000046}"  VersionMajor ="1"  VersionMinor ="3"  Lcid = "0"  WrapperTool ="tlbimp" />   Office and VBIDE COM objects appear alongside theExcel COM object in the Common.csproj file mapped in a similar way. UnderVisual Studio | Solution Explorer | Common | References the references appearas Excel , Office , and VBIDE . As a final step, the Common.csproj file thatcontains the PIA mappings is checked back into the ClearCase code repository.   This is a good workable solution, and one that doesn teven require producing the Interop.Excel.dll, nor keeping it in the ClearCasecode repository. An additional advantage to this mapping method is thatdistributing the project code to another machine often works correctly rightout of the box, provided that the Microsoft Office configuration is exactlythe same on both machines. However, this solution has several major drawbacks,not the least of which is that it introduces an element of DLL Hell that is afrequent headache with maintaining Windows software.   The problem with direct installation of COM objects isthat the .NET Framework maps the reference directly to GUID or the address ofthe COM object in the machine s Registry. Any differences in Microsoft Officeconfigurations between the development machines (including any problems withOffice components, upgrades, or patches) can change the GUID or the addressof the COM object in the registry. This change has a deleterious effect onmaintaining the PIA mappings during code distribution to other machines.   The loss of PIA mappings during code distribution resultsin the same can t find method/class X, are you missing an assembly reference? errors seen during the compile step shown in method 1. Again, the PIA mappingis lost and must be deleted and recreated using the Visual Studio | SolutionExplorer | Common | References setup dialog box as previously described.However, in contrast to method 1, reestablishing the direct COM mappingsresults in having different Common.csproj files on different machines. Thismeans that one csproj file will not work on another machine with a slightlydifferent Microsoft Office configuration, and thus Common.csproj files can NOTbe checked into ClearCase. Therefore, although this method of direct COMmapping is a slight improvement over method 1, it is also less than ideal.  Method 3: Map PIAs in the Framework Directory After spending some time trying to understand theintricacies of PIA mapping, and investigating methods 1 and 2, I still had tocome up with a satisfactory solution that would work well with my ClearCaserepository. What I needed, I theorized, was an equivalent of the Java lib directory. This directory acts as a sort of central library repository: anythingplaced into this directory is automatically available for mapping to theapplication and any mappings to the objects in the lib directory can besafely distributed between development machines.   I finally found the .NET equivalent of the Java lib directory I was looking for under the .NET tab in the Visual Studio | SolutionExplorer | Common | References setup dialog box. I discovered that a great manylibraries in this tab are mapped from theC:WINNTMicrosoft.NETFrameworkv1.1.4322 directory. If the PIAs are placedin that directory, would .NET maintain persistent mappings to these libraries?As I expected, this was indeed the case.   To map the PIA using this method, begin by placing theInterop.Excel.dll and its companion libraries (Interop.Office.dll andInterop.VBIDE.dll) into the C:WINNTMicrosoft.NETFrameworkv1.1.4322directory. As in methods 1 and 2, go to Visual Studio | Solution Explorer |Common | References and select Add Reference. Navigate to the .NET tab andselect Interop.Excel.dll PIA. The resulting dialog box is shown in Figure 5.  
Figure 5: Adding a reference toInterop.Excel.dll PIA in the .NET Framework directory.   Map the two remaining Excel companion Interop libraries(Interop.Office.dll and Interop.VBIDE.dll) in the same way and click OK to savethe mappings in the Common.csproj file. At this point, the mappings in theCommon.csproj file look like this:   Name ="Interop.Excel"  AssemblyName ="Interop.Excel"  HintPath ="............WINNTMicrosoft.NETFramework v1.1.4322Interop.Excel.dll" />   Under Visual Studio | Solution Explorer | Common |References the Excel PIA reference appears as Interop.Excel .   This method at last presents a workable solution thatinterfaces very well with the ClearCase repository. As long as every machinehas the Interop libraries in the C:WINNTMicrosoft.NETFrameworkv1.1.4322directory, the rest of the code can be safely checked into the ClearCaserepository, updated, and redeployed without losing the PIA mappings.   The only problem with this solution is experienced whensome of the dev machines have the ClearCase VOB code base installation on anydrive other than the C: drive, or in a different directory structure. In thosecases, the relative mapping to:  ............WINNTMicrosoft.NETFrameworkv1.1.4322 Interop.Excel.dll   in the Common.csproj file is in fact pointing to:   D:WINNTMicrosoft.NETFrameworkv1.1.4322 Interop.Excel.dll   or some other incorrect relative path to the PIA file.When the code is distributed to such a machine, the result is the same can tfind method/class X, are you missing an assembly reference? errors seen inmethod 1. This time, however, the problem is easily remedied by manuallyediting the Common.csproj file to point to the correct .NET Framework directoryusing the absolute path instead:   Name ="Interop.Excel"  AssemblyName ="Interop.Excel"  HintPath = "C:WINNTMicrosoft.NETFrameworkv1.1.4322 Interop.Excel.dll" />   The resulting Common.csproj file is then checked back intothe ClearCase repository. Because the mappings are absolute, this Common.csprojfile can be safely distributed to other machines and is guaranteed to workwithout any problems regardless of the ClearCase repository folderconfiguration on the target machines.   From the findings, this article draws the conclusion thatthe best solution for easy deployment and ClearCase integration can be achievedby mapping PIAs in the .NET Framework directory using an absolute file path, asshown in method 3.   The method of mapping PIAs to the .NET Framework directoryusing the absolute path presents a very elegant and flexible real-world solution to a complex problem. The only requirement is that the .NET Frameworkmust be installed on the C: drive on all the development machines, and theInterop DLLs are added to the .NET Framework directory (this can beaccomplished easily with a simple batch script). This solution ensures that theabsolute mappings always point to the correct PIA files on every developmentmachine, regardless of the individual Microsoft Office configuration. Thissolution integrates perfectly with the ClearCase code repository, because thecode can be safely distributed to other machines requiring nothing extra to bechecked into the code repository or mapped manually.  Conclusion This article described the complete process for buildingand mapping Microsoft .NET Primary Interop Assemblies (PIAs). The mappingmethod that seems to be best suited to diverse development environmentsinvolves placing all the PIAs into C:WINNTMicrosoft.NETFrameworkv1.1.4322and mapping the PIA references in the corresponding project (csproj) file usingthe absolute PIA file path. This solution allows the easiest distribution ofthe .NET projects regardless of the Microsoft Office configuration and isindependent of the drive letter or folder structure on which the .NETapplication resides. This method also offers elegant integration with the ClearCasecode repository with nothing extra to map or check in. I recommend consideringthis method of mapping Primary Interop Assemblies in your .NET developmentproject.  Greg Nudelmanearned his MS CIS from Golden Gate Universityin San Francisco. He still lives inthe San Francisco BayArea. He has worked with J2EE, .NET, and SQL for more than six years, designing,and developing multi-tier distributed applications for biotechnology andmortgage companies. His latest obsession is Web software usability.      

Read more about:

Microsoft
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like