Lab 5: Deploying Office Documents that Use Managed Code Extensions

 

Lori Turner
Microsoft Corporation

March 2004

Applies to:
    Microsoft® Visual Studio® Tools for the Microsoft Office System
    Microsoft Office Professional Edition 2003
    Microsoft Visual Basic® .NET 2003

Summary: Demonstrates some of the methods you can use to deploy Office solutions created with Visual Studio Tools for the Microsoft Office System. (10 printed pages)

Contents

Introduction
Exercise 1: Using Caspol.exe to Create .NET Framework Security Policies
Exercise 2: Creating a Setup for Your Managed Code Office Solution
Exercise 3: Testing Primary Interop Assembly (PIA) Install-on-Demand
Next Steps

Download the VSTOLabs.exe sample file.

Introduction

The objective of this lab is to introduce you to some of the methods you can use for deploying your Microsoft Office 2003 managed code solutions, as well as discuss security issues. In the lab exercises, you use the Code Access Security Policy tool (Caspol.exe) to set up policies; you also create a Setup application that uses a custom Installer class for deploying the document, assembly, and required policies for a local computer solution. Then you test your Setup to observe "install on demand" for the Office primary interop assemblies.

For testing the various deployment scenarios, you use the My Word Bookmarks project you created in Lab 1: Creating Projects Using Visual Studio Tools for the Microsoft Office System.

Estimated time to complete:

  • Exercise 1: Using Caspol.exe to Create .NET Framework Security Policies - 15 minutes
  • Exercise 2: Creating a Setup Project for Your Managed Code Office Solution - 30 minutes
  • Exercise 3: Testing Primary Interop Assembly (PIA) Install-on-Demand - 15 minutes

For a link to all labs in this series, see Visual Studio Tools for the Microsoft Office System Training.

Note   The labs in this series are designed to be completed in order.

Exercise 1: Using Caspol.exe to Create .NET Framework Security Policies

To get started

  1. Copy the folder C:\Labs\Lab1\My Word Bookmarks and all its contents to C:\Labs\Lab5\.

  2. Start Word 2003.

  3. On the File menu, click New, and then select From existing document in the task pane.

  4. Browse to C:\Labs\Lab5\My Word Bookmarks\My Word Bookmarks.dot, and click Create New.

    When the document opens, you receive the following error:

    The current .NET security policy does not permit My Word Bookmarks to run from the folder \My Word Bookmarks_bin\.

    You receive this error because the assembly does not have permissions to load from the folder C:\Labs\Lab5\My Word Bookmarks\My Word Bookmarks_bin.

  5. Close the document without saving changes and quit Word.

To use Caspol.exe to create a code group for the assembly

  1. Create a batch file with the following contents and save the batch file as C:\Labs\Lab5\My Word Bookmarks\SecuritySetup.bat:

    @rem - polchgprompt - Enables or disables the prompt that is displayed
    @rem -                whenever Caspol.exe is run using an option that
    @rem -                would cause policy changes.
    @rem - addgroup - Adds a new code group to the code group hierarchy.
    @rem - url - Specifies code that originates from the given URL.
    @rem - name - specifies the scripting name for a code group to add.
    
    CD \
    PATH=%windir%\microsoft.net\framework\v1.1.4322\
    caspol.exe -polchgprompt off -u -addgroup All_Code -url "C:\labs\lab5\My Word Bookmarks\My Word
     Bookmarks_bin\My Word Bookmarks.dll"  FullTrust -name "My Word Bookmarks Assembly"
    caspol.exe -polchgprompt on
    Pause
    
  2. At a command prompt, execute the batch file:

    "C:\Labs\Lab5\My Word Bookmarks\SecuritySetup.bat"
    
  3. Examine the new user-level code group named "My Word Bookmarks Assembly" in the .NET Configuration 1.1 window.

    After changing or creating a policy, you should quit all instances of Word for your policy to take effect. Verify that no instances of Winword.exe are running using Windows Task Manager.

  4. Start Word.

  5. On the File menu, click New and then select From existing document in the task pane.

  6. Browse to C:\Labs\Lab5\My Word Bookmarks\My Word Bookmarks.dot and click Create New.

  7. This time, the document opens without error, and the managed code extension executes.

Exercise 2: Creating a Setup Project for Your Managed Code Office Solution

This exercise contains the following tasks:

  • Create a custom action for installing and uninstalling a Microsoft .NET Framework security policy.
  • Create the Setup project for deploying the document, assembly, and .NET Framework security policy.

Task 1: Create a Custom Action for Installing and Uninstalling a Microsoft .NET Framework Security Policy

To create a project and add a custom action

  1. Start Visual Studio .NET and open C:\Labs\Lab5\My Word Bookmarks\My Word Bookmarks.sln.

  2. On the File menu, click Add Project, and then choose New Project.

  3. In the New Project dialog box, select Visual Basic Projects in the Project Type pane, and then choose Class Library in the Templates pane.

  4. In the Name box, type SetupHelper, and in the Location box, type C:\Labs\Lab5.

  5. Click OK to add the new project to your solution.

  6. On the Project menu, choose Add New Item.

  7. Select the Installer Class, name the new class SecurityCustomAction.vb and click Open.

  8. On the View menu, click Code.

  9. Add the following Imports statement to SecurityCustomAction.vb:

    Imports System.Security
    

    The SetupPolicy function creates a .NET user-level security policy with FullTrust permissions and the URL for evidence.

  10. Add the SetupPolicy function to the SecurityCustomAction class:

    Private Function SetupPolicy(ByVal sPath As String, ByVal sName As String)
    
        'Get a reference to the User level "All Code" group.
        Dim PolLevel As Policy.PolicyLevel
        Dim PolLevels As IEnumerator = _
            System.Security.SecurityManager.PolicyHierarchy
        Do While PolLevels.MoveNext
            If PolLevels.Current().Label = "User" Then
                PolLevel = PolLevels.Current
                Exit Do
            End If
        Loop
        Dim AllCodeCG As Policy.UnionCodeGroup
        AllCodeCG = PolLevel.RootCodeGroup  'All code group
    
        ' Create a new code group with the FullTrust permission
        ' set and a URL as evidence of membership.
        Dim permSet As System.Security.PermissionSet = _
            PolLevel.GetNamedPermissionSet("FullTrust")
        Dim URLMemCond As System.Security.Policy.UrlMembershipCondition = _
            New System.Security.Policy.UrlMembershipCondition(sPath)
        Dim cg As System.Security.Policy.UnionCodeGroup = _
            New System.Security.Policy.UnionCodeGroup( _
            URLMemCond, New System.Security.Policy.PolicyStatement(permSet))
        cg.Name = sName
        AllCodeCG.AddChild(cg)
    
        ' Save the policy.
        System.Security.SecurityManager.SavePolicy()
    
    End Function
    
  11. Override the Install member of the SecurityCustomAction class so that it calls the SetupPolicy function to create the policy:

    Public Overrides Sub Install(ByVal stateSaver _
        As System.Collections.IDictionary)
        MyBase.Install(stateSaver)
        SetupPolicy(Me.Context.Parameters.Item("path"), _
            Me.Context.Parameters.Item("name"))
    End Sub
    

    The RemovePolicy function attempts to locate a .NET Framework user-level security policy with the given name, the given URL, and a FullTrust permission set. If such a policy is found, then the policy is removed.

  12. Add the RemovePolicy function to the SecurityCustomAction class:

    Private Function RemovePolicy(ByVal sPath As String, ByVal sName As String)
        ' Get a reference to the User level "All Code" group.
        Dim PolLevel As Policy.PolicyLevel
        Dim PolLevels As IEnumerator = _
            System.Security.SecurityManager.PolicyHierarchy
        Do While PolLevels.MoveNext
            If PolLevels.Current().Label = "User" Then
                PolLevel = PolLevels.Current
                Exit Do
            End If
        Loop
        Dim AllCodeCG As Policy.UnionCodeGroup
        AllCodeCG = PolLevel.RootCodeGroup  'All code group
    
        ' Determine the resolved membership condition for the 
        ' specified path.
        Dim sResolvedPath As String = _
            New System.Security.Policy.UrlMembershipCondition _
            (sPath).ToString()
    
        ' Locate a code group with the same name, the same resolved 
        ' path, and FullTrust; if found, remove the child group.
        Dim CGs As IEnumerator = AllCodeCG.Children.GetEnumerator()
        Do While CGs.MoveNext
            Dim CG As Policy.CodeGroup
            CG = (CType(CGs.Current(), Policy.CodeGroup))
            If CG.Name = sName Then
                If CG.MembershipCondition.ToString = sResolvedPath And _
                    AllCodeCG.PermissionSetName = "FullTrust" Then
                    AllCodeCG.RemoveChild(CG)
                    System.Security.SecurityManager.SavePolicy()
                    Exit Do
                End If
            End If
        Loop
    
    End Function
    
  13. Override the Uninstall member of the SecurityCustomAction class so that it calls the RemovePolicy function to remove the policy when the user uninstalls:

    Public Overrides Sub Uninstall(ByVal savedState As System.Collections.IDictionary)
        MyBase.Uninstall(savedState)
        RemovePolicy(Me.Context.Parameters.Item("path"), _
            Me.Context.Parameters.Item("name"))
    End Sub
    
  14. In Solution Explorer, right-click the SetupHelper project and click Build.

Task 2: Create the Setup Project for Deploying the Document, Assembly, and .NET Framework Security Policy

To create the Setup project

  1. In Solution Explorer, right-click Solution My Word Bookmarks, point to Add on the context menu, and then click New Project.

  2. In the list of ProjectTypes, choose Setup and Deployment Projects, and select the SetupWizard template.

  3. Set the project name to Setup and the project location to C:\Labs\Lab5 and click OK.

    The Setup Wizard starts.

  4. In the Setup Wizard, click Next.

  5. Select Create a setup for a Windows application and click Next.

  6. Select Primary output from My Word Bookmarks, select Primary output from SetupHelper, and click Next.

  7. Click Add to include both the Word template and the XML file:

    C:\Labs\Lab5\My Word Bookmarks\My Word Bookmarks.dot

    C:\Labs\Lab5\My Word Bookmarks\WordReadBookmark.xml

    and click Next.

  8. Click Finish.

  9. In Solution Explorer, select the Setup project and press F4 to display the Properties window. Change the properties in the Properties window as shown in Table 1:

    Table 1. Setup project properties

    Property Property Value
    Author YourName
    Manufacturer VSTO Lab
    ProductName My Word Bookmarks
    Title My Word Bookmarks Setup
  10. In Solution Explorer, expand the Detected Dependencies node of the Setup project.

    By default, the Office primary interop assemblies (PIAs) are included in your Setup application; however, you should not distribute the primary interop assemblies. You should instead allow Office 2003 Setup (or install-on-demand) to install them.

  11. Right-click each of the following assemblies in the DetectedDependencies node and choose Exclude from the shortcut menu to exclude them from your Setup:

    • Microsoft.Office.Interop.Word.dll
    • Microsoft.Vbe.Interop.dll
    • Microsoft.Vbe.Interop.Forms.dll
    • Office.dll
    • stdole.dll
  12. In Solution Explorer, right-click Primary output from My Word Bookmarks, and click Find in Editor on the shortcut menu.

    The File System editor appears.

  13. In the File System editor, right-click Application Folder, click Add, and then click Folder.

  14. Name the new subfolder My Word Bookmarks_bin.

  15. Drag Primary output from My Word Bookmarks (Active) from the Application folder to the My Word Bookmarks_bin subfolder.

  16. In Solution Explorer, right-click Primary output from SetupHelper, and click Find in Editor.

To add your custom action to install the policy:

  1. On the View menu, click Editor, and then click Custom Actions.

  2. In the Custom Actions window, right-click Install, and choose Add Custom Action.

  3. In the Select Item in Project dialog box, open Application Folder, select Primary output from SetupHelper (Active) and click OK.

  4. In the Custom Actions window, select Primary output from SetupHelper, and press F4 to display the Properties window.

  5. In the Properties window, change the CustomActionData property to (all on one line):

    /path="[TARGETDIR]My Word Bookmarks_bin/My Word Bookmarks.dll" /name="My Word Bookmarks from Setup"

To add your Custom Action to uninstall the policy

  1. In the Custom Actions window, right-click Uninstall, and choose Add Custom Action.

  2. In the Select Item in Project dialog box, open Application Folder, select Primary output from SetupHelper (Active), and click OK.

  3. In the Custom Actions window, select Primary output from SetupHelper,****and press F4 to display the Properties window.

  4. In the Properties window, change the CustomActionData property to (all on one line):

    /path="[TARGETDIR]My Word Bookmarks_bin/My Word Bookmarks.dll" /name="My Word Bookmarks from Setup"

Testing the Application

Your Setup creates a new policy. Recall that after you change or create a policy, you should quit all instances of Word for your policy to take effect. Verify that no instances of Winword.exe are running using Windows Task Manager.

Try it out:

  1. In Solution Explorer, right click the Setup project and click Build on the context menu.

  2. To test the installation, right-click the Setup project in Solution Explorer and click Install.

  3. Follow the instructions in the Setup wizard to complete the installation.

  4. Open the .NET Framework Configuration 1.1 window and verify that the new My Word Bookmarks from Setup user-level policy was created by the Setup program.

  5. Close the .NET Framework Configuration 1.1 window.

  6. Start Word.

  7. On the File menu, click New. In the task pane, click From existing document.

  8. Browse to the template installed by your Setup (the default install path would be C:\Program Files\VSTO Lab\My Word Bookmarks\My Word Bookmarks.dot) and click Create New.

    If the Setup was successful, the managed code extension executes when the document is created.

  9. Quit Word.

  10. Use Add or Remove Programs in Control Panel to uninstall the My Word Bookmarks solution.

    After uninstalling, verify that the folder "C:\Program Files\VSTO Lab\My Word Bookmarks" and the .NET policy have been removed.

Exercise 3: Testing Primary Interop Assembly (PIA) Install-on-Demand

In a run-time situation, if an Office primary interop assembly (PIA) is set to Installed on first use in Office Setup, that PIA is installed "on demand" when a document with a managed code extension is opened in Word or Excel. In this exercise, you change the install state for the Word PIA to observe the install-on-demand feature when a Word document with a managed code extension is opened.

To uninstall the Word PIA

  1. In Control Panel, run Add or Remove Programs.

  2. Select Microsoft Office Professional Edition 2003 in the Currently installed programs list, and click Change.

    The Microsoft Office 2003 Setup Wizard starts.

  3. Choose Add or Remove Features and click Next.

  4. Select the Choose Advanced customization of applications check box and click Next.

  5. Expand Microsoft Office Excel, click the box next to .NET Programmability Support, and then click Installed on First Use.

  6. Expand Microsoft Office Word, click the box next to .NET Programmability Support, and then click Installed on First Use.

  7. Expand Office Tools, click the box next to Microsoft Forms 2.0 .NET Programmability Support, and then click Installed on First Use.

  8. Under Office Tools, expand Microsoft Graph, click the box next to .NET Programmability Support, and then click Installed on First Use.

  9. Click Update.

To examine the list of assemblies that are installed

  1. Open the .NET Framework Configuration 1.1 window, and double-click Assembly Cache.

  2. On the View menu, click Assemblies.

    All the assemblies installed to the global assembly cache are displayed. Observe that the Word primary interop assembly (Microsoft.Office.Interop.Word.dll) is not in the global assembly cache.

To install the primary interop assemblies "on demand"

  1. Leave the .NET Configuration 1.1 window open. Run your My Word Bookmarks Setup program (C:\Labs\Lab5\Setup\Debug\Setup.msi).

  2. Start Word.

  3. On the File menu, click New.

  4. In the task pane, click From existing document.

  5. Browse to the template installed by your Setup (the default install path would be C:\Program Files\VSTO Lab\My Word Bookmarks\My Word Bookmarks.dot) and click Create New.

    The managed code extension executes once the Word primary interop assembly has been "installed on demand".

    **Note   **The primary interop assembly install-on-demand is silent and may take a minute. Also note that the cursor does not change to an hourglass during the installation.

  6. Quit Word.

  7. To examine the list of assemblies that are installed, return to the **.**NET Configuration 1.1 window.

  8. On the View menu, click Refresh Assembly List.

    Observe that the Word primary interop assembly (Microsoft.Office.Interop.Word.dll) is now in the GAC; it was installed on demand by Word when you loaded your managed code extension.

Next Steps

See Lab 6: Using XML and C# in Word Solutions to learn how to populate and retrieve data from XML nodes in a Word document at run time using Visual C# code and Visual Studio Tools for the Microsoft Office System.

For more information, as well as links to other labs in this series, see Visual Studio Tools for the Microsoft Office System Training.