Export (0) Print
Expand All
Expand Minimize
3 out of 6 rated this helpful - Rate this topic

Creating InfoPath 2007 Add-Ins by Using Visual Studio 2005 Tools for the Office System SE

Office 2007

Summary:   Learn how to use the Microsoft Office InfoPath 2007 object model to work with custom forms. Create a menu item to call the functionality of an InfoPath 2007 add-in and a custom task pane. (17 printed pages)

Robert Green, MCW Technologies, LLC

December 2007

Applies to:   Microsoft Visual Studio 2005 Tools for the Microsoft Office System, 2007 Microsoft Office system, Microsoft Office InfoPath 2007

Contents

Overview of Customizing InfoPath 2007 Forms

Microsoft Office InfoPath 2007 offers a variety of options for developers who want to customize InfoPath forms:

  • Using the Microsoft Script Editor to write customizations in Microsoft Visual Basic Scripting Edition (VBScript) or Microsoft JScript.

  • Writing customizations in managed code with the Microsoft Visual Studio 2005 Tools for Applications environment, which supports the Microsoft .NET Framework and Microsoft Visual Basic and Microsoft Visual C# programming languages.

  • Using Microsoft Visual Studio 2005 Tools for the Microsoft Office system to create an InfoPath 2007 add-in.

You can use the first two options to add customizations to a specific InfoPath form. However, you might want a customization to be available in more than one form. Use Visual Studio 2005 Tools for Microsoft Office to create an application-level add-in for InfoPath 2007 that is available regardless of what form is opened.

In this article, you create an InfoPath 2007 add-in by using Visual Studio 2005 Tools for Microsoft Office.

InfoPath 2007 Object Model

To write managed code that interacts with InfoPath, you use classes in the Microsoft.Office.Interop.InfoPath and Microsoft.Office.Interop.InfoPath.XML namespaces.

The top-level object in the InfoPath object model is the Application object, which represents a running instance of InfoPath. The Application object contains a collection of Window objects and XDocument objects. An open form is displayed in a window, and custom task panes belong to a window. The XDocument object represents the source XML data of an InfoPath form. To read or write to the XML in a form, you use the XDocument object and classes in the InfoPath.XML namespace.

To work with a form visually, you can use the UI object and the View object, which are exposed as properties of the XDocument object. The UI object provides methods to display custom and built-in dialog boxes. For example, you might use the Alert method of the UI object to display an error message or Help information. Views in InfoPath enable you to separate form content into multiple pages within a form. Each page is associated with a View object. You can use the SwitchView method of the View object to change views.

Creating the InfoPath Form

The InfoPath form used in this article is a customer contact form. The user inserts information about the customer and the date of contact. Before you can create an add-in for this form, you must build the form shown in Figure 2.

To build a data source for an InfoPath form

  1. In InfoPath 2007, select Design a Form Template.

  2. In the Design a Form Template dialog box, click the Blank template, and then click OK.

  3. In the Design Tasks task pane, select Data Source.

  4. In the Data Source task pane, right-click myFields, and then click Add.

  5. In the Add Field or Group dialog box, type CustomerRep in the Name text box. Select Cannot be blank, and then click OK.

  6. In the Data Source task pane, right-click myFields, and then click Add.

  7. In the Add Field or Group dialog box, enter ContactDate in the Name text box. Change the data type to Date. Set the default value to today's date, and then click OK.

  8. Add a CompanyName and a ContactName field.

    These are required strings and cannot be blank.

  9. Add the following fields: ContactTitle, Phone, Fax, Address, City, Region, PostalCode, Country, and Notes.

    These are all strings, but they are not required. The result should look like Figure 1.

    Figure 1. Fields in the Customer Contact Report form

    Fields in the Customer Contact Form

To create the contact report form

  1. On the Table menu, create one or more tables to create the contact report form. Drag the fields from the Data Source task pane into the appropriate places in the table (or directly onto the form if you are not using tables).

    The form should look similar to Figure 2.

    Figure 2. The Customer Contact Report form

    The Customer Contact Report form
  2. Save the form as Customer Contact Report.xsn.

Creating an InfoPath Add-in

In the following procedures, you create an add-in for InfoPath 2007. This add-in helps the user fill out a customer contact report form with the user’s name, the date, and customer information.

To create an InfoPath Add-in project

  1. Start Microsoft Visual Studio 2005

  2. On the File menu, click New Project.

  3. In the New Project dialog box, expand the Visual Basic project types. Expand the Office project types, and then click 2007 Add-ins.

  4. In the Templates pane, select InfoPath Add-in. Type VSTOInfoPathAddIn in the Name box, and then click OK.

  5. On the Project menu, click Show All Files.

  6. In Solution Explorer, expand the References node.

    Visual Studio adds several Office references to the project, including:

    • Microsoft.Office.Core, a reference to the Microsoft Office 12.0 Object Library.

    • InfoPath, a reference to the Microsoft Office InfoPath 12.0 Type Library.

You are creating an application-level add-in that is available whenever you have InfoPath open, regardless of the form you are working with. This add-in helps the user fill out a form. You may want the add-in available to the user for every form, or available only for some forms, but not all. In this project, you create a menu item that displays a custom task pane. The custom task pane contains controls to help the user fill out a form.

Bb968857.note(en-us,office.12).gifNote:

InfoPath 2007 does not include the Office Fluent Ribbon, so your control choices are a menu item or a toolbar button.

To add a menu

  1. In Solution Explorer, right-click the ThisAddIn.vb node, and then click View Code.

  2. Add the following declarations to the code window underneath the public class ThisAddIn statement.

    Private mainMenuBar As Office.CommandBar
    Private helpMenuIndex As Object
    Private vstoAddInMenu As Office.CommandBarPopup
    Private contactFormMenuItem As Office.CommandBarButton
    Private menuAdded As Boolean = False
    
    
  3. Add the following method to your code.

    This code creates the VSTO Add-ins menu with a Customer contact form menu item.

    Private Sub AddMenu()
        ' Get a reference to the Outlook main menu bar.
        mainMenuBar = CType(Me.Application.ActiveWindow.CommandBars, _
            Office.CommandBars).ActiveMenuBar
        ' Locate the Help menu.
        Try
            helpMenuIndex = mainMenuBar.Controls("Help").Index
        Catch
            helpMenuIndex = mainMenuBar.Controls.Count
        End Try
        ' Create a VSTO Add-Ins menu to the left of the Help menu.
        vstoAddInMenu = CType(mainMenuBar.Controls.Add( _
            Office.MsoControlType.msoControlPopup, _
            Type.Missing, Type.Missing, helpMenuIndex, True), _
            Office.CommandBarPopup)
        vstoAddInMenu.Caption = "VSTO Add-ins"
        vstoAddInMenu.Visible = True
    
        ' Create a menu item in the VSTO Add-Ins menu.
        contactFormMenuItem = CType(vstoAddInMenu.Controls.Add( _
            Office.MsoControlType.msoControlButton, _
            Type.Missing, Type.Missing, 1, 1), Office.CommandBarButton)
        contactFormMenuItem.Style = _
            Microsoft.Office.Core.MsoButtonStyle.msoButtonCaption
        contactFormMenuItem.Caption = "Customer contact form"
        AddHandler contactFormMenuItem.Click, _
            AddressOf ContactFormMenuItem_Click
    
    menuAdded = True
    
    End Sub
    
    
  4. Add the following method to your code.

    This code adds a custom task pane to the active window when the user selects the menu item.

    Private Sub ContactFormMenuItem_Click( _
        ByVal ctrl As Office.CommandBarButton, _
        ByRef CancelDefault As Boolean)
    
    End Sub
    
    

    To build an add-in for Microsoft Office Word 2007 or Microsoft Office Excel 2007, you might call the AddMenu method from the Startup event handler, and then add the menu when the add-in loads. You cannot do this in InfoPath 2007. Although you can get a reference to the Application object, you cannot use its properties or methods until a form has been loaded.

    You can use the NewXDocument and XDocumentOpen events to detect when a form is loaded. These events are provided by the ApplicationEvents class in the InfoPath namespace. However, to access these events, you must take some intermediate steps.

  5. Add the following declarations.

    Private WithEvents appevents As InfoPath.ApplicationEvents
    Private app3 As InfoPath._Application3
    
    
  6. Add the following code to the Startup method. This code adds the toolbar to InfoPath 2007 when the add-in loads.

    ' Cast from Application to _Application3.
    app3 = CType(Me.Application, InfoPath._Application3)
    ' Get the events source object.
    appevents = CType(app3.Events, InfoPath.ApplicationEvents)
    
    
  7. Add the following methods to handle the NewXDocument and XDocumentOpen events. If the menu has not been added already, open an existing form or create a new form to add the menu.

    Private Sub appevents_NewXDocument( _
      ByVal pDocument As InfoPath._XDocument) _
      Handles appevents.NewXDocument
        If Not menuAdded Then AddMenu()
    End Sub
    
    Private Sub appevents_XDocumentOpen( _
      ByVal pDocument As InfoPath._XDocument) _
      Handles appevents.XDocumentOpen
        If Not menuAdded Then AddMenu()
    End Sub
    
    
  8. On the Build menu, click Build Solution and verify that the project compiles correctly with no errors. Press F5 to run the application.

    When InfoPath 2007 starts, typically you see the Getting Started dialog box. The VSTO Add-ins menu should not appear at this time.

  9. Open the Customer Contact Report form. Now you should see the VSTO Add-ins menu.

Creating a Custom Task Pane

Custom task panes are a powerful way to provide context-sensitive user interface (UI) assistance. Custom task panes contain a user control, which you can create in either Microsoft Visual Basic or Microsoft Visual C#. This enables you to reuse existing UI elements, code, and techniques. Creating custom task panes is covered in more detail in Creating Custom Task Panes Using Visual Studio 2005 Tools for the Office System SE.

The custom task pane in this add-in enables the user to add the user's name to the Customer Contact Report form, to select a date from a calendar and add that to the form, and to select a customer and add that customer’s information to the form.

Bb968857.note(en-us,office.12).gifNote:

This procedure uses SQL Server 2005 Express Edition and the Northwind sample database. You can also use SQL Server 2005. You can download this sample database from the SQL Server 2005 Samples and Sample Databases.

To add a data source and create a dataset

  1. On the Project menu, click Add New Item.

  2. Select Dataset in the list of Templates. Type NorthwindDataset in the Name box, and then click Add. The Dataset Designer appears.

  3. On the Data menu, point to Add, and then click TableAdapter. The TableAdapter Configuration Wizard is displayed.

  4. In the Choose Your Data Connection page, create or select a connection to the Northwind database. Click Next.

    Bb968857.note(en-us,office.12).gifNote:

    For more detailed information about how to do this, see Creating Custom Task Panes Using Visual Studio 2005 Tools for the Office System SE.

  5. On the Save the Connection String page, click Next.

  6. On the Choose a Command Type page, select Use SQL Statements, and then click Next. Type the following on the Enter a SQL Statement page.

    
    Select CustomerID, CompanyName From Customers
    
    
  7. Click Advanced Options. The user can select a customer from this list but cannot make changes. Clear the Generate Insert, Update, and Delete statements check box, click OK, and then click Next.

  8. On the Choose Methods to Generate page, clear Create methods to send updates directly to the database check box. Click Finish.

  9. After the table adapter is created, change the name of the adapter in the Properties pane to Customers.

You want to add another table adapter to the dataset.

To add another table adapter to the dataset

  1. Add another table adapter to the dataset using the same technique as in the previous steps. Use the following SQL statement.

    
    SELECT CompanyName, ContactName, ContactTitle, Address, City, 
      Region, PostalCode, Country, Phone, Fax
    FROM Customers
    WHERE (CustomerID = @customerID)
    
    
  2. After the table adapter is created, change the name of the adapter in the Properties pane to Customer.

  3. Close the Dataset Designer.

Next, you create the user control that is displayed to the user in the custom task pane.

To create a user control for the custom task pane

  1. On the Project menu, click Add New Item.

  2. In the Add New Item dialog box, select User Control from the list of templates. Type ContactFormControl in the Name box, and then click Add. In the Properties pane, set the Size property to 265, 840.

  3. From the Toolbox, in the Containers tab, drag a Panel to the top of the user control.

  4. From the Common Components tab, drag a Button onto the panel. Name the button InsertNameButton and set the Text property of the button to Insert my name.

  5. Add a Panel, a MonthCalendar control, and a Button to the middle of the form. Leave the default name of the calendar control as MonthCalendar1. Name the button InsertDateButton, and set the Text property to Insert date.

  6. Add a Panel to the bottom of the form.

    In Solution Explorer, click the Data Sources tab, and drag the Customers table from the Data Sources pane onto the form inside the panel. This creates a DataGridView control that is bound to the Customers table.

  7. Right-click the DataGridView and select Edit Columns. Remove the CustomerID column, and set the HeaderText of the CompanyName column to Customers. Adjust the Width property so that the column fills the grid.

  8. Add a button below the data grid. Name the button InsertCustomerButton, and set the Text property to Insert customer info.

  9. Adjust the width of the panels and controls until the user control looks like Figure 3.

    Figure 3. The custom task pane for the add-in

    The custom task pane for the add-in

When the user selects the Customer contact form menu item, the custom task pane appears. If the custom task pane is already visible, selecting this menu item hides it.

To display the custom task pane

  1. Click the Solution Explorer tab, and in the ThisAddIn.vb code window, add the following declarations.

    Private ctpContactForm As Microsoft.Office.Tools.CustomTaskPane
    Public showTaskPane As Boolean = False
    
    
  2. Add the following code to the ContactFormMenuItem_Click method.

    showTaskPane = Not showTaskPane
    If showTaskPane Then
        ' Add the customer contact task pane to the open document.
        ctpContactForm = Me.CustomTaskPanes.Add( _
            New ContactFormControl(), "Customer Contact Form", _
            Me.Application.ActiveWindow)
    
        ' The default width is 206. That is not enough 
        ' to display all of the controls.
        ctpContactForm.Width = 275
    
        ' Display the custom task pane.
        ctpContactForm.Visible = True
    Else
        ' Remove the customer contact task pane from the open document.
        Me.CustomTaskPanes.Remove(ctpContactForm)
    End If
    
    

    This code creates a new custom task pane and adds it to the collection of custom task panes that belong to this add-in. The first two arguments of the Add method specify the control to add to the custom task pane and the title to display on the task pane. The third argument, which is optional, specifies the parent window for the custom task pane.

  3. Add the following code to the Shutdown event handler.

    ' Remove the customer contact task pane from the open document.
    Me.CustomTaskPanes.Remove(ctpContactForm)
    
    
  4. In Solution Explorer, double-click the ContactFormControl.vb node, click View Code, and then add the following Load event handler to the class.

    Private Sub CustomersControl_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       ' Retrieve customer information from the database.
       Me.CustomersTableAdapter.Fill(Me.NorthwindDataset.Customers)
    End Sub
    
    

    This code fills the data grid with data from the Customers table.

  5. On the Build menu, click Build Solution and verify that the project compiles correctly with no errors.

  6. Press F5 to run the application.

  7. Open the Customer Contact Report form.

  8. On the VSTO Add-ins menu, click Customer contact form.

    The custom task pane is displayed, and the data grid shows a list of customers.

  9. On the VSTO Add-ins menu, click Customer contact form.

    The custom task pane is hidden.

Working with XML in an InfoPath Form

To read or write to the XML in a form, you use the classes in the Microsoft.Office.Interop.InfoPath.Xml namespace. The Microsoft.Office.Interop.InfoPath.Xml.dll file is the InfoPath primary interop assembly and is installed by default when you install InfoPath. The classes and interfaces in this namespace enable managed code to interoperate with the Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office COM server.

Bb968857.note(en-us,office.12).gifNote:

If you use Visual Studio Tools for Applications to write customizations for InfoPath 2007, you can use the System.Xml namespace to work with the XML in a form. However, external applications, such as add-ins written with Visual Studio 2005 Tools for Microsoft Office, use MSXML.

Before you can work with the XML in an InfoPath form, you must know the structure of the XML. If you designed the XML first, and then built the form by using that XML, you already know the structure. If you designed the form first, InfoPath created a structure for you.

An InfoPath XSN file is actually a compressed CAB file that consists of a number of files. You can extract these files and view the XML that the form uses.

To view the XML schema used in an InfoPath form

  1. With the Customer Contact Report form displayed, on the Tools menu, click Design This Form.

  2. On the File menu, click Save As Source Files. Select a folder and click OK. Remember the location of this folder because you use it later in this procedure.

  3. Close InfoPath.

The source files that make up this Customer Contact Report form are described in Table 1 and shown in Figure 4.

Table 1. Source files for the Customer Contact Report form

Source file Description

myschema.xsd

Contains the XML schema used by the form.

template.xml

Contains a list of the fields used in the form.

view1.xsl

Contains the instructions InfoPath uses to display the form at run time.

sampledata.xsl

Contains sample data for the form.

On the View menu, click Sample Data. InfoPath generates sample data and fills in the form.

manifest.xsf

Contains pointers to the files listed previously. InfoPath uses this file to locate the elements that make up the form at run time.

Figure 4. Source files for the Customer Contact Report form

Source files for the Customer Contact Report form

The important part of this procedure is viewing the XML schema. When you use the classes in the InfoPath.Xml namespace, you must know certain elements in this schema, including the names of the fields and the XML namespaces. The following is the first part of the XML schema for the Customer Contact Report form.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema targetNamespace="http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-02-21T00:06:55" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-02-21T00:06:55" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="myFields">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="my:CustomerRep" minOccurs="0"/>
        <xsd:element ref="my:ContactDate" minOccurs="0"/>
        <xsd:element ref="my:CompanyName" minOccurs="0"/>
        <xsd:element ref="my:ContactName" minOccurs="0"/>
        <xsd:element ref="my:ContactTitle" minOccurs="0"/>
        <xsd:element ref="my:Phone" minOccurs="0"/>
        <xsd:element ref="my:Fax" minOccurs="0"/>
        <xsd:element ref="my:Address" minOccurs="0"/>
        <xsd:element ref="my:City" minOccurs="0"/>
        <xsd:element ref="my:Region" minOccurs="0"/>
        <xsd:element ref="my:PostalCode" minOccurs="0"/>
        <xsd:element ref="my:Country" minOccurs="0"/>
        <xsd:element ref="my:Notes" minOccurs="0"/>
      </xsd:sequence>
      <xsd:anyAttribute processContents="lax" 
        namespace="http://www.w3.org/XML/1998/namespace"/>
    </xsd:complexType>
</xsd:element>

You are now ready to write code to insert data into the form, based on selections that the user makes in the custom task pane.

First you must add a project reference to the Microsoft.Office.Interop.InfoPath.Xml primary interop assembly. When you install InfoPath, this assembly is added to the global assembly cache. However, the file itself resides in the Microsoft Office installation folder. Visual Studio does not search in this folder by default, and therefore, this assembly does not appear in the .NET tab of the Add Reference dialog box. To add the reference, you must manually locate the file.

To modify the XML in an InfoPath form

  1. In Visual Studio, on the Project menu, click Add Reference.

  2. In the Add Reference dialog box, click the Browse tab.

  3. Navigate to the Office installation folder, which by default is Program Files\Microsoft Office\Office 12.

  4. Select the Microsoft.Office.Interop.InfoPath.Xml.dll file. Click OK to add the reference.

  5. Open the code file for the ContactFormControl user control.

  6. Add the following declarations.

    Private doc As InfoPath.XDocument = _
        Globals.ThisAddIn.Application.ActiveWindow.XDocument
    Private domDoc As InfoPath.Xml.IXMLDOMDocument3
    Private docNode As InfoPath.Xml.IXMLDOMNode
    
    

    The variable doc contains a reference to the form’s underlying XML data. The variable domDoc represents an MSXML IXMLDOMDocument3 object, and the variable docNode represents an MSXML IXMLDOMNode object.

  7. Add the following code to the Load event handler for the user control to get a reference to the DOM for the XML.

    domDoc = CType(doc.DOM, InfoPath.Xml.IXMLDOMDocument3)
    
    
  8. You use XPath queries to locate the XML associated with the various fields in the form. Add the following code to specify the XMLNamespace declaration to use in the XPath expressions.

    domDoc.setProperty("SelectionNamespaces", _
        "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " & _
        "xmlns:xhtml='http://www.w3.org/1999/xhtml' " & _
        "xmlns:my='http://schemas.microsoft.com/office/" & _
        "infopath/2003/myXSD/2007-02-21T00:06:55' " & _
        "xmlns:xd='http://schemas.microsoft.com/office/infopath/2003'")
    
    

Next, you want to insert the user's name into the form.

To insert the user's name into the form

  1. In Solution Explorer, right-click ContactFormControl.vb, and then click View Designer.

  2. Double-click the Insert my name button to create the Click event handler.

  3. Add the following code to the Click event handler of the Insert my name button to insert the user’s name into the form.

    docNode = domDoc.selectSingleNode("//my:CustomerRep")
    docNode.text = System.Environment.UserName
    
    

    This code uses an XPath query to find the CustomerRep element in the form’s XML. Change the text property of the resulting node to modify the data in the XML and update the value displayed in the form.

    Notice the use of the my prefix. For this query to return the expected results, the SelectionNamespaces property must be set correctly to ensure that the namespaces you use match the namespaces used by InfoPath.

  4. Locate the folder where you saved the source files of the Customer Contact Report form, and open the myschema.xsd file.

  5. Copy the namespace statement starting with "xmlns:my=".

  6. Replace the "xmlns:my=" statement that you previously pasted into the Load event handler with the namespace statement you just copied.

  7. On the Build menu, click Build Solution and verify that the project compiles correctly with no errors. Press F5 to run the application.

  8. Open the Customer Contact Report form.

  9. On the VSTO Add-ins menu, click Customer contact form, and then click Insert my name.

    Your name appears in the Customer Service Representative text box in the form. Close InfoPath.

You want to insert a specific date, instead of displaying the current date by default.

To insert a specific date

  1. On the ContactFormControl designer, double-click the Insert date button to create the Click event handler.

  2. Add the following code to the Click event handler of the Insert date button to insert the calendar’s selected date into the form. The form displays the current date by default, but the user can override this.

    docNode = _
        domDoc.selectSingleNode("//my:ContactDate")
        docNode.text = MonthCalendar1.SelectionStart.ToString("yyyy-MM-dd")
    
    
  3. Add the following declarations.

    Private customersRow As NorthwindDataset.CustomersRow
    Private customerRow As NorthwindDataset.CustomerRow
    Private customerTA As New _
        NorthwindDatasetTableAdapters.CustomerTableAdapter
    
    

You want to add code to the Click event handler so that you can get a reference to a selected customer's data.

To insert the customer's data

  1. Add the following code to the Click event handler of the Insert customer info button to get a reference to the selected customer’s data.

    customersRow = CType(CType( _
        Me.CustomersBindingSource.Current, DataRowView).Row, _
        NorthwindDataset.CustomersRow)
    
    
  2. Add the following code to retrieve the information for the selected customer.

    Dim customerTable As New NorthwindDataset.CustomerDataTable
    customerTable = customerTA.GetData(customersRow.CustomerID)
    customerRow = CType(customerTable.Rows(0), _
        NorthwindDataset.CustomerRow)
    
    
  3. Add the following code to add the company name to the form.

    docNode = domDoc.selectSingleNode("//my:CompanyName")
    docNode.text = customerRow.CompanyName
    
    
  4. Add the following code to add the rest of the customer information to the form. This code first checks to see whether there is information in each column. If so, the information is retrieved and added to the appropriate text box on the form.

    ' Add the contact name if it is not null.
    If Not customerRow.IsContactNameNull() Then
        docNode = domDoc.selectSingleNode("//my:ContactName")
        docNode.text = customerRow.ContactName
    End If
    ' Add the contact title if it is not null.
    If Not customerRow.IsContactTitleNull() Then
        docNode = domDoc.selectSingleNode("//my:ContactTitle")
        docNode.text = customerRow.ContactTitle
    End If
    ' Add the phone number if it is not null.
    If Not customerRow.IsPhoneNull() Then
        docNode = domDoc.selectSingleNode("//my:Phone")
        docNode.text = customerRow.Phone
    End If
    ' Add the fax number if it is not null.
    If Not customerRow.IsFaxNull() Then
        docNode = domDoc.selectSingleNode("//my:Fax")
        docNode.text = customerRow.Fax
    End If
    ' Add the address if it is not null.
    If Not customerRow.IsAddressNull()Then
        docNode = domDoc.selectSingleNode("//my:Address")
        docNode.text = customerRow.Address
    End If
    ' Add the city if it is not null.
    If Not customerRow.IsCityNull()Then
        docNode = domDoc.selectSingleNode("//my:City")
        docNode.text = customerRow.City
    End If
    ' Add the region if it is not null.
    If Not customerRow.Is_RegionNull()Then
        docNode = domDoc.selectSingleNode("//my:Region")
        docNode.text = customerRow._Region
    End If
    ' Add the postal code if it is not null.
    If Not customerRow.IsPostalCodeNull()Then
        docNode = domDoc.selectSingleNode("//my:PostalCode")
        docNode.text = customerRow.PostalCode
    End If
    ' Add the country if it is not null.
    If Not customerRow.IsCountryNull()Then
        docNode = domDoc.selectSingleNode("//my:Country")
        docNode.text = customerRow.Country
    End If
    
    

Finally, you want to compile and run the application.

To compile and run the application

  1. On the Build menu, click Build Solution and verify that the project compiles correctly.

  2. Press F5 to run the application.

  3. Open the Customer Contact Report form.

  4. On the VSTO Add-ins menu, click Customer contact form.

  5. Click Insert my name.

    Your name appears in the Customer Service Representative text box in the form.

  6. Select a date in the calendar, and click Insert date.

    The date appears in the Date of Customer Contact text box in the form.

  7. Select a customer, and click Insert customer info.

    The customer information is displayed in the appropriate text boxes in the form, as shown in Figure 5.

  8. Close InfoPath.

    Figure 5. Completed Customer Contact Report form

    Completed Customer Contact Report form

Conclusion

To automate InfoPath 2007 from an external application, you use the classes and interfaces in the Microsoft.Office.Interop.InfoPath and Microsoft.Office.Interop.InfoPath.Xml namespaces. An add-in built with Visual Studio Tools for Office is considered an external application, and so you use these namespaces to work with an InfoPath form and its underlying XML. After you are familiar with these namespaces and the InfoPath object model, creating an InfoPath add-in is straightforward and uses familiar code and techniques.

Additional Resources

This section lists a number of resources you can use to learn more about the products and technologies that are mentioned or used in this article.

About the Author

Robert Green is a developer, writer, and trainer, and is a senior consultant with MCW Technologies. Robert is a co-author of AppDev's Visual Basic, Visual C#, and Windows Workflow Foundation courseware. Prior to joining MCW, Robert worked at Microsoft and was the Visual Studio Tools for Office Product Manager.

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.