Introduction to the Office 2003 Primary Interop Assemblies Sample Launcher

 

John R. Durant
Microsoft Corporation

April 2005

Applies to:
    Microsoft Visual Studio 2005
    Microsoft Visual Studio 2003
    Microsoft Visual Studio 2005 Tools for the Microsoft Office System
    Microsoft Visual Studio Tools for the Microsoft Office System, Version 2003
    Microsoft Office 2003 Editions

Summary: Learn the details of the Microsoft Office 2003 Primary Interop Assemblies Sample Launcher and how to use it to view and launch sample code. (11 printed pages)

Download Office2003PIASampleLauncher.exe.

Contents

What Are Primary Interop Assemblies?
Introduction to the Primary Interop Assemblies Sample Launcher
Using OPSL
Viewing Custom Code with OPSL
Creating New Assemblies for OPSL
Providing Custom Controls in Your Form
Adding Attributes to the AssemblyInfo File
Displaying Sample Code in the Code Window
Conclusion
Additional Resources

What Are Primary Interop Assemblies?

For a number of years developers have become accustomed to developing desktop productivity solutions in Microsoft Visual Basic for Applications (VBA). In the more recent past, developers have become increasingly inclined to develop these solutions using managed code with the Microsoft .NET Framework. Microsoft provides official wrapper assemblies for writing managed code against the programmable unmanaged Microsoft Office libraries. These are called the primary interop assemblies. There has been no managed code–focused documentation for this enterprise, and there have been no official managed samples.

Introduction to the Microsoft Office 2003 Primary Interop Assemblies Sample Launcher

With the release of Microsoft Visual Studio 2005 Tools for the Microsoft Office System, this changes. Visual Studio 2005 Tools for Office includes documentation for Microsoft Office Word 2003, Microsoft Office Excel 2003, and the shared CommandBars object models, all with a managed code orientation. Accompanying this documentation is the Microsoft Office 2003 Primary Interop Assemblies Sample Launcher (OPSL).

The OPSL enables you to do more than reading code samples or cutting and pasting them to see code run. The OPSL actually runs the samples and exposes the code used for the samples. After you launch OPSL, you see a form that allows you to choose which sample group you want to run (Figure 1).

Figure 1. List of samples to launch

For example, you may want to see samples relating to the XML features in Word 2003 or those relating to ranges in Excel 2003. After you select the sample group, you are shown a form that displays the various methods in that group (Figure 2).

Figure 2. Primary launcher with the Chart.Protect method selected

This method has some arguments to customize its behavior. The signature for this method looks like this:

Chart.Protect([Password As Object], [DrawingObjects As Object], 
[Contents As Object], [Scenarios As Object], [UserInterfaceOnly As Object])

Using OPSL

To make it easier for you to experiment with passing different parameters, the form enables you to supply different values through a convenient interface. After either accepting the default parameter values or altering them, you can click Demo to load the target Office application and run code calling the target method while incorporating your parameter settings.

Note   In some cases the target methods may have many arguments, some optional and others required. The bottom half of the form displays scroll bars if the number of arguments grows large. There are some methods with so many optional parameters that they are not all displayed in the form. When you launch the sample, OPSL uses the default settings for these arguments.

Viewing Demonstration Sample Code

In addition to launching the demonstration, you can see the basic sample code that the demonstration runs by clicking Code on the form. You can see the sample code in Microsoft Visual Basic .NET and Microsoft C#. Remember that the displayed code is not dynamically generated. So, if you configure parameter settings in the form, these are not reflected in the displayed code. The displayed code is hard-coded.

Figure 3. Example of hard-coded displayed code

You can cause the form to display in both languages or just one of the two target languages by changing settings on the Options menu of the form. You can also select code in the form and copy it by clicking Copy selected demo code (also on the Options menu). The menu also has an option to copy all of the demonstration code.

Running Demonstration Code

If you choose to the run the demonstration rather than view the code, OPSL launches the demonstration. In so doing, it aligns the target Office application to the left of the launcher form (Figure 4), adjacent to the launcher form. In some cases, the demonstration uses a sample document to facilitate the code demonstration. These files are stored in a \SampleDocs folder in the same directory as the Office2003PIASampleLauncher executable. This folder contains source Word documents and templates, Excel spreadsheets and templates, XML documents, XSL stylesheets, and XSD schemas.

Figure 4. Excel is aligned next to the window

For example, running the demonstration for the Chart.Protect method launches Excel and opens an existing spreadsheet. The demonstration code displays a message (Figure 5) indicating that the demonstration is attempting to change the spreadsheet, which is protected according to the settings you configured.

Figure 5. Warning dialog box seen when running the demonstration

Once you protect a spreadsheet, attempts to change its contents fail. In these cases, Excel displays a message indicating that such alterations are not allowed (Figure 6).

Figure 6. Alternations cannot occur on a protected spreadsheet

After you complete the demonstration, you can close the target application or leave it open and run another sample. The OPSL closes open documents and opens new ones automatically as you move through samples for a single application. For example, switching from the Chart.Protect method to the Chart.Paste method causes the protected spreadsheet to close and a new one to open. Moving to a new target application (for example, moving from Excel samples to Word samples) does not cause the current application and document to close. You must minimize or close the current application.

Switching Sample Groups

Switching from one sample group to another is simple. Click the Selections menu to see the sample group list that was shown when you first started the demonstration launcher (Figure 7).

Figure 7. Choosing a sample group

The currently selected sample group is indicated, and you can move the cursor over another item and select it to change sample groups.

Restoring Your Sample Launcher View

As you use OPSL, run demonstrations, and perform other desktop tasks not related to the samples, the forms may no longer be in their intended position (OPSL to the right, target application to the left). You can refresh your view. To do so, on the Window menu of the form, click Restore. This moves OPSL to one side of your desktop and realigns the target application adjacent to the launcher.

Viewing Custom Code with OPSL

Using OPSL is simple. You do not need to know anything about the internal workings of OPSL to run demonstration code and see Office programmability in action. But, one of the great advantages of OPSL is that it is built upon an extensible sample framework. In other words, if you want to create your own samples and plug them into the OPSL framework, you can do so.

When OPSL first starts, it looks in its startup directory for .NET Framework–based assemblies that it can load into its infrastructure. Each of these assemblies is the physical manifestation of a sample group that a user sees in the list of sample groups (Figure 7). You can create your own assemblies that conform to the requirements of OPSL and place them in that startup directory so that they appear in the list of possible sample groups. You can also leave your custom assembly in another directory and navigate to it by choosing Open from the File menu of the form.

Creating New Assemblies for OPSL

To get started creating an assembly for OPSL, start Visual Studio and create a Microsoft Windows application project. On the Project Properties menu, change the project into a class library project. This ensures that the proper references are set in the project. Of course, you can choose your language of choice for this project. In your project, you must also add a reference to the DRSupport.dll assembly, located in the OPSL directory. This assembly includes class definitions and other elements that make it easy for you to add to the sample groups. You can delete the default class definition that Visual Studio adds to your new project because you will not use it. Next, add a new Windows Form to the project. You also need to add a reference to the host application (such as Word or Excel) or to its primary interop assemblies to take advantage of any of that application's functionality. A form that contains parameter information needs to exhibit certain characteristics. For example, it can have no borders, and you want the font to match the font for the rest of OPSL. The following lines of code show the settings you want to use for the form. Note that the exact height is not as important as the width of the form.

Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14)
Me.ClientSize = New System.Drawing.Size(274, 80)
Me.Font = New System.Drawing.Font("Verdana", 8.25!, 
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 
CType(0, Byte))
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
Me.Location = New System.Drawing.Point(4, 4)

In addition, your form needs to inherit from the DRSupport.ParameterForm base class, so that OPSL can communicate with the form you create. Your form must provide a RunDemo procedure using either a Sub in Visual Basic .NET, or a void procedure in C#. The OPSL calls this procedure when users click the Demo button.

Remember that this form maps to a specific method in the sample group represented by the entire assembly. Thus, you can have multiple forms within a single assembly. If your method has arguments that you want to configure in OPSL (rather than choosing to hard-code them in your demonstration code), then you can add radio buttons, text boxes, drop-down lists, and other controls to make it easier for users to set parameters.

Providing Custom Controls in Your Form

The DRSupport assembly provides custom controls, and you should use the custom controls instead of the default controls included with the .NET Framework. For example, if you want to include a radio button, you should use the DRSupport.ParameterGroupBox control. This includes the radio buttons and other controls to simplify the addition of new arguments to the form. If you want to include a check box option, use the DRSupport.CheckboxOption control. When you add these and similarly designed controls to your custom form, the user can set the values, and you can retrieve these values as normal and pass them to the method you are calling in the target application. For example, the Chart.Protect method accepts an argument for the actual password. The parameter form has a ParameterGroupBox (Figure 8) called pbxPassword.

Figure 8. The Password box

In the code, the Chart.Protect method accepts the parameter from this control by using its Value property. For example, Chart.Protect(pbxPassword.Value). Other controls expose a similar property that you can use in a like manner.

For your sample to work properly, it must expose some custom demonstration code. This code is placed in a RunDemo procedure. The RunDemo procedure is defined in the DRSupport.DemoForm base class that your custom Windows Form inherits. You must override the RunDemo procedure in your custom class. The following example shows the RunDemo code for the Chart.Protect method in OPSL:

  Public Overrides Sub RunDemo()
    Dim cht As Excel.Chart = _
      ChartDemo.CreateChart("ChartProtect", _
      Excel.XlChartType.xlColumnClustered)
    cht.Protect( _
     pbxPassword.Value, _
     pbxDrawingObjects.Value, _
     pbxContents.Value, _
     pbxScenarios.Value, _
     pbxUserInterfaceOnly.Value)
    DisplayInfo("Attempting to change the chart. " _
    & "The success depends on your protection settings.")
    cht.HasTitle = True
    cht.ChartTitle.Text = "Sales by Nation"
  End Sub

You can see that code includes a reference to an Excel chart by calling a local ChartDemo.CreateChart method. Here, ChartDemo is a class within the ExcelChart assembly and contains several shared methods that reduce code duplication for getting instances of charts and worksheets, displaying message dialogs, and so forth. You can use these same shared methods or write your own code.

Adding Attributes to the AssemblyInfo File

After you create your assembly with the desired demonstration functionality, you need to add an attribute to the AssemblyInfo file. The sample looks for this attribute as it loops through the assemblies in its startup directory. If the assembly does not contain this attribute, the assembly is not listed with the other sample groups in OPSL. Configure the attribute as follows:

<Assembly: DRSupport.Demo("Assembly_Name")>

The text, Assembly_Name, appears in the list of sample groups. To finish off the demonstration project, you need to compile it and place your executable in the startup directory where the OPSL executable is located or, on the File menu, click Open to locate your executable.

Displaying Sample Code in the Code Window

To display the sample code in the code window, your assembly must supply a file named CodeSnippets.xml, embedded as a resource within the assembly. To accomplish this, follow these steps:

  1. In Visual Studio, point to Project, and then click Add New Item. From the Add New Item dialog box, select XML File. Name the new XML file CodeSnippets.xml.
  2. In the Solution Explorer window, select the new CodeSnippets.xml file. If the Properties window isn't visible, on the View menu, click Properties Window to make it visible.
  3. In the Properties window, set the BuildAction property to Embedded Resource.

Now, you can start adding the code snippets. The root element of the XML document must be SampleCode, and the following code example shows the necessary schema:

<?xml version="1.0" encoding="utf-8"?>
<SampleCode>
    <Method Name="Chart.ApplyCustomType">
        <Code Language=" Visual Basic .NET ">
<![CDATA[        
Put your Visual Basic .NET code sample here
]]>        
        </Code>
        <Code Language="C#">
<![CDATA[        
Put your C# code sample here
]]>        
        </Code>
    </Method>
    <Method Name="Chart.SomeOtherMethod">
        <Code Language="Visual Basic .NET">
<![CDATA[        
Put your Visual Basic .NET code sample here
]]>        
        </Code>
        <Code Language="C#">
<![CDATA[        
Put your C# code sample here
]]>        
        </Code>
    </Method>
</SampleCode>

It is recommended that each code snippet either be self-sufficient or include a reference to existing code with a comment indicating how to find that existing code. In other words, you should be able to copy code examples stored in the CodeSnippets.xml file from the code window, place them into a sample application, and run them without other code, unless noted with a comment.

With the CodeSnippets.xml file embedded within the assembly, you can copy the assembly into the folder with the OPSL executable, run the application, and see your assembly in the list of available groups.

Conclusion

The Microsoft Office 2003 Primary Interop Assemblies Sample Launcher represents a milestone in the developer documentation for the Microsoft Office System. While thousands of small samples and explanations for Word, Excel, and CommandBars have accompanied the product documentation for many years, there has been a clear need for more elaborate samples. With the release of Microsoft Visual Studio 2005 Tools for the Microsoft Office System, there is also a need for these samples to be written in managed code. The OPSL provides code, samples, and a convenient launching program to make it easier for developers to see how some of the most prominent methods they will use can be coded. Additionally, the OPSL provides an extensible architecture for additional samples written by the community.

About the Author

John R. Durant is Microsoft's voice for Microsoft Office programmability and is a program manager for Visual Studio 2005 Tools for the Microsoft Office System. He has extensive experience architecting and developing small-scale to large-scale collaboration solutions in a variety of environments. He frequently delivers seminars on Microsoft .NET and Office technologies, is the co-author of the Wiley & Sons Press book The XML Programming Bible, and maintains a lively blog.

Additional Resources

For more information, read the following articles:

© Microsoft Corporation. All rights reserved.