Chapter 15. Forms Services and InfoPath

Exposing forms to the browser empowers users to leverage one of SharePoint's advanced features. Creating simple forms is easy, even for end users. However, creating more complex forms requires higher-level knowledge. This chapter shows how to build and extend a basic form within InfoPath using code, deploy this to a SharePoint server, and make the form available online. Different ways of deploying InfoPath form templates and integrating forms into complex solutions will be described. Taking it further, you will see how to program InfoPath forms and how to add custom code to forms.

These form templates can be published to a SharePoint server, which can render them in a web browser using InfoPath Forms Services. This enables users without an InfoPath client installed on their computers to fill out InfoPath forms.

XmlFormView is a Web Part used to render InfoPath forms in SharePoint and make the form available in the browser. Programming the control extends its behavior and provides enhanced features usually available only to InfoPath clients. In this chapter we explain how to overcome common limitations of the form viewer.

InfoPath uses XML to store user input. With programmatic access to the XML, changes are possible on the fly during the loading and saving processes. Combined with workflows, which are described in the next chapter, this creates powerful applications and makes complex form management possible.

This chapter includes

  • How InfoPath files are structured

  • How to design browser-enabled forms

  • Using data connections to access external data

  • Publishing forms to SharePoint and making the forms available in a browser

  • Building InfoPath forms with code-behind

  • Creating applications with XmlFormView and extending its default behavior

Internals of InfoPath Forms

Using line-of-business (LOB) applications on browser-based platforms is a solution in high demand, with many advantages for the enterprise. Often one of the core challenges is to provide users with easy-to-use forms. In many cases, such forms must adhere to corporate design stipulations, and their textual information needs to be adjusted regularly.

SharePoint and InfoPath complement one another and offer a solution to many of these issues. InfoPath provides a very intuitive UI for developing form templates, enabling information workers and even business users to develop and customize forms.

Designing solutions for SharePoint in combination with InfoPath Forms Services requires developers to be familiar with InfoPath. This includes a basic understanding of the internal structure of forms, as well as designing form templates using InfoPath. Since many of the wizards integrated into InfoPath are aimed at ad hoc solutions and lack support for professional development solutions, we will examine the internal structure and functionality of InfoPath form templates.

InfoPath separates layout and data. On one hand, an InfoPath form template describes the layout and behavior of the form. This information is stored within a template file with the extension .xsn. On the other hand, the data that is entered by a user into the form's controls is stored in an XML data file. This XML file contains a reference to the corresponding XSN file that is used to display the data. When discussing an InfoPath form, we are generally referring to the form template.

InfoPath Form Template

Despite the attractive InfoPath UI, developers need to understand the internal structure of InfoPath form templates. The XSN file, created by InfoPath when designing a form template, is essentially a Windows Cabinet Archive (.cab) file containing several different files. You can see those files when you use the option Share

InfoPath Form Template
Structure of InfoPath files

Figure 15.1. Structure of InfoPath files

We will describe the constituent files within an InfoPath form template in more detail. The listings and snippets in this chapter are taken from an example form template called Conference Room Booking. Figure 15-2 shows a form that is used to book conference rooms within a company. Users can enter their names and contact information and reserve a room for a specified date and time period. The form consists of two different views: one for editing the form, and another, marked as read-only, that will be displayed after the document has been submitted.

Example form template: Conference Room Booking

Figure 15.2. Example form template: Conference Room Booking

Form Definition Files

InfoPath stores all the relevant information about a form template in the form definition file, called manifest.xsf. This file is the core file of an InfoPath template and holds information about the document schema, views, business logic, event handlers, form metadata, and deployment information.

When viewing the XML structure of this file in a text editor, you will find many elements that hold information you have entered in InfoPath Designer. Listing 15-1 shows a complete XSF file for the Conference Room Booking example form. Some of the subelements have been omitted to increase readability.

Example 15.1. Sample XSF File

<?xml version="1.0" encoding="UTF-8"?>
<xsf:xDocumentClass trustSetting="automatic"
                    trustLevel="restricted"
                    solutionFormatVersion="3.0.0.0"
                    solutionVersion="1.0.0.16" productVersion="14.0.0"
                    publishUrl="C:FormsEquipmentRequest.xsn"
                    name="urn:schemas-microsoft-com:office:infopath:
                          EquipmentRequest:-myXSD-2009-09-22T18-21-06"
                    xmlns:xsf="http://schemas.microsoft.com/office/
                               infopath/2003/solutionDefinition"... >
    <xsf:package>
        <xsf:files>
            <xsf:file name="myschema.xsd">
               <xsf:property name="namespace" type="string"
                    value="http://schemas.microsoft.com/office/
infoapth/2003/myXSD/2010_01_20T22:54:17"> </xsf:property>
               <xsf:property name="editability" type="string" value="full">
               </xsf:property>
               <xsf:property name="rootElement" type="string" value="RoomBooking">
               </xsf:property>
               <xsf:property name="useOnDemandAlgorithm" type="string" value="yes">
               </xsf:property>
            </xsf:file>
            <xsf:file name="template.xml"></xsf:file>
            <xsf:file name="sampledata.xml">...</xsf:file>
           <xsf:file name="view1.xsl">...</xsf:file>
           <xsf:file name="view2.xsl">...</xsf:file>
           <xsf:file name="upgrade.xsl"></xsf:file>
      </xsf:files>
     </xsf:package>
    <xsf:importParameters enabled="yes"></xsf:importParameters>
    <xsf:documentVersionUpgrade>
        <xsf:useTransform transform="upgrade.xsl" minVersionToUpgrade="0.0.0.0"
                          maxVersionToUpgrade="1.0.0.15"></xsf:useTransform>
    </xsf:documentVersionUpgrade>
    <xsf:extensions>
        <xsf:extension name="SolutionDefinitionExtensions">
            <xsf2:solutionDefinition runtimeCompatibility="client server"
                                     allowClientOnlyCode="no">
                <xsf2:offline openIfQueryFails="yes" cacheQueries="yes">
                </xsf2:offline>
                <xsf2:server isPreSubmitPostBackEnabled="no"
                             isMobileEnabled="no" formLocale="en-US">
               </xsf2:server>
                <xsf2:solutionPropertiesExtension branch="share">
                    <xsf2:share formName="test"
                                path="C:UsersAdministratorDocuments	est.xsn"
                                accessPath="">
                    </xsf2:share>
                </xsf2:solutionPropertiesExtension>
               <xsf2:viewsExtension>
                   <xsf2:viewExtension ref="view2" readOnly="yes" clientOnly="no">
                   </xsf2:viewExtension>
               </xsf2:viewsExtension>
            </xsf2:solutionDefinition>
        </xsf:extension>
    </xsf:extensions>
    <xsf:views default="View 1">
        <xsf:view showMenuItem="yes" name=" View 1" caption=" View 1">
        ...
        </xsf:view>
        <xsf:view showMenuItem="yes" name="Readonly" caption="Readonly">
        ...
        </xsf:view>
    </xsf:views>
    <xsf:applicationParameters application="InfoPath Design Mode">
        <xsf:solutionProperties fullyEditableNamespace="http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-22T18:21:06" lastOpenView="view1.xsl" lastVersionNeedingTransform="1.0.0.15"></xsf:solutionProperties>
</xsf:applicationParameters>
    <xsf:documentSchemas>
        <xsf:documentSchema rootSchema="yes" location="http://schemas.microsoft.com/office/infopath /2003/myXSD/2009-09-22T18:21:06 myschema.xsd"></xsf:documentSchema>
    </xsf:documentSchemas>
    <xsf:fileNew>
        <xsf:initialXmlDocument caption="EquipmentRequest" href="template.xml">
        </xsf:initialXmlDocument>
    </xsf:fileNew>
    <xsf:submit caption="Submit" disableMenuItem="no" onAfterSubmit="close" showStatusDialog="no">
        <xsf:submitToHostAdapter name="Main submit" submitAllowed="yes">
        </xsf:submitToHostAdapter>
        <xsf:errorMessage>The form cannot be submitted because of an error.</xsf:errorMessage>
    </xsf:submit>
    <xsf:ruleSets>
        <xsf:ruleSet name="ruleSet_1">
            <xsf:rule caption="Send" isEnabled="yes">
                <xsf:assignmentAction targetField="my:readonly" expression="&quot;true&quot;">
                </xsf:assignmentAction>
                <xsf:submitAction adapter="Main submit"></xsf:submitAction>
                <xsf:closeDocumentAction promptToSaveChanges="no"></xsf:closeDocumentAction>
            </xsf:rule>
        </xsf:ruleSet>
    </xsf:ruleSets>
</xsf:xDocumentClass>

You can find the following important information in the manifest file:

  • Unique identifier for the form: This identifier is also used within SharePoint to reference the form template. It is provided using the name attribute of the root element <xsf:xDocumentClass>.

  • Global metadata about the form: The root element <xsf:xDocumentClass> also contains information about document versions, publishing, trust settings, and definitions for the various namespaces that are used within the manifest.

  • Packaging of the XSN file: The <xsf:package> element lists all the files that are included in the cabinet file using <xsf:files> elements.

  • XML Schema definition of form data: Within the <xsf:files> section you can see the <xsf:file> element that references the schema XSD file. It contains several <xsf:property> elements, which define the name of the rootElement and whether the schema can be edited. The exact properties that can be specified vary depending on the file type. Later in the manifest file, the element <xsf:documentSchemas> contains a reference to the document schema used in the form.

  • Definition of the different views within the form: The <xsf:views> element contains a child <xsf:view> element for each view. Each view element defines the Etensible Stylesheet Language Transformation (XSLT) that is used to display the view. Furthermore, editing components are defined within the <xsf:editing> tag. Editing controls are special controls that handle user editing of the nominated data field. In the following example (in Listing 15-2), a calendar control for editing the date field and a control for multiline data are defined. The <xsf:unboundControls> element describes additional controls that are not bound to the XML data, such as Button controls.

    Example 15.2. Definition of Views in XSF

    <xsf:view showMenuItem="yes" name="View1" caption="Edit View">
        <xsf:mainpane transform="view2.xsl"></xsf:mainpane>
        <xsf:editing>
            <xsf:xmlToEdit name="Date_7" item="/my:RoomBooking/my:Date">
                <xsf:editWith proofing="no" autoComplete="no" component="xField"></xsf:editWith>
            </xsf:xmlToEdit>
            <xsf:xmlToEdit name="Comment_15" item="/my:ConferenceBooking/my:Comment">
                <xsf:editWith type="plainMultiline" component="xField"></xsf:editWith>
            </xsf:xmlToEdit>
        </xsf:editing>
        <xsf:unboundControls>
            <xsf:button name="CTRL18_6">
                <xsf:ruleSetAction ruleSet="ruleSet_1"></xsf:ruleSetAction>
            </xsf:button>
        </xsf:unboundControls>
    </xsf:view>
  • Actions and rules: These are defined within the <xsf:ruleSets> element as described in Listing 15-3. They define how the rules are bound to controls and what actions are taken. In the following example, a rule is defined that sets the my:readonly field to true, submits the form using the Main submit data source, and closes the document.

    Example 15.3. Definition of Rules in XSF

    <xsf:ruleSet name="ruleSet_1">
        <xsf:rule caption="Send" isEnabled="yes">
            <xsf:assignmentAction targetField="my:readonly"
                                  expression="&quot;true&quot;">
            </xsf:assignmentAction>
            <xsf:submitAction adapter="Main submit"></xsf:submitAction>
            <xsf:closeDocumentAction promptToSaveChanges="no"></xsf:closeDocumentAction>
        </xsf:rule>
    </xsf:ruleSet>
  • Data validation: In the section <xsf:CustomValidation>, all custom validation rules are expressed using <xsf:ErrorCondition> elements as shown in Listing 15-4. These describe the fields that are validated using the match attribute and the expression to be evaluated. The subelement <xsf:errorMessage> contains the shortMessage that will be displayed if validation fails.

    Example 15.4. Validation Rules in XSF

    <xsf:customValidation>
        <xsf:errorCondition match="/my:RoomBooking"/my:Schedule/my:Date"
                            expressionContext="."
                            Expression="msxsl:string-compare(.,xdDate:Today()) &lt; 0">
            <xsf:errorMessage type="modeless" shortMessage="Date must be in the future">
            </xsf:errorMessage>
            <?caption Validate Date?>
        </xsf:errorCondition>
    ...
    </xsf:customValidation>

Form Schema File (XSD)

Every form template has a schema file (.xsd) that prescribes the data structure expected by this form template. The schema file is expressed in XML Schema Definition (XSD), as defined by the W3C organization.

InfoPath validates every XML file to be rendered by the specified form template against this schema. This makes designing the schema very important, especially when the XML data files are manipulated outside of the InfoPath and Forms Services environments. If the XML is invalid according to the schema, the form cannot be displayed.

Warning

InfoPath does not support all features of XSD! Please check out the MSDN library for a list of XML schema elements that are not supported by InfoPath: http://msdn.microsoft.com/en-us/library/bb251017.aspx.

Listing 15-5 shows the schema file from the Conference Room Booking example. The second line contains a very important definition: the target namespace. This is the namespace to which all the elements and attributes belong. During validation of XML data files, InfoPath verifies that all the elements and attributes in the XML instance exist within the declared namespace.

In the example form data file (in Listing 15-8), you will see that the namespace declaration for the namespace my is exactly the targetNamespace of the schema. The other namespaces used in the schema define the XML schema namespace that contains all schema elements and some additional InfoPath schema extensions.

InfoPath uses element references to structure the schema. Starting at the root node, InfoPath creates complexType elements containing all elements at that node. Each element is described using element references pointing to elements, which are defined at the root element of the schema. This enhances readability of the schema and reusability of the elements.

Looking at the elements, you can see that InfoPath created some simpleType definitions, such as requiredString. This is used to implement the "Cannot be blank" check box in the field properties dialog in InfoPath Editor. This string extends the basic string format of XML Schema using a restriction, saying that the element has a minimum length of 1. You need to understand the difference between this and the minOccurs attribute used in the element descriptions. minOccurs tells the XML parser how often an element may be present in the XML. If you define the FirstName element with minOccurs=1, you are only specifying that this XML element is mandatory. However, the value of the element could still be empty.

Another important related attribute is the nillable attribute. This is usually used for date and time fields, as it allows an element to set the attribute nillable=true. Because a date element always requires the content to be a valid date, this is the only way to create empty date fields. Otherwise, if you entered an empty string into the date element, the validation of the XML would fail. An empty date can thus be created in the XML as <my:Date nil='true'></my:Date>.

Example 15.5. Example Schema

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xsd:schema targetNamespace="http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-29T22:54:17" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-29T22:54:17" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="RoomBooking">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="my:UserInformation" minOccurs="0"/>
                <xsd:element ref="my:Schedule" minOccurs="0"/>
                <xsd:element ref="my:Hardware" minOccurs="0"/>
                <xsd:element ref="my:Catering" minOccurs="0"/>
                <xsd:element ref="my:Comments" minOccurs="0"/>
                <xsd:element ref="my:readonly" minOccurs="0"/>
            </xsd:sequence>
            <xsd:anyAttribute processContents="lax"
                              namespace="http://www.w3.org/XML/1998/namespace"/>
        </xsd:complexType>
    </xsd:element>

    <xsd:element name="UserInformation">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="my:FirstName" minOccurs="0"/>
                <xsd:element ref="my:LastName" minOccurs="0"/>
                <xsd:element ref="my:Email" minOccurs="0"/>
                <xsd:element ref="my:Telephone" minOccurs="0"/>
            </xsd:sequence>
        </xsd:complexType>
</xsd:element>
    <xsd:element name="FirstName" type="my:requiredString"/>
    <xsd:element name="LastName" type="my:requiredString"/>
    <xsd:element name="Email" type="xsd:string"/>
    <xsd:element name="Telephone" type="xsd:string"/>

    <xsd:element name="Schedule">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="my:Room" minOccurs="0"/>
                <xsd:element ref="my:Date" minOccurs="0"/>
                <xsd:element ref="my:TimeBegin" minOccurs="0"/>
                <xsd:element ref="my:TimeEnd" minOccurs="0"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="Room" type="xsd:string"/>
    <xsd:element name="Date" nillable="true" type="xsd:date"/>
    <xsd:element name="TimeBegin" nillable="true" type="xsd:time"/>
    <xsd:element name="TimeEnd" type="xsd:string"/>

    <xsd:element name="Hardware">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element ref="my:DataProjector" minOccurs="0"/>
                <xsd:element ref="my:Microphone" minOccurs="0"/>
                <xsd:element ref="my:Notebook" minOccurs="0"/>
                <xsd:element ref="my:Speakers" minOccurs="0"/>
                <xsd:element ref="my:VideoConferencing" minOccurs="0"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="DataProjector" nillable="true" type="xsd:boolean"/>
    <xsd:element name="Microphone" nillable="true" type="xsd:boolean"/>
    <xsd:element name="Notebook" nillable="true" type="xsd:boolean"/>
    <xsd:element name="Speakers" nillable="true" type="xsd:boolean"/>
    <xsd:element name="VideoConferencing" nillable="true" type="xsd:boolean"/>

...

    <xsd:element name="readonly" nillable="true" type="xsd:boolean"/>

    <xsd:simpleType name="requiredString">
        <xsd:restriction base="xsd:string">
            <xsd:minLength value="1"/>
        </xsd:restriction>
    </xsd:simpleType>

    <xsd:simpleType name="requiredAnyURI">
        <xsd:restriction base="xsd:anyURI">
            <xsd:minLength value="1"/>
        </xsd:restriction>
    </xsd:simpleType>

    <xsd:simpleType name="requiredBase64Binary">
        <xsd:restriction base="xsd:base64Binary">
            <xsd:minLength value="1"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:schema>

Form Views (XSL)

Each view in the form template is defined by an XSL stylesheet file, which comprises all the relevant information for displaying the view. To render a view, the selected XML data file will be transformed into an HTML view via XSLT processing.

Listing 15-6 shows the body of such a view definition. For a clearer perspective, the HTML content, style definitions, and namespace definitions have been removed.

Example 15.6. Form View Definition in XSL

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:"...">
    <xsl:output method="html" indent="no"/>
    <xsl:template match="my:RoomBooking">
        <html>
            <head>
                <meta content="text/html" http-equiv="Content-Type"></meta>
                <style controlStyle="controlStyle">...</style>
                <style themeStyle="urn:office.microsoft.com:themeOffice">...</style>
                <style languageStyle="languageStyle">...</style>
            </head>
            <body style="BACKGROUND-COLOR: #ffffff; COLOR: #000000">
            ...
            </body>
        </html>
     </xsl:template>
</xsl:stylesheet>

The stylesheet defines one template rule that applies to the root element of the XSD schema. In the example you can see that the match attribute points to the RoomBooking node, which is the root element in our example. Within this template, HTML defines the display behavior. To insert the XML information from the data file, XSLT instructions are used within the template. The following snippet (in Listing 15-7) demonstrates how the drop-down list for the room is defined as a table element within the HTML layout. An XSLT select element is inserted, and the attributes value and selected are supplied from the XML data using XSLT instructions.

Example 15.7. XSLT Transformation in XSL File

<td class="xdTableComponent" style="PADDING-BOTTOM: 1px; VERTICAL-ALIGN: middle; PADDING-TOP: 1px">
    <div>
        <select class="xdComboBox xdBehavior_Select" title="" size="1" tabIndex="0" xd:xctname="dropdown" xd:CtrlId="CTRL19" xd:binding="my:Schedule/my:Room" xd:boundProp="value" style="WIDTH: 100%">
            <xsl:attribute name="value">
                <xsl:value-of select="my:Schedule/my:Room"/>
            </xsl:attribute>
            <option value="">
                <xsl:if test="my:Schedule/my:Room=&quot;&quot;">
                    <xsl:attribute name="selected">selected</xsl:attribute>
                </xsl:if>
            </option>
        </select>
    </div>
</td>

As you can see, the structure of XSL views is quite easy to follow and allows you to make changes to the layout or the XSL instructions. Nevertheless, manually editing views is very time consuming and requires you to deal with some Microsoft-specific schemas.

Form XML Template (XML)

Every form template contains two XML files: sampledata.xml and template.xml. The sampledata.xml file contains all the elements of the form with their default values, which were specified when the form was designed. The template.xml file represents an XML template that is used as a template for creating new documents. Although at first sight these files may not seem to be very useful, for developers this is not so. The template file, for example, can be used to create new document instances from custom code. If you wish to dynamically set default values for your forms, you can edit sampledata.xml from within your code.

The structure of the XML files is the same as the structure of form data files, described next.

InfoPath Form Data

The following snippet (see Listing 15-8) shows an example data file for the InfoPath form used in the Conference Room Booking example. In addition to the standard XML structure that complies with the preceding schema definition, InfoPath has added two special processing instructions. Within them are several attributes that define InfoPath metadata, such as version numbers. The most important attribute is the href attribute in the mso-infoPathSolution processing instruction. It links to the InfoPath form template—which is used to render the form—by specifying its location.

Example 15.8. Sample XML Data File

<?xml version="1.0" encoding="UTF-8"?>
<?mso-infoPathSolution solutionVersion="1.0.0.24" productVersion="14.0.0" PIVersion="1.0.0.0" href="file:///C:UsersAdministratorAppDataLocalMicrosoftInfoPathDesigner370314fc2849b4bbcmanifest.xsf" ?><?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.3"?>
<my:ConferenceBooking xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-22T18:21:06" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-us">
    <my:UserInformation>
        <my:FirstName>John</my:FirstName>
        <my:LastName>Smith</my:LastName>
        <my:Email>[email protected]</my:Email>
        <my:Telephone>01234567</my:Telephone>
    </my:UserInformation>
    <my:Schedule>
        <my:Room>Conference Room 1</my:Room>
        <my:RoomNumber>0001</my:RoomNumber>
        <my:Date>2009-12-31</my:Date>
        <my:TimeBegin>12:00:00</my:TimeBegin>
        <my:TimeEnd>14:00:00</my:TimeEnd>
    </my:Schedule>
    <my:Hardware>
        <my:DataProjector>true</my:DataProjector>
        <my:Microphone>false</my:Microphone>
        <my:Notebook>false</my:Notebook>
        <my:Speakers>false</my:Speakers>
        <my:VideoConferencing>true</my:VideoConferencing>
    </my:Hardware>
    <my:Catering>
        <my:Coffee>false</my:Coffee>
        <my:SoftDrinks>false</my:SoftDrinks>
        <my:Cookies>false</my:Cookies>
        <my:Snacks>false</my:Snacks>
    </my:Catering>
    <my:Comments>
        <my:Comment>Some additional comment</my:Comment>
    </my:Comments>
    <my:readonly>false</my:readonly>
</my:RoomBooking>

Designing Browser-Enabled Form Templates

Having examined the internal structure of InfoPath form templates, we will now take a closer look at the important steps in building form templates that can be used within SharePoint and Forms Services. Most of the wizards, dialogs, and property windows that can be used throughout these steps are identical in InfoPath 2007 and 2010. Many of the changes made to the InfoPath 2010 UI are concentrated in the reorganized menus on to the ribbon bars. You will find some properties that used to be hidden in cascaded dialogs are now directly available in the ribbon bars, which is a great improvement when designing larger forms.

InfoPath 2010 has been divided into two distinct programs: InfoPath Designer and InfoPath Filler. This separation reflects the two different usage scenarios and with it the two different roles for working with InfoPath. InfoPath Designer is targeted at those who create and design form templates. InfoPath Filler is the client application for filling out forms. The split makes it easier for users to understand InfoPath—in the past this difference was not made clear to new users of InfoPath.

Defining the Data Structure

When using forms in complex business solutions, the most important aspect is the design of your data schema. This is particularly so if you are using the schema throughout a business process where you access the XML contents using custom .NET code or property promotion and demotion in SharePoint lists. Schema design becomes even more complex if you plan to use your schema across different applications (e.g., when using BizTalk to process form data with the BizTalk mapping facilities).

There are two approaches to designing the schema:

  • Use the InfoPath client to generate and edit the schema during template design.

  • Define your schema first and create a form template based on this schema.

When you begin form creation by selecting a new blank form template, InfoPath will create the schema definition for you. This way you can simply add new controls to your views, or edit the schema in the Fields dialog (see Figure 15-3). Although your control over the schema that is produced is limited in this case, this scenario may be adequate for simple forms.

The Fields dialog

Figure 15.3. The Fields dialog

If you need full control over the XSD schema definition (e.g., when planning to use the XML across different applications), you should first build the XSD schema definition yourself and then create a new form template based on this schema. InfoPath provides a wizard to generate a new form by selecting the XML or Schema template. You merely choose your schema and start designing your form based on that schema.

When you design your own schema, you are able to use some advanced mechanisms of XML Schema, but you should keep in mind the following:

  • InfoPath does not support the entire XML Schema syntax.

  • If you build your form on an existing schema, you will not be able to change the field properties using the Fields dialog. Instead you will have to use the Data

    The Fields dialog
  • You can use data type restrictions in your schema to limit the allowed values in your form. Since InfoPath validates your XML input against the schema, you have only limited control of the errors that are presented to users when they input data that is invalid according to the schema.

  • For suitable user feedback, it may be better to validate input data using rules in InfoPath and displaying meaningful messages to the users.

  • Very strict schema definitions can prevent Forms Services from displaying your form at all, since invalid XML, according to the schema, will not be opened. This results in a very general "Form has been closed" message in the UI.

  • Overly restrictive data types in the schema make modifying "accepted input" more complex, especially if you intend that not only developers but also information workers should be able to make changes to the form design. For example, if your schema is defined to accept any string for user input, rules can be used to constrain the input to certain values. These rules can be changed by anyone capable of working with InfoPath, whereas a change to the schema would necessitate a complex development change scenario.

Overall, you should create your schema with care and weigh the pros and cons of very strict schemas. Use your schema to define the basic data structure but take care when using strong data type restrictions—you might end up spending a lot of time searching for the reason why your forms can't be displayed.

Designing the Form Templates

To lay out form templates, InfoPath uses different views. Only one view at a time will be displayed when the form is rendered, but users can switch between these views. This allows you to split large forms into different views, which makes it easier to work with the form. Furthermore, views can also be defined as read-only or designed with the sole purpose of printing. Read-only views in particular are very useful when forms should be immutable after they have been submitted. To achieve this behavior you simply add a property named readonly to your schema that will be set to true when the form is submitted. Adding a rule into the form load event, which switches the active view to the read-only view, if this readonly property is set to true, will always show the read-only view after the form is submitted.

Within views, layout tables should be used to arrange elements. These layout tables are displayed in InfoPath Editor using dashed lines, but they are not displayed when the form is rendered. These tables result in HTML table elements in the XSL form view. Controls or fields can simply be dragged into the layout table at the desired position. To limit the effort to lay out the form, InfoPath 2010 offers some table and section templates, as shown in Figure 15-4. You can use them to quickly build well-organized form templates.

Section templates

Figure 15.4. Section templates

To edit the behavior of control fields you can use either the context menu or the Properties ribbon bar. Depending on the type of control, different properties will be available. Every control is bound to a field in your document schema. The Change Binding option will change the binding target. Selecting the Control Properties window will allow you to specify data properties, display properties, size properties, and some other advanced properties. For special data types such as integers and dates, on the display tab you can configure the output format—for example, to display an integer as a currency.

Adding Rules and Validation

Rules are used in InfoPath to control form behavior. While in InfoPath 2007 rules are dispersed across multiple menus—rules, data validation, and conditional formatting—InfoPath 2010 merges them together. They can now be action rules, validation rules, or formatting rules, but are all accessible through one editor pane, the Rules dialog (Figure 15-5).

The Rules dialog

Figure 15.5. The Rules dialog

Every rule consists of an entry condition, allowing the form template author to define when the rule applies. Formatting rules specify text formatting to apply to the nominated field. Validation rules will result in a form error when the condition is not met, and the data for the particular control will be flagged as invalid. Whenever a user changes the value of a control, InfoPath checks the entry conditions of all the action rules assigned to that control. If the condition for a rule is fulfilled, the specified actions are executed.

Warning

Action rules will only by evaluated when the value in the field actually changes. Loading a default value does not trigger the change event, even when it meets the condition for the action rule. Formatting and validation rules, on the other hand, will always be applied.

To view all the rules within a form, you can use the Rule Inspector. It shows all the dynamic elements (e.g., rules, calculated default values, and managed code). Figure 15-6 shows the Rule Inspector for the Conference Room Booking example. You can see that data validations have been added for the date and time values, aggregated under Alerts. Also note too the interesting rules shown in the Other Actions section. The Programming section will contain the events raised by your code when you add code to your form template.

The Rule Inspector

Figure 15.6. The Rule Inspector

Accessing External Data

Designing forms for LOB applications often requires data from external data sources to be included in the form. Typically, such data is retrieved from databases, SharePoint lists, or web services. A drop-down list, for instance, could be populated with values directly within the form. If the values are subject to change, though, you might consider populating them from outside the form. InfoPath accommodates access to external data through the definition of secondary data sources.

Each form consists of one primary data source (also called a data connection) and several secondary data sources. In the previous chapter we described how to define a primary data source using an XSD schema. Data connections can be managed via the Data menu. You can add new data connections using the Data Connection wizard. The wizard will prompt for some specific parameters for the data connection, such as the URL of the SharePoint list and the fields that you want to use. Once the data connection is set up, you need to tell InfoPath to load the data from this connection. This is not done automatically, except when you check the box "automatically retrieve data when the form is opened" in the final step of the Data Connection wizard. Otherwise, you will have to add a rule action that queries the data connection, as shown in Figure 15-7, or execute the connection using code.

Creating a rule to query a data connection

Figure 15.7. Creating a rule to query a data connection

When using web service connections that require query parameters, you need to build a rule that sets the query parameter, queries the connection, and finally returns the result of the web service.

Secondary data connections can be employed in the same ways as primary data connections—in rules and formulas or binding to a control. A common scenario for secondary data connections is to fill a drop-down list with dynamic values, as shown in Figure 15-8.

Building a drop-down list from a data connection

Figure 15.8. Building a drop-down list from a data connection

In this example, the Rooms data source is selected to supply the values in the drop-down list. This data source points to a SharePoint list containing all rooms. The Entries field references the repeating item in the resultant data from the connection, and the list ID and Title are used in the Value and "Display name" fields, respectively.

Data connections can be used for querying data from and submitting data to a data repository. The following table shows a list of data sources you can use and whether they can be used for sending or receiving data.

Table 15.1. Different Types of Data Connections

Data Connection

Submit

Receive

Web service

Yes

Yes

SharePoint library or list

No

Yes

SharePoint document library

Yes

No

E-mail message

yes

No

Groove library or list

No

Yes

Microsoft SQL Server database

No

Yes

XML document

No

Yes

Hosting environment

Yes

No

One very useful data repository is the hosting environment. This can be used to send data to the environment that is hosting the InfoPath form, such as the forms service running on SharePoint or a custom application page. We will discuss this topic in the "InfoPath Forms Services" section later in the chapter.

Using the InfoPath wizard to add a data connection strongly binds the form template to the data connection, since all the information about the connection is stored within the form. When working with SharePoint forms within a multilevel development environment—consisting of a development and production environment—or when creating reusable forms, this solution is very inflexible. To add another layer of abstraction for data connections, you should use data connection libraries in SharePoint. They can easily be created like any other library. Select View All Site Content from the Site Actions drop-down menu. Then click Create and select Data Connection Library to create a new data connection library.

Those libraries can hold Universal Data Description (UDCX) files, which are used to store connection information. UDCX files can then be used by InfoPath to reference data connections. This decouples the strong binding between the actual data connection and the form template, and thus allows you to supply the same form template with different UDCX files for different SharePoint environments.

UDCX files are XML files adhering to the UDC schema definition. Listing 15-9 shows an example UDCX file for a data connection to SharePoint, to retrieve the rooms for the Conference Room Booking example.

Example 15.9. Example Universal Data Description File

<?xml version="1.0" encoding="UTF-8"?>
<?MicrosoftWindowsSharePointServices ContentTypeID="0x010100B4CBD48E029A4ad8B62CB0E41868F2B0"?>
<udc:DataSource MajorVersion="2" MinorVersion="0" xmlns:udc="http://schemas.microsoft.com/office/infopath/2006/udc">
    <udc:Name>Rooms</udc:Name>
    <udc:Description>Format: UDC V2; Connection Type: SharePointList; Purpose: ReadOnly; Generated by Microsoft Office InfoPath 2007 on 2009-10-05 at 13:46:53 by WAPPSmoss_service.</udc:Description>
    <udc:Type MajorVersion="2" MinorVersion="0" Type="SharePointList">
        <udc:SubType MajorVersion="0" MinorVersion="0" Type=""/>
    </udc:Type>
    <udc:ConnectionInfo Purpose="ReadOnly" AltDataSource="">
        <udc:WsdlUrl/>
            <udc:SelectCommand>
                <udc:ListId>{68BB674B-85D9-450A-B394-6FD9F08B6959}</udc:ListId>
                <udc:WebUrl>http://winsrv2008as/</udc:WebUrl>
                <udc:ConnectionString/>
                <udc:ServiceUrl UseFormsServiceProxy="false"/>
                <udc:SoapAction/>
                <udc:Query/>
            </udc:SelectCommand>
            <udc:UpdateCommand>
                <udc:ServiceUrl UseFormsServiceProxy="false"/>
                <udc:SoapAction/>
                <udc:Submit/>
                <udc:FileName>Specify a filename or formula</udc:FileName>
                <udc:FolderName AllowOverwrite=""/>
            </udc:UpdateCommand>
            <!--udc:Authentication><udc:SSO AppId='' CredentialType='' /> </udc:Authentication-->
        </udc:ConnectionInfo>
    </udc:ConnectionInfo>
</udc:DataSource>

The preceding listing contains a processing instruction for SharePoint with a ContentTypeID attribute, which specifies the ContentType for data connection files within SharePoint. The DataSource element defines the namespace and the version of the UDCX format. The attributes of the data connection are defined within the ConnectionInfo section. The element Type as a subelement of DataSource has an attribute also called Type, which specifies the type of the connection. It can be one of the following values, which match the data connection option in InfoPath Editor:

  • SharePointList

  • SharePointLibrary

  • Database

  • XmlQuery

  • XmlSubmit

  • WebService

The attribute Purpose specifies the direction of the data connection. ReadOnly is used for receive connections, WriteOnly is used for submit connections, and ReadWrite is used for bidirectional connections. Depending on this parameter, SelectCommand and/or UpdateCommand need to be supplied. Both support all the necessary information to set up the connection.

To create a UDCX file, you can edit an existing UDCX file or let InfoPath create the file as follows:

  1. Create a data connection library in SharePoint.

  2. Configure your data connection using the InfoPath wizard.

  3. Select the Data Connection Manager in InfoPath from Data

    Example Universal Data Description File
  4. Choose the particular data connection and click Convert to Connection File...

  5. Enter the path to the data connection library you created in step 1, followed by the file name of the UDCX file you want to create.

  6. Choose "Relative to site collection" to cause InfoPath to look for the data connection library relative to the site collection, or choose "Centrally managed data connection" if you intend to manage your data connections in Central Administration.

  7. If you choose to manage your UDCX files centrally, you need to download the UDCX file, save it locally, and then add it manually to Central Administration.

  8. Now you can use this UDCX file in your forms to create a new data connection by selecting "Search for connections on a Microsoft Office SharePoint Server" and entering the URL to the data connection library.

Forms Security

InfoPath form templates support three different levels of security. Each security level defines the allowed level of access to external resources from a form. The required security level for your form depends on the scenario in which you want to use your form. These scenarios range from simple data input scenarios where the form is only used for user input with no programming logic or access to external data sources, to very sophisticated forms that make use of programming facilities and aggregate information from various sources.

You can change the security settings in the Form Options dialog, accessible via File

Forms Security
Security options

Figure 15.9. Security options

By default, the check box "Automatically determine security level" is checked. In this case, InfoPath tries to define the security level based on the features used in the form. Since you should know the scenario for which you are designing the form, it is a good idea to manually select one of the following options. Otherwise, you might run into complications during publishing and deployment, and have to spend extra time searching for the source of your problems.

  • Restricted: The Restricted security level is used for forms that don't contain any code and don't communicate with external data sources. Forms that are created with restricted access can only be used as a data container to collect information from users. Since communication outside of the form is not permitted and no potentially harmful code can be contained in those forms, restricted forms provide the highest level of security. On the other hand, usage scenarios for these types of forms are very limited. Restricted forms always require InfoPath Filler, because to use them with Forms Services in SharePoint, a minimum security level of Domain is required. However, you could e-mail these forms to the recipients or put them on a network share and have users fill them out with InfoPath Filler.

  • Domain: The Domain security level restricts the access of a form to a particular domain. The form can contain code and may access data sources within the domain of the form. InfoPath Forms Services requires at least the Domain security level for forms to render in the browser. By default, you will work with this security level when designing browser-based form templates, as they are suitable for most scenarios where the form accesses lists and libraries on the local SharePoint Server but doesn't contain code that accesses local resources. This type of form is also called sandboxed, because the form is placed in the local cache while the user is filling it out, and access to system resources is denied.

  • Full Trust: The Full Trust security level allows the form to access system resources and other components on the computer where the form will be used, or to use cross-domain data connections. For example, fully trusted forms can contain potentially harmful code and use Microsoft ActiveX controls. Having a higher set of permissions requires fully trusted forms to be digitally signed to ensure security when deploying them to SharePoint. Although you could possibly create fully trusted forms without signing the form, this scenario would require you to install the template on each client—not an acceptable solution in most scenarios. We will show you how to sign and deploy fully trusted form templates in the section "Deploying InfoPath Forms to SharePoint." Fully trusted forms in SharePoint need to be approved by a farm administrator.

Enabling Browser Support

InfoPath allows you to design form templates, targeting different scenarios. The most interesting scenario within the context of SharePoint is the ability to render InfoPath forms in a browser using InfoPath Forms Services. Designing browser-based forms requires some special considerations and settings, and poses some limitations compared to designing forms for the InfoPath client.

Setting Form Compatibility

When you start to design a new form, you can choose the type of template you want to design. Some advanced templates will require you to enable browser support in your form template. To enable browser support, go to File

Setting Form Compatibility

Depending on the compatibility setting, some features will be hidden or deactivated in the relevant dialogs. For example, the multiline feature of text boxes is limited when you work with browser-enabled forms. Figure 15-11 shows the different options for templates designed for InfoPath Editor (on the left) and InfoPath Forms Services (on the right). Therefore, you should always set the compatibility before starting to design your form template. This way you ensure that you are only using available features.

Enabling browser compatibility

Figure 15.10. Enabling browser compatibility

Different properties for InfoPath forms (left) and browser-enabled forms (right)

Figure 15.11. Different properties for InfoPath forms (left) and browser-enabled forms (right)

Configuring Interface Options for InfoPath Forms Services

After you have set the compatibility to Web Browser Form, you will find a new category called Web Browser in your Form Options dialog when you reopen it (Figure 15-13). Here you can set advanced options that change the browser interface, which is shown in Figure 15-14. You can select the commands you wish to display to the user when editing the form. Furthermore, you can select alternative toolbars in case the ribbon bar is not available, and set the language that will be used for displaying the commands and dialogs.

UI in InfoPath Forms Services

Figure 15.12. UI in InfoPath Forms Services

Setting UI options

Figure 15.13. Setting UI options

Configuring Submit Options

You need to specify the destination for the data entered into the form. Submitting the form will trigger Forms Services to run the validation checks on the form. All the validation rules must pass before the submit is allowed to proceed.

You can either specify submission using rules (i.e., you can add a button with an action rule and select the submit action) or you can use the submit options from the Data ribbon bar. In either case you need to specify a submit data connection as described previously. Most commonly you will use a connection to a SharePoint library, a SharePoint data connection, or the hosting environment. When specifying a SharePoint library, you need to provide the URL of the library and the file name for saving the form. The file name can be constructed using a formula. The hosting environment will be used when you want to programmatically access the form information from an ASP.NET application such as SharePoint application pages.

The submit options, as shown in Figure 15-14, allow you to specify the submit destination and the corresponding data connection. As an alternative, you could use code to programmatically handle the submit event.

Specifying submit options and using a button with action rules to submit the form differ in the way the submit action will be displayed to the users. If you are using submit options, the submit button will be displayed in the ribbon bar; however, placing a button in the form provides more flexibility and might be more intuitive for many users. You can also make use of the new image buttons, which allow you to customize button layout.

Setting submit options

Figure 15.14. Setting submit options

To ensure that browser support is configured correctly, use the following checklist:

  • Compatibility is set to Web Browser Form.

  • The UI options are set correctly.

  • The security level is set to Domain or Full Trust.

  • Design Checker shows no compatibility errors.

  • The Submit option is set to either SharePoint or Hosting environment.

Deploying InfoPath Forms to SharePoint

Once you have finished designing your InfoPath form template using InfoPath Designer, you need to make the form template available to users so that they can fill out forms based on your form template. Since information about the target location is stored inside the XSN file, you cannot simply copy your form to that location. Instead, InfoPath offers a process called publishing, which prepares the form template for its target location. Depending on the targeted scenario, required parameters are set in the manifest.xml file inside the XSN archive.

Using InfoPath Forms in SharePoint

Before talking about how publishing works, we will take a closer look at the different ways to use InfoPath forms inside SharePoint. (You can also use your InfoPath forms without SharePoint, but such scenarios will not be covered here.)

The following are some scenarios for using InfoPath forms in SharePoint:

  • Forms in document libraries: This is probably the most common scenario for using InfoPath forms in SharePoint. You simply create a forms library—a special type of document library—in SharePoint and attach form templates to this library. Users are then able to fill out forms based on the provided form templates and submit the results to the forms library. You can easily attach SharePoint workflows to these document libraries to implement simple business processes for your forms.

  • Workflow forms: When building SharePoint workflows you can use InfoPath forms to gather information from users. Workflows allow you to integrate forms at various stages of workflow execution (e.g., association, initiation, or user tasks). Each of these forms can be handled with InfoPath forms instead of custom ASPX pages. In Chapter 16, we describe workflows in more detail and also show how to deploy and integrate InfoPath forms into workflows.

  • Custom application using InfoPath Forms Services: Of course, you can also develop your own application pages, built on InfoPath forms and InfoPath Forms Services. You can host the XmlFormView control within your own page and use it to display InfoPath forms. We will describe the XmlFormView control in more detail later, in the section "InfoPath Forms Services." Creating your own application pages is the most powerful option for using InfoPath forms, because you are barely limited in the solution you build. On the other hand, you have to do more coding, but you gain a significant amount of control!

  • Integrating forms into SharePoint pages using the InfoPath Form Web Part: In SharePoint 2010 a new Web Part for displaying forms has been added, allowing users to add a form to a SharePoint page without any additional effort. Simply select Insert

    Using InfoPath Forms in SharePoint
  • List item forms: SharePoint 2010 increases the integration of InfoPath forms and offers the possibility of customizing all forms for creating, editing, and viewing items in SharePoint lists using InfoPath. If you select Customize Form from the List ribbon bar, as shown in Figure 15-15, InfoPath Designer will open, allowing you to create a custom form for viewing, editing, and creating list items. You can also manage these forms under List Settings

    Using InfoPath Forms in SharePoint
Customizing list forms

Figure 15.15. Customizing list forms

Publishing and Deploying Using the InfoPath Wizard

The easiest way to publish your form templates is to use the InfoPath Publishing wizard. You can reach the wizard from File

Publishing and Deploying Using the InfoPath Wizard
  • Publish form to current location

  • Publish form to SharePoint Library

  • Publish form to a list of E-Mail recipients

  • Publish form to a network location or file share

The first option is available as soon as you define a publishing location. You can use this option to quickly publish your form with the settings you entered the last time you published the form. The publish button is also available in the Quick Access Toolbar.

Publishing to e-mail recipients requires each user to have InfoPath Filler installed on their computer, to fill out the form.

To deploy forms directly to SharePoint you can select the second option, "Publish form to SharePoint Library." If you are deploying your form using a special deployment method, such as features, command-line scripts, or uploading your form using Central Administration, you can also use the fourth option and publish your form to a network location. All the InfoPath Publishing wizard does is add some parameters and options to your manifest file. These settings can, of course, also be set by the other publishing methods. Nevertheless, the wizard can be used for prototyping and ad hoc solutions, so we will describe the different publishing options using the wizard first. In the next chapter, we will show how you can use other publishing methods.

When you start to publish a form to SharePoint using the Publishing wizard, the first step requires you to enter the URL of your SharePoint server. After InfoPath contacts the SharePoint web services to gather information about the site, the dialog shown in Figure 15-16 will appear. Some of the options might be disabled based on the security settings of the form. For example, fully trusted forms will only allow the last option to be selected. The three options are discussed following.

Publishing a form template to SharePoint (basic options)

Figure 15.16. Publishing a form template to SharePoint (basic options)

Tip

After you have entered all the relevant information and finished the wizard, InfoPath will use the Forms Services web service to browser-enable the form template. You can use the same web service for your own deployment scenario. The web service is available at <web application URL>/_vti_bin/FormsServices.asmx. This web service offers methods for browser-enabling form templates and design-checking forms, and several other methods that are useful for form template deployment. Detailed information is available at http://msdn.microsoft.com/en-us/library/bb862916.aspx.

Publishing Form Templates to Document Libraries

When you choose to publish the form template to a document library, the form template will be stored inside the document library in an invisible folder called Forms. The form template itself will be called template.xsn, irrespective of its original file name. A content type will then be created based on this XSN file, and assigned as a standard content type for the document library in question.

By default, when creating a new document library, either from the wizard or manually, only one content type is allowed per library. During publishing, InfoPath will overwrite this content type and set the form template as the default content type.

You can create new documents based on the published form template by clicking New Document on the library toolbar. Thus, this publishing option offers a quick method to create a document library with one InfoPath form assigned. This way you can provide a single form template per library, and you cannot reuse the published form template across multiple libraries.

Note

Although you can select the "Allow management of multiple content types" option from Form Library Settings

Publishing Form Templates to Document Libraries

Publishing Form Templates as a Separate Content Type

If you want to use your InfoPath template across multiple libraries, or use multiple form templates within one library, you need to publish your form template as a separate content type. When you do so, InfoPath Forms Services will create a new content type (or update an existing one if you choose this option) based on the form template. You will then be able to select this content type for your library in the list settings page. When you add the new content type to your library, users will be able to create new documents based on this form template by selecting New Document from the Documents ribbon.

In the Publishing wizard you will be asked to specify a location and file name for your form template (Figure 15-17). You can specify any document library within the site to which your content type will be published. However, the best location for your form templates is a library called Form Templates within your site. This library is available in every site and can be accessed by the path <Site URL>/FormServerTemplates.

Publishing a form template to SharePoint as a content type

Figure 15.17. Publishing a form template to SharePoint as a content type

Publishing Form Templates as Administrator-Approved Templates

As already mentioned in when talking about forms security earlier, whenever you wish to publish a fully trusted form to SharePoint, the form must be deployed by a farm administrator. Such forms are known as administrator-approved form templates. Of course, you can also deploy forms as administrator-approved form templates that don't require administrator approval. You might want to do this to unify your deployment when working with different types of form templates. However, the form templates will have to be deployed by a farm administrator in any case.

During publishing of an administrator-approved template you will be asked to enter the SharePoint URL, which will be saved in the published form template. After that, you must enter a network location or local file name where the template will be saved. A SharePoint administrator can now upload this published form to SharePoint via Central Administration. After uploading, the form must be enabled for the site collections where it is to be used.

In general, using administrator-approved templates requires the following:

  • The form template must be published to a location on the network or local file system.

  • The template must be uploaded to SharePoint.

  • The template must be enabled for a site collection or activated using a script.

In the "InfoPath Forms Services" section we will describe how you can manage form templates in SharePoint Central Administration and how you can deploy and activate your administrator-approved form templates.

Publishing Form Templates to a Network Location

Instead of directly publishing your form template to SharePoint or publishing it as an administrator-approved template, you can publish your template to a network location. In particular, if you are deploying your form template manually to the SharePoint server, or using any other method, such as including your form template into a solution, you can use this publishing method. Since publishing to a network connection does not require you to connect to the SharePoint server, this method will also work when you don't have access to the SharePoint server.

All the relevant settings that allow you to use your form within SharePoint will be established when you enable your template, meaning that you can use this method instead of the more complex SharePoint wizards. In development scenarios, on the other hand, running a wizard allows you to quickly publish new versions of your form. But when using this publishing method, make sure to take one of the following steps to make your form work in Forms Services:

  • Manually upload your form using Central Administration.

  • Use the Forms Services web service.

  • Use stsadm -activateformtemplate.

  • Use the Enable-SPInfoPathFormTemplate cmdlet.

  • Use the XSNFeatureReceiver class in your feature definition (described next).

Warning

If you are deploying your form to a network location, you must in any case specify no "alternate access path" in the last step of the Publishing wizard (as shown in Figure 15-18). Otherwise, the form will not work, because it will not be browser enabled. When you leave the field empty, InfoPath will show a warning you can ignore by selecting OK.

Publishing to a network location: Alternative access path

Figure 15.18. Publishing to a network location: Alternative access path

Embedding Forms into SharePoint Features

SharePoint features offer a standardized way to package all the relevant elements of a certain scope together and deploy them to a SharePoint farm. When creating a feature you will probably also want to include your form templates to deploy them along with your other elements.

The example in Listing 15-10 demonstrates how to build a feature to deploy your form templates to the Form Template library of a site collection. The feature definition file contains the following important entries that are particular to form template deployment:

  • ReceiverClass: This attribute of the feature element points to the XsnFeatureReceiver class, which provides an implementation of the SPFeatureReceiver and handles events that are raised when a feature is installed, uninstalled, activated, or deactivated. It takes actions on the forms according to the feature event, such as registering a form template when the feature is installed. Essentially, the XsnFeatureReceiver class takes care of your XSN files when you include them in a feature.

  • ReceiverAssembly: This refers to the Microsoft.Office.InfoPath.Server assembly, which contains the XsnFeatureReceiver class.

  • ElementFile: The Location attribute points to the XSN file of your form template relative to your feature.xml file.

  • ActivationDependency: To make sure that the InfoPath Forms Services feature is available, it is good practice to add an activation dependency to this feature. This way, an error will be displayed during feature activation if Forms Services is not available. In the following example, you will see an ActivationDependency element referencing the FeatureId of the InfoPath Forms Services feature.

Tip

For additional requirements and extreme scenarios, you can also extend the feature receiver and develop your own implementation for deploying XSN files through a SharePoint feature. Please refer to the MSDN documentation for further information: http://msdn.microsoft.com/en-us/library/microsoft.office.infopath.server.administration.xsnfeaturereceiver(office.14).aspx.

Example 15.10. Including a Form Template in a Feature: feature.xml

<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="F1C92BB0-61E2-4372-B626-4276BE8A4435"
    Title="RoomBookingFeature"
    Description="RoomBooking form deployed using a feature"
    Version="1.0.0.0"
    Hidden="False"
    Scope="Site"
    DefaultResourceFile="core"
    xmlns="http://schemas.microsoft.com/sharepoint/"
    ReceiverClass="Microsoft.Office.InfoPath.Server.Administration.XsnFeatureReceiver"
    ReceiverAssembly="Microsoft.Office.InfoPath.Server, Version=14.0.0.0, Culture=neutral,
 PublicKeyToken=71e9bce111e9429c">

    <ElementManifests>
        <ElementManifest Location="elements.xml"/>
        <ElementFile Location="RoomBookingFeature.xsn" />
    </ElementManifests>

    <ActivationDependencies>
        <ActivationDependency FeatureId="C88C4FF1-DBF5-4649-AD9F-C6C426EBCBF5" />
    </ActivationDependencies>

</Feature>

The elements.xml manifest file contains only one Module element (Listing 15-11). Module elements are used to provision files to SharePoint. The Url attribute of the module element denotes the target URL on the SharePoint server. In this case, the form template will be stored in the form template library relative to the site collection. For each file that needs to be provisioned to SharePoint, one File element is required within the Module element. You can also provision a collection of files using one module. See the following link for more details on file provisioning: http://msdn.microsoft.com/en-us/library/ms441170(office.14).aspx.

Example 15.11. Including a Form Template in a Feature: elements.xml

<?xml version="1.0" encoding="utf-8" ?>
<Elements  xmlns="http://schemas.microsoft.com/sharepoint/">
    <Module Name="RoomBooking" Url="FormServerTemplates" RootWebOnly="TRUE">
        <File Url="RoomBookingFeature.xsn" Name="RoomBookingFeature.xsn" Type="GhostableInLibrary" />
    </Module>
</Elements>

Deploying Forms Using Command-Line Utilities

When you are developing SharePoint applications in a professional environment, you will probably wish to automate deployment and avoid uploading each form template to each environment by hand using the InfoPath UI. There are two options, both of which are command-line utilities to script SharePoint administration tasks: stsadm.exe and PowerShell cmdlets.

For either to work correctly, you first need to publish your form to a file on a network share or on the local file system. This step needs to be done manually by the form template designer. When referring to a form template to be deployed, we are always talking about a previously published template.

stsadm.exe

stsadm.exe is the command-line utility used in previous SharePoint versions to administer SharePoint from the command line and for scripting batch files. Although its use will diminish in favor of PowerShell cmdlets, it is still supported by SharePoint 2010. Since it is widely used, we will show the most important commands. stsadm.exe is located in the bin folder of the SharePoint installation path: C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14instsadm. To run the utility, you need to pass the parameter -o followed by the supported operation you wish to execute.

Working with InfoPath forms, the operations described in Table 15-2 are useful for uploading and installing form templates.

Table 15.2. stsadm Operations for InfoPath Form Templates

Operation

Description

ActivateFormTemplate

Activates a form template for a site collection

AddDataConnectionFile

Adds a new instance of a DataConnectionFile to the DataConnectionFiles collection

DeactivateFormTemplate

Deactivates a form template for a site collection

EnumDataConnectionFileDependants

Enumerates all forms that are dependent on the specified data connection file

EnumDataConnectionFiles

Enumerates all of the DataConnectionFiles in the collection

EnumFormTemplates

Enumerates all form templates

GetFormTemplateProperty

Retrieves properties of a form template

RemoveDataConnectionFile

Removes specified data connection files from the collection

RemoveFormTemplate

Removes the specified form template

SetDataConnectionFileProperty

Sets a file property to a data connection file

SetFormsServiceProperty

Sets a configuration property of Form Services

SetFormTemplateProperty

Sets the properties of an individual form template

UploadFormTemplate

Uploads a form template to Forms Services

VerifyFormTemplate

Checks whether it's acceptable for the form template to be uploaded to the server

Using the preceding operations you could write a script such as the following to upload a new form template after deactivating and removing the prior version of the form. Instead of the file name, you can also use the <formid> to specify the form template.

STSADM.EXE -o DeActivateFormTemplate -url http://<servername> -filename <filename.xsn>
STSADM.EXE -o RemoveFormTemplate -filename <filename.xsn>
STSADM.EXE -o VerifyFormTemplate -filename <filename.xsn>
STSADM.EXE -o UploadFormTemplate -filename <filename.xsn>
STSADM.EXE -o ActivateFormTemplate -url http://<servername> -filename <filename.xsn>

PowerShell Cmdlets

As described in Chapter 9, SharePoint 2010 relies heavily on PowerShell cmdlets for administration tasks. The following cmdlets are relevant when working with InfoPath form templates. The table also lists the stsadm commands that have similar functions, to give users familiar with stsadm a quick cross-reference:

Table 15.3. PowerShell Cmdlets for InfoPath Form Templates

Operation Name

Description

stsadm Equivalent

Disable-SPInfoPathFormTemplate

Deactivates a form template for a site collection

DeactivateFormTemplate

Enable-SPInfoPathFormTemplate

Activates a form template for a site collection

ActivateFormTemplate

Get-SPDataConnectionFile

Enumerates all of the DataConnectionFiles in the collection

EnumDataConnectionFiles

Get-SPDataConnectionFileDependent

Enumerates forms that are dependent on the specified data connection file

EnumDataConnectionFileDependants

Get-SPInfoPathFormTemplate

Returns an InfoPath form template and its parameters

GetFormTemplateProperty, EnumFormTemplates

Install-SPDataConnectionFile

Installs the provided data connection file

AddDataConnectionFile

Install-SPInfoPathFormTemplate

Uploads a form template to Forms Services

UploadFormTemplate

Set-SPDataConnectionFile

Sets properties of a data connection file

SetDataConnectionFileProperty

Set-SPInfoPathFormsService

Sets parameters for InfoPath Forms Services

SetFormsServiceProperty

Set-SPInfoPathFormTemplate

Sets the properties of an individual form template

SetFormTemplateProperty

Test-SPInfoPathFormTemplate

Validates that a form template can be browser enabled

VerifyFormTemplate

Uninstall-SPDataConnectionFile

Removes specified data connection files from the collection

RemoveDataConnectionFile

Uninstall-SPInfoPathFormTemplate

Removes the specified form template from a farm

RemoveFormTemplate

Update-SPInfoPathFormTemplate

Upgrades all form templates on the farm

 

By analogy, with the stsadm commands shown in the table, the following script can be used to upload a new version of an InfoPath form, after deactivating and removing the prior version of the form:

Uninstall-SPInfoPathFormTemplate -Identity formName.xsn
Install-SPInfoPathFormTemplate -Path C:Form.xsn
Enable-SPInfoPathFormTemplate -Identity "FormTemplate.xsn" -Site "http://TestSite"

Deploying Forms with Code

When using custom code in your InfoPath form template, as described in the next section, you have two deployment options:

  • Deploying your form as a sandboxed solution

  • Deploying your form as an administrator-approved form

InfoPath forms that contain code will be deployed as sandboxed by default when you use the Publishing wizard to deploy your form to SharePoint. In this case, the code will be run in a sandbox to avoid harm to your SharePoint farm. This publishing method can be chosen by any site administrator and does not require farm administration privileges. Sandboxed form templates are only available to InfoPath 2010 form templates that do not use Web Part connection parameters.

The second option is to deploy your form as an administrator-approved form template, as described earlier. In this case, the code will be granted full trust, since this deployment method is only available to farm administrators.

Tip

To use sandboxed form templates you must ensure that the Microsoft SharePoint Foundation User Code Service is started. This service is responsible for sandboxed solutions. It can be started in Central Administration via System Settings

Deploying Forms with Code

Table 15-4 compares the two options for deploying forms with code.

Table 15.4. Comparing Sandboxed and Administrator-Approved Templates

Category

Sandboxed Form Template

Administrator-Approved Template

Permission

Site collection administrator

Farm administrator

Publishing

InfoPath Designer wizard

Central Administration

Security

Form code run in sandbox, no harm to farm

Code runs with full trust on the server

Programming InfoPath Forms

InfoPath Designer 2010 features a convenient UI for designing form templates and adding some basic control logic using rules. But as soon as the complexity of your forms grows and interaction with the environment increases, you should take a closer look at the development facilities in InfoPath. Looking at the Developer tab in the ribbon bar (Figure 15-19), you can get an idea of the variety of events that can be used to integrate managed code into your InfoPath form template.

Developer ribbon bar in InfoPath Designer

Figure 15.19. Developer ribbon bar in InfoPath Designer

Attaching Managed Code

Before you can begin programming your form template, you need to specify the code language and the location for your code project in the Form Options dialog. You can reach this dialog directly using the Language button on the Developer tab. The managed code language options are C# and Visual Basic. In addition, you can nominate the location where the project for your form code will be stored. For every form, a separate project is created. The assembly that is generated when the project is built will also be included in the resulting XSN file.

Note

You can also use InfoPath 2010 to develop forms that are compatible with 2007. You can select "InfoPath 2007 compatible code" from the Form template code language drop-down list. In this case, the project will reference the old library, located by default in C:Program filesMicrosoft OfficeOffice14InfoPathOMInfoPathFormsServicesInfoPathFormsServicesV12.

After you have configured these basic development settings, a click on the Code Editor button or one of the events on the Developer tab of the ribbon bar will cause Visual Studio Tools for Applications (VSTA) to start. InfoPath 2010 still uses VSTA 2005, and the resulting projects are based on .NET 2.0. However, VSTA will configure all the required settings for you. The project for your form template will open, and you can start programming your form template. Figure 15-20 shows the basic skeleton of a form project.

Basic InfoPath project with VSTA

Figure 15.20. Basic InfoPath project with VSTA

Note

The ability to develop script code using JScript or VBScript has been removed in InfoPath 2010. Instead, form templates can use only managed code.

Depending on the form type that is selected in the form options, the appropriate InfoPath library will be included into the project. Since Forms Services only supports a subset of functionality when designing web browser forms, a different Microsoft.Office.InfoPath.dll is loaded from the subfolder InfoPathOMFormsServices.

When accessing the form code for the first time, the necessary project will be created automatically. A class named FormCode will be autogenerated. This class is derived from XmlFormHostItem, which is an abstract class, acting as a wrapper for an XMLForm. The FormCode class that you will use for programming is implemented as a partial class. All virtual methods that need to be overwritten are implemented in FormCode.Designer.cs. From here, the method InternalStartup and all the events you implement will be called. This illustrates the basic paradigm for programming InfoPath forms: everything you do must be associated with an event. The only way to execute your code is in reaction to something that happens in the form, such as loading the form, changing a value, or closing the form.

InfoPath Object Model

The InfoPath object model offers programmatic access to the views, data connections, and behavior of the form. Using this object model, you can make your forms highly flexible. As stated earlier in this chapter, Forms Services only supports a subset of the InfoPath object model, which is available to InfoPath Filler forms. Since we are focusing on using InfoPath together with SharePoint, the following descriptions are focused on the object model available to Forms Services.

The Microsoft.Office.InfoPath.XmlForm class represents the data of the underlying XML document. Thus, it is one of the key objects for interacting with the XML data of the form. However, when working with browser-compatible forms, you will only have access to the properties and methods of the XmlForm object that are wrapped by the XmlFormHostItem object in the form template code. Since the class that is created for you is a subclass of XmlFormHostItem, you can access the relevant members using the keyword this.

Events

For code in your InfoPath project to be called, it needs to be tied to an event. Events can be added by clicking the event buttons in the development ribbon. Each event will be registered as a delegate in the InternalStartup method. The class EventManager is used to bind event handlers to the different events.

Events are divided into three categories: FormEvents, ControlEvents, and XmlEvents. Each of these categories is represented by an object of the same name. FormEvents are events that occur to the form, such as loading and saving. ControlEvents are events issued by special controls. For example, the ButtonEvent implements the Clicked event, which is handled as a control event. Whenever you add a button and want to handle the Clicked event using code, an event handler will be added to the ControlEvents.

Finally, XmlEvents are used for anything that happens to the underlying XML structure of your form—for example, when a field is changed. When changes are made to the XML data, events will be bubbled up through the data structure. Assume your schema has a group element group1 that contains a field element called test. Figure 15-21 shows the simple data schema for this example.

Simple data schema used for the events example

Figure 15.21. Simple data schema used for the events example

When you change the content of the field element test, the event handler of the test element will be called. After that, the Changed event of the group1 element will be raised. When working with XmlChange events, the XmlEventArgs object supplies detailed information about the change. You can retrieve the OldValue, which shows the value before the change, and the NewValue, which contains the value after the change. In addition, the member Site returns an XPathNavigator object that points to the element on which the change event is currently being handled. The element that is responsible for the change (in the preceding example, this is the test element) can be accessed using the sender object. This is also an XPathNavigator object that points to the element that was originally changed and caused the event to be passed upward through the hierarchy. Listing 15-12 shows how these events will be thrown. Each event simply displays a MessageBox that outputs the name of the event along with the name of the Site element and the name of the sender object. This example is built with an InfoPath Filler form template to keep it as simple as possible. The MessageBox is not available to web browser forms.

Example 15.12. Assigning Events in Form Code

public partial class FormCode
{
    public void InternalStartup()
    {
        // Register events
EventManager.XmlEvents["/my:myFields"].Changed +=
                                  new XmlChangedEventHandler(myFields_Changed);
        EventManager.XmlEvents["/my:myFields/my:group1"].Changed +=
                                    new XmlChangedEventHandler(group1_Changed);
        EventManager.XmlEvents["/my:myFields/my:group1/my:test"].Changed +=
                                      new XmlChangedEventHandler(test_Changed);
    }

    public void group1_Changed(object sender, XmlEventArgs e)
    {
        // Show a message box about the changes
        MessageBox.Show("group1_Changed: Site=" + e.Site.Name + " sender=" +
             ((XPathNavigator)sender).Name + "from " + e.OldValue + " -> " +
             e.NewValue);
    }

    public void test_Changed(object sender, XmlEventArgs e)
    {
        MessageBox.Show("test_Changed: Site=" + e.Site.Name + " sender=" +
             ((XPathNavigator)sender).Name);
    }

    public void myFields_Changed(object sender, XmlEventArgs e)
    {
        MessageBox.Show("myFields_Changed: Site=" + e.Site.Name + " sender=" +
             ((XPathNavigator)sender).Name);
    }
}

Table 15-5 shows all events that are available in browser-enabled forms. When working with InfoPath Filler, some additional events are available.

Table 15.5. Events in Form Templates

Category

Event

Description

FormEvents

Loading

Occurs after the form template has been loaded.

FormEvents

Submit

Occurs when the form is submitted.

FormEvents

ViewSwitched

Occurs after a view has been switched.

FormEvents

VersionUpgrade

Occurs when the form needs to be updated, because its version number is older than the form template on which it is based

ControlEvents

Clicked

Occurs when a Button control is clicked. The ButtonEvent class implements the Clicked event.

XmlEvent

Validating

Occurs when changes have been made to the XML document and after InfoPath has finished validation.

XmlEvent

Changed

Occurs after changes have been made to the XML document and after the Validating event.

Accessing the Form Data

When discussing events earlier, we encountered a very important class for working with XML data sources: XPathNavigator. This class provides cursor-based access to primary and secondary XML data sources of the InfoPath form and allows modification of the XML data structure. You can use XPathNavigator to navigate over the XML structure using move methods such as MoveToFirstChild or MoveToParent. The cursor of XPathNavigator will then be moved relative to its current node and point to a different node in the XML hierarchy. On the node to which the cursor is currently pointing, you can execute several methods to modify the data or retrieve information about that node. The property Name contains the name of the current node, and OuterXml will return the XML data for the current node from its opening to its closing tags, including its child nodes. InnerXml, on the other hand, returns the XML fragment that is contained within the current node, excluding the node itself. The property Value returns the string of the current node's value item, and the method SetValue allows you to set this value.

When working with InfoPath, navigating through the XML structure along the XPath axes is not very common, since you already know about your data structure. Most of the time you will want to directly select a node or node set to read or write fields in your data source. XPathNavigator offers two very useful methods for selecting nodes: Select and SelectSingleNode. Both methods select nodes according to the given XPath expression, but instead of returning an instance of XPathNodeIterator, SelectSingleNode returns the XPathNavigator object of the first node matching the XPath query. Thus, accessing a node in your form becomes very easy. All you need to do is right-click the node in the Fields pane in InfoPath Designer and select Copy XPath, as shown in Figure 15-22.

Copying the XPath of a field

Figure 15.22. Copying the XPath of a field

This will create the XPath expression for selecting the node, which can then be copied into the Select method of the XPathNavigator object. To resolve the namespaces used in the form, the select methods also require an element implementing the IXmlNamespaceResolver interface. Fortunately, the NamespaceManager object of the XmlForm already implements this interface, and you can simply use the NamespaceManager property when calling the Select methods.

To access the XML data using XPathNavigator, you first need access to the data sources. XmlForm offers access to a DataSource through its DataSources property. As mentioned earlier, a form consists of one primary and several secondary data sources. The DataSources property contains all the data sources, including the main data source. In addition, MainDataSource provides direct access to the form's main data source. On any DataSource object, you can call the CreateNavigator method to obtain an XPathNavigator that can be used to access and manipulate the data source.

The following example shows a very common scenario, in which data is loaded from a web service into the main data source using XPathNavigator. A data connection to the SharePoint list Rooms was added to retrieve all the room entries in the list and load them into the Room drop-down list on the InfoPath form, which is shown in Figure 15-23.

Selecting rooms from a SharePoint list

Figure 15.23. Selecting rooms from a SharePoint list

The web service will be called during form loading, and a second data connection, called GetRoom, will be added. It will be queried when a user selects a room from the drop-down list, and will load the detailed information from the list for the selected room. Then the "RoomNumber" field will be filled from the web service response using XPathNavigator. Calling the "GetRoom" data connection and loading the "RoomNumber" will be done in the changed event that is bound to the Room field. So whenever someone edits the content of the Room field by selecting a room, this code will be executed.

Example 15.13. Loading Data from a Web Service into a Form

using Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;

namespace RoomBooking_LoadingWebService
{
    public partial class FormCode
    {

        public void InternalStartup()
        {
            EventManager.XmlEvents["/my:RoomBooking/my:Schedule/my:Room"]
                          .Changed += new XmlChangedEventHandler(Room_Changed);
        }

        public void Room_Changed(object sender, XmlEventArgs e)
        {
            XPathNavigator form = MainDataSource.CreateNavigator();

            // Set parameter for web service request and query connection
            DataSources["GetRoom"].CreateNavigator().SelectSingleNode(
                  "/dfs:myFields/dfs:queryFields/q:SharePointListItem_RW/q:ID",
                  NamespaceManager).SetValue(e.NewValue);
            DataSources["GetRoom"].QueryConnection.Execute();

            // Create navigator on web service response
            XPathNavigator roomdata = DataSources["GetRoom"].CreateNavigator();
// Set fields with values from web service response
            XPathNavigator nodeRoomNumber = form.SelectSingleNode(
                "/my:RoomBooking/my:Schedule/my:RoomNumber", NamespaceManager);
            nodeRoomNumber.SetValue(roomdata.SelectSingleNode(
                "/dfs:myFields/dfs:dataFields/d:SharePointListItem_RW/d:RoomNumber",
                NamespaceManager).Value);
        }
    }
}

Maintaining State in Browser-Based Forms

To maintain global state in browser-enabled forms, you can use the FormState property of XmlForm. Working with browser-enabled forms, this is the only way to persist data during a session. As with web pages, you cannot use member variables to maintain state, since they will not be persisted between requests. The FormState property will keep its values from the time the form is opened until it is closed.

FormState is an IDictionary object that holds user-defined key/value pairs of state variables. Both key and value can be any object, but generally strings are used for the key. The value can store objects that hold complex data. For convenience you might consider introducing a global member variable that leverages FormState by reading from and writing to FormState in the get and set methods. This gives you the ease of use of properties while still persisting data between requests.

Listing 15-14 shows how you can create a member variable using FormState, which can persist information across multiple events.

Example 15.14. Maintaining State in Forms Using FormState

public string Username
{
    get
    {
        if (FormState["_username"] != null)
        {
            return (string)FormState["_username"];
        }
        else
        {
            return "";
        }
    }
    set
        {
            FormState["_username"] = value;
        }
    }
}

Accessing Views

Forms are organized using views. You can also work with views in your form code. As described earlier, you can use the ViewSwitched event to react to the change of the current view. The XmlForm object contains useful information about views. First of all, you can use the CurrentView property to get the view that is currently active. In a web-based form template, the resulting View object contains a ViewInfo member with descriptive information about the view. In web forms, you can only access the Name of the view. To access all the available views for a form template, the ViewInfos member returns a list of ViewInfo objects. In addition, it holds the Default and Init properties, which return the default view and the initial view of the form.

If you wish to programmatically switch the view, you can use the SwitchView method of the ViewInfoCollection returned by ViewInfos to switch the view from the current view to the desired view.

Handling Errors

During validation of a form, several errors in the form data can occur. For example, if you add a validation rule, the field will be displayed in red when the validation fails. In general, errors can arise when a form's XML schema is validated, when a custom validation rule fails, or when the error is added to the collection of errors from code. The XmlForm object keeps in the Errors property a collection of all errors that occurred. You can access individual Error objects from the list of errors, as with any other enumerable collection.

Each Error object contains detailed information about the error, (e.g., in the Name, Message, and DetailedMessage properties). The property FormErrorType specifies how the error was generated: through SchemaValidation, SystemGenerated or, UserDefined. Since an error always belongs to a node in the XML data that caused the error due to a failed validation, the property Site holds an XPathNavigator object that points to the affected node.

You can also add your own errors to the Errors collection using the Add method. This method expects an XPathNavigator pointing to the affected node, a name, and a message. Deleting errors from the list can also be done easily using the Delete method.

Using the Errors collection allows you to manage all the errors in your form that can eventuate during validation.

InfoPath Forms Services

InfoPath Forms Services is part of Microsoft SharePoint Server 2010. It renders InfoPath forms in the browser and allows users to complete InfoPath forms without InfoPath Filler. This section discusses the basic settings for enabling InfoPath Forms Services on SharePoint 2010, how to manage form templates, and how you can use XmlFormView to customize Forms Services. Finally, different ways to integrate forms with SharePoint are presented.

Preparing InfoPath Forms Services Support

Before you can start viewing InfoPath forms in SharePoint, several configuration options need to be set, and the form templates have to be managed appropriately. Compared to SharePoint Server 2007, many of the configuration settings have been simplified, especially because the shared service providers have been replaced by service applications in SharePoint 2010. Many of the settings we will demonstrate using Central Administration can also be adjusted using PowerShell. As far as is practicable, we will also mention corresponding cmdlets.

For Forms Services to work properly, you need to do the following:

  • Enable the State Service using the Farm Configuration wizard.

  • Configure InfoPath Forms Services in the general application settings.

After you are finished with these settings you can start to deploy your forms and integrate them into your SharePoint solution. But first we will show you in more detail what these settings are about.

State Service

What was a painful configuration hazard in earlier versions of SharePoint has become effortless with SharePoint 2010: configuring the State Service. Since SharePoint relies on service applications to provide shared functionality, you don't have to deal with shared service providers any more. Simply run the Farm Configuration wizard from the Configuration Wizard section. On the second page are many service applications. Select State Service and complete the wizard.

State Service configuration

Figure 15.24. State Service configuration

The State Service is required to store temporary data between related HTTP requests and thus keep the state of your forms. To store the data, a SQL database is used. By default, the data will be stored in the same database as the content database, and a single State Service instance will be shared among all components that require State Service. You can only change those advanced settings using PowerShell. SharePoint Central Administration does not provide any control other than enabling State Service using default settings.

Configuring InfoPath Forms Services

SharePoint Central Administration contains a separate section for managing InfoPath Forms Services. It is located on the General Application Settings page. Besides management of form templates, data connection files, and a proxy for InfoPath forms, it also contains a link to the "Configuration of InfoPath Forms Services" settings.

Central Administration: Configuring InfoPath Forms Services

Figure 15.25. Central Administration: Configuring InfoPath Forms Services

Without going into too much detail, we will briefly describe the most relevant settings in the configuration screen (Figure 15-25). Most of the settings are self explanatory.

The first section defines how browser-enabled forms deployed by users are handled in InfoPath Forms Services. If you select "Allow users to browser-enable form templates," you allow users to deploy browser-enabled forms. The next option allows browser-enabled user form templates to be displayed in the browser. If you don't select "Render form templates that are browser-enabled by users," users will still be able to deploy browser-enabled forms, but the forms will not be displayed in the browser. If you ever have trouble displaying a browser-enabled form, make sure that these options are set correctly.

If you want your users to access data from other domains using data connection files, you should check the "Allow cross-domain data access . . ." check box.

For any other settings, please refer to MSDN for detailed information here: http://technet.microsoft.com/en-us/library/cc262263(office.14).aspx.

For many common scenarios, the default settings in this dialog are appropriate.

Configuring Libraries

Each document library has options for displaying browser-based documents and for managing document templates. In addition, settings concerning content types also need to be considered when deploying forms to form libraries. Figure 15-26 shows the most significant options for configuring forms in document libraries.

You can configure separately for each library whether an InfoPath form will be opened in the browser when adding a new form to the library or selecting an existing form in the list. Go to the Library settings page and select Advanced Settings. Among several others, you will be able to change the "Opening Documents in the Browser" setting. You can choose whether you always want your forms to be opened in the browser or on the client using InfoPath Filler.

Depending on how you deploy your forms, and whether you want to use several different forms in one library, you can specify whether the library in question should allow management of content types. Under the Yes option, different forms can be added to the library via content types. This requires you to deploy your form templates as a content type. If you select No, only one template is allowed at a time.

The Document Template setting allows you to specify the URL of the form template used in this library. This option is only available when management of content types is deactivated. If you have InfoPath Designer installed on your computer, you can use the (Edit Template) link to directly edit the form template.

Form options in library settings

Figure 15.26. Form options in library settings

Managing Form Templates

Deploying InfoPath forms to a SharePoint library can easily be done in InfoPath Designer with the help of the Publishing wizards. But if you need to deploy your form template as an administrator-approved template, you must manually upload your template to SharePoint. This can be done in the Central Administration page. Under General Application Settings, InfoPath Forms Services is "Manage form templates." On this page (Figure 15-27) you will find all form templates that are available to the farm, which are templates that are either shipped with SharePoint or have been uploaded by an administrator. Those form templates can be activated to a site collection. Doing so will copy these templates to the Form Templates library in the selected site collection. Naturally, you can also deactivate a form template from a site collection, causing the form template to be removed from the Form Templates library of the site collection.

If you don't need your templates to be approved by an administrator, or if you only want to use your forms in the context of a site collection, you can simply upload your form template to the Form Templates library of the site collection.

Manage form templates in Central Adminstration

Figure 15.27. Manage form templates in Central Adminstration

Displaying Forms in the InfoPath Form Web Part

Probably the easiest way to display your browser-enabled forms in a web page is by using the InfoPath Form Web Part. This Web Part is new with SharePoint 2010 and allows you to integrate your forms into any page. You can use this Web Part like any other Web Part and simply add it to one of the Web Part zones on your page. Although your influence on form behavior is limited, this Web Part is excellent for rapid prototyping and basic scenarios. For more complex scenarios you might want to look into the possibilities offered by the XmlFormView control, described in the next section.

The InfoPath Form Web Part uses the XmlFormView control to render InfoPath forms. Many options for configuring the Web Part are available, and the Web Part can handle different sources for the form template and the form data, but form rendering is handled by XmlFormView.

To insert the Web Part into your page, you need to switch to Edit mode for the page and select Editing Tools

Displaying Forms in the InfoPath Form Web Part
Inserting the InfoPath Form Web Part

Figure 15.28. Inserting the InfoPath Form Web Part

Use the Edit Web Part option to configure the Web Part. You will find the following settings in the Web Part configuration pane, as shown in Figure 15-29. You can specify the source of your form template to display. Essentially, you can select any form template that is published to a list or library, and is thus available as a content type. Opt for the appropriate list or library and then choose the template. You can also specify the default view to display and the behavior after the form is submitted.

You may be wondering where you configure the destination of the form data when it is submitted. Remember that this is already configured within the form template, and therefore there is no configuration required in the Web Part. However, since you don't have full control over the Web Part, the "Submit to the hosting environment" option cannot be used with this scenario.

InfoPath Form Web Part configuration dialog

Figure 15.29. InfoPath Form Web Part configuration dialog

Customizing the Browser View Using XmlFormView

To display your browser forms within SharePoint you can use the InfoPath Form Web Part to integrate the form with a page, as described earlier. If a form is opened from a form library, it will be displayed by FormServer.aspx, which is an application page that hosts a control for displaying forms. If you need more control over the way the form will be displayed and want direct access to events, you can use the XmlFormView ASP.NET control in your own application page. This control renders InfoPath forms in the browser and provides several facilities for developers to change its default behavior.

Integrating XmlFormView in an Application Page

To integrate XmlFormView with your web page, you need to register the assembly Microsoft.Office.InfoPath.Server. Having done that, you can place the XmlFormView control in your ASPX markup, set some important parameters for the control, and bind events. The following listing shows the markup for an application page. The OnSubmitToHost attribute is bound to a method in the code-behind file. This code will be called when the form sends data to the hosting environment, using a submit data connection. Another attribute to note is the EditingStatus. This describes the editing state of the form and has three possible values: Init, Editing, and Closed. Use the Init state to hide the form during loading of the form and set it to Editing later on. In state Editing, the form is visible to the user. This is the only state in which the user can edit or view the form. When the form is closed, the common message "The form has been closed" will be displayed. If you have ever had an error in your form, you will be familiar with this message.

Example 15.15. Integrating XmlFormView into the Markup of an Application Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowForm.aspx.cs" Inherits="ShowForm" EnableSessionState="True" %>
<%@ Register tagprefix="fv" namespace="Microsoft.Office.InfoPath.Server.Controls" assembly="Microsoft.Office.InfoPath.Server, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register tagprefix="Server" namespace="Microsoft.Office.InfoPath" assembly="Microsoft.Office.InfoPath, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>FormViews</title>
    </head>
    <body style="margin: 0px;overflow:auto;padding:20px">
        <form id="form1" runat="server" enctype="multipart/form-data">
            <fv:XmlFormView ID="formView" runat="server"
                            EditingStatus="Editing"
                            OnSubmitToHost="FormView_SubmitToHost"
                            Width="700px">
            </fv:XmlFormView>
        </form>
    </body>
</html>

To correctly display forms, XmlFormView needs to know the location of the form to display, the location of the form template used to render the form, and finally, the location for saved forms to be stored. The properties XmlLocation, XsnLocation, and SaveLocation are used to pass this information to the XmlFormView object.

Note

You don't need to specify SaveLocation if you don't use the Save method. This may be the case if you deactivate the Save button in the User Interface Options section of the Form Options dialog (see Figure 15-13), or if you implement your own save method.

When opening an existing form, the matching form template is contained in the manifest file and does not need to be specified. But when a new form is created, the form template needs to be specified. You can specify these parameters in the page markup as attributes or set the class properties directly inside your code-behind.

To display an XML form, you can use the following code in the On_Load method in the code-behind file of the previous example. In the following listing, depending on a request parameter, either an existing form will be loaded using the XmlLocation parameter or the template will be assigned by the XsnLocation if the request parameter action equals new.

Example 15.16. Code-Behind File of an Application Page Hosting XmlFormView

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.InfoPath.Server.Controls;

namespace com.apress.formviewdemo
{

    public partial class ShowForm : LayoutsPageBase
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            string action = Request.Params["action"];
            if (action == "new")
            {
                // Set the template location for new forms
                String templateLib = "FormServerTemplates";
                String xsnName = "template.xsn";
                formView.XsnLocation = String.Format("{0}/{1}/{2}",
                              SPContext.Current.Web.Url, templateLib, xsnName);
            }
            else
            {
                // Set the XML location for an existing form
                String lib = "TestForms";
                String name = "example.xml";
                formView.XmlLocation = String.Format("{0}/{1}/{2}",
                                         SPContext.Current.Web.Url, lib, name);
            }
        }

        protected void FormView_SubmitToHost(object sender, SubmitToHostEventArgs e)
        {
            // Will be implemented later
        }
    }
}

Accessing the XmlForm Object

Working with XmlFormView, you can access the XmlForm object and thus all the values and settings of the form described in the "Table 15-6 compares the two options for deploying forms with code.

Table 15.6. Comparing Sandboxed and Administrator-Approved Templates

Category

Sandboxed Form Template

Administrator-Approved Template

Permission

Site collection administrator

Farm administrator

Publishing

InfoPath Designer wizard

Central Administration

Security

Form code run in sandbox, no harm to farm

Code runs with full trust on the server

Programming InfoPath Forms" section. Via the XmlForm property you can reach the properties DataSources, ViewInfos, FormState, and such from within the page that is hosting the form. The XmlForm object can be accessed whenever the code is run within one of the following event handlers, which enables a form to communicate with its hosting environment:

Table 15.7. Events Available in XmlFormView

Event

Description

Initialize

This is called when the form is loaded.

NotifyHost

Notification events can pass a parameter to the hosting environment. Call this.NotifyHost() in your form template code.

SubmitToHost

This is called when the form is submitted using a submit to host data connection.

Close

This is called when the form is closed.

If you want to access the XmlForm object from another event on your page, you have to first call the method Data Bind of the XmlFormView object to ensure that the XmlForm object is adequately populated.

You can directly access fields inside your form using the XPathNavigator on the MainDataSource. This may be required when implementing your own OnSubmitToHost event where you wish to store the XML data into a library and build the file name using information within the form. Listing 15-17 shows how this can be done. To keep things clear, we have only implemented the OnSubmitToHost event, which was left blank in the previous example.

Example 15.17. Saving a Form to a SharePoint Library Using OnSubmitToHost Event

protected void FormView_SubmitToHost(object sender, SubmitToHostEventArgs e)
{
    SPWeb web = SPContext.Current.Web;
    web.AllowUnsafeUpdates = true;

    // Load the XML and save it as a byte array
    System.Xml.XPath.XPathNavigator navigator =
                            formView.XmlForm.MainDataSource.CreateNavigator();
Byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(navigator.OuterXml);

    // Create XmlDocument from the form XML
    XmlDocument doc = new XmlDocument();
    XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
    nsm.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-29T22:54:17");
    doc.LoadXml(navigator.OuterXml);

    // Load name information from the XML
    XmlNode nodeLastName = doc.SelectSingleNode(
                        "/my:RoomBooking/my:UserInformation/my:LastName", nsm);
    string name = (nodeLastName != null) ? nodeLastName.InnerText : string.Empty;
    XmlNode nodeFirstName = doc.SelectSingleNode(
                       "/my:RoomBooking/my:UserInformation/my:FirstName", nsm);
    string firstname = (nodeFirstName != null) ?
                                          nodeFirstName.InnerText : string.Empty;

    // Generate file name
    string filename = String.Format("{0}{1}_{2}.xml", name, firstname,
                                            DateTime.Now.ToString("yyyyMMdd"));

    // Open library and save XML
    SPFolder formLibrary = web.GetFolder(LIBRARY_NAME);
    formLibrary.Files.Add(filename, formBytes);

    web.AllowUnsafeUpdates = false;
}

Integrating InfoPath Forms with the Environment

InfoPath forms can be developed and designed independently of your SharePoint environment. If you need to load additional information from external sources into your form, you can call a web service or use other data connections. But as soon as your form is part of a more complex business process, you might need some additional information within your form that is provided by the business process, or you may need information from outside of InfoPath that is entered through a form. In some scenarios you will have to pass parameters from your SharePoint application to your form, or vice versa.

Property Promotion and Demotion of XML Documents

Using InfoPath forms in SharePoint and storing the forms in a forms library enables development of complex browser-based applications with a great user experience. The forms are well-integrated into SharePoint with the support of Forms Services, but all the information that was entered by the users is stored within the XML file. There seems to be no easy access from the SharePoint environment to this data. What if you want to create a view that shows all the room bookings for one particular room? Or what if you want to change single values in your XML file from SharePoint? Many of the great features SharePoint offers work with list columns but don't offer extensibility to access information within XML files.

To solve this problem, SharePoint and InfoPath support features called property promotion and property demotion. SharePoint allows you to define fields in your InfoPath form that will be automatically provided as a column in your SharePoint document library. SharePoint automatically propagates changes that are made in your document to the SharePoint column and vice versa. Property promotion involves extracting fields from XML documents and writing these values to columns in SharePoint document libraries. Property demotion, on the other hand, involves taking changes to the SharePoint column available in your XML form.

Property promotion and demotion work as follows: whenever a new or existing XML file is saved in the document library, SharePoint invokes a built-in XML parser on the XML file. When the document content type contains a column that maps a field in the XML document to a list column (via an XPath expression that is pointing to the XML field), this value will be promoted to the library. In the other situation, where the column in the library is updated, this XPath expression is used to demote the information to the XML file.

In the description of the XmlFormView earlier in this chapter, we showed a method to directly manipulate the form's XML structure, which could also be used to access form fields, but requires more effort.

Tip

You can find more details on property promotion and demotion on MSDN at http://msdn.microsoft.com/en-us/library/aa543481(office.14).aspx.

Configuring Promotion/Demotion Using InfoPath

When you are using the InfoPath Publishing wizard to publish your form template to SharePoint, you will encounter the dialog shown in Figure 15-30. In this dialog, you can add property promotion and demotion using the Add... button in the upper area of the wizard. In the upcoming dialog you can select a field from your main data source and specify the column name within the document library. InfoPath Forms Services will then create the necessary columns in the document library and store the XPath link to the referenced nodes in the column definition. The lower area is used for Web Part connection parameters (described next).

Configuring property promotion and demotion

Figure 15.30. Configuring property promotion and demotion

Configuring Promotion/Demotion Within a List Feature

When using InfoPath Designer to manage list propagation, the necessary settings and changes will only be made on the list to which the InfoPath file is published. For any other deployment scenario (such as a multistage development and production environment), you can describe list propagation together with your list using the schema.xml file. You can simply nominate the column that should be used for property promotion with an ID and Name attribute. In addition, you merely need to specify the Node attribute. This attribute takes an XPath expression pointing to the field within the XML file. This XPath expression will be used for promotion and demotion of properties. Listing 15-18 shows an example for a list definition that specifies some nodes in the RoomBooking form that will be promoted to the list.

To make sure that you are using the right XPpath expression, you can use InfoPath Designer: right-click the field in the Fields tree and select Copy XPath, which will generate the correct expression for you.

Example 15.18. Configuring Property Promotion and Demotion in a Feature Definition

<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint"
    Title="Order Requests"
    Direction="$Resources:Direction;"
    Url="OrderRequests" BaseType="1"
    EnableContentTypes="TRUE"
    AllowMultipleContentTypes="True"
    xmlns="http://schemas.microsoft.com/sharepoint/">
    <MetaData>
        <ContentTypes>
            <ContentType ID="0x01010100B3E78F42234547a580BDE72BCB3E650A" Name="Order Requests"
 Description="Request a new Order"
 Group="$Resources:Document_Content_Types" Version="1">
                <FieldRefs>
                    <FieldRef ID="{DDC3C6B7-C34A-4d5a-8355-DC4E81885C8D}"
                              Name="Title" />
          ...
                    <FieldRef ID="{6CE8A87B-0862-4d8d-891F-5CA9C16833D4}"
                              Name="Room" />
                    <FieldRef ID="{05F09611-7D5B-4bae-9FA5-3EC8402F7A00}"
                              Name="Date" />
                    <FieldRef ID="{2C1B30B7-AADC-434b-9F82-D70639B59AB1}"
                              Name="TimeBegin" />
                    <FieldRef ID="{52BBFDF2-3176-43d7-A4D2-EFFA78CCED33}"
                              Name="TimeEnd" />
                </FieldRefs>
                <DocumentTemplate TargetName="/FormServerTemplates/RoomBooking.xsn"
                />
            </ContentType>
        </ContentTypes>
        <Fields>
      ...
            <Field ID="{6CE8A87B-0862-4d8d-891F-5CA9C16833D4}" ShowInNewForm="FALSE" Type="Text" Name="Room" DisplayName="Room" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Room" Node="/my:RoomBooking/my:Schedule/my:Room" ></Field>
            <Field ID="{05F09611-7D5B-4bae-9FA5-3EC8402F7A00}" ShowInNewForm="FALSE" Type="DateTime" Name="Date" DisplayName="Date"
SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Date" Node="/my:RoomBooking/my:Schedule/my:Date" ></Field>
            <Field ID="{2C1B30B7-AADC-434b-9F82-D70639B59AB1}" ShowInNewForm="FALSE" Type="DateTime" Name="TimeBegin" DisplayName="TimeBegin" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="TimeBegin" Node="/my:RoomBooking/my:Schedule/my:TimeBegin" ></Field>
            <Field ID="{52BBFDF2-3176-43d7-A4D2-EFFA78CCED33}" ShowInNewForm="FALSE" Type="DateTime" Name="TimeEnd" DisplayName="TimeEnd" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="TimeEnd" Node="/my:RoomBooking/my:Schedule/my:TimeEnd" ></Field>
        </Fields>
    </MetaData>
</List>

This listing defines common attributes for the list, such as Title and Url. In the <MetaData> section, the content type and fields are specified. The ID of the <ContentType> element starts with 0x01010, which is the parent ID for form libraries. The <FieldRef> elements refer to the <Field> elements that are specified later using their GUIDs. The <Field> elements specify an additional attribute, Node, which contains the XPath to the field in the XML file of the InfoPath form. This node will be used to perform property promotion and demotion.

Web Part Connection Parameters

Web Parts on a page can be interconnected using connection parameters to pass values between them. Similar to property promotion, InfoPath fields can be promoted as Web Part connection parameters. This allows Web Parts to send data to or get data from a field in an InfoPath form without any further coding. Especially when using the newly introduced InfoPath Form Web Part, these connection parameters enable you to quickly interconnect your form with other SharePoint Web Parts. Figure 15-21, which was already described in connection with property promotion earlier, shows this dialog that allows you to add new Web Part connection parameters.

To specify Web Part connection parameters, you can use the Property Promotion category, accessible either through the Publishing wizard or the Form Options dialog. When adding new Web Part connection parameters, you will be asked to select the field you want to promote and enter a name for the parameter. Finally, you need to choose the parameter type: input, output, or inputoutput. Input parameters can be used to retrieve data from other Web Parts. Output parameters can send data to other Web Parts. If you want to do both, you must select "inputoutput."

Note

Remember that Web Part connection parameters cannot be used with sandboxed form templates, which contain managed code.

Passing Parameters from SharePoint to InfoPath Forms

When your form already exists, you can use property demotion to set fields in your form. But often you want to preload information in your form when a new form is created. In this case, you can pass parameters to your browser form using request parameters. If you write your own application page that hosts the XmlFormView, you can access the form's XML data and directly write parameters into the XML. But if you don't, request parameters might be the solution for you.

You can pass your additional parameters as so-called input parameters via HTTP request parameters. There are two ways to access these parameters:

  • Using the InfoPath InputParameters property

  • Directly accessing the HTTP request parameters

InfoPath offers access to input parameters either for InfoPath Filler forms or for browser-based forms. They are handled exactly the same way. In the load event you access the LoadingEventArgs parameter e and select the desired parameter using the [] selector:

String param = e.InputParameters["param"];

In this case, you don't have to deal with HTTP request parameters. But since your form is hosted inside a web page you can also read the HTTP request parameters from within your form template in the form code. All you need to do is add a reference to the System.Web assembly. Then you can access the QueryString collection of the HttpRequest to read all the parameters required to load data into the form. Of course, you can also access the other properties of the request (e.g., Url, Headers, UserAgent, LogonUserIdentity, and anything else that might be useful when programming your form). You can retrieve the browser session to exchange data between SharePoint and InfoPath. The next example demonstrates both ways to load data into your form using a request parameter. Instead of simply writing the value directly into the form, the parameter will be used to call a web service that is responsible for fetching the data that is required in the form.

To begin, add the following reference to your project, along with the using statement, to access the HTTP request:

using System.Web;

Now you can obtain the request parameters in your form-loading event to retrieve a parameter that identifies an item from the QueryString. With this itemid parameter, the GetItemData web service is called. The results are then stored into the form using XPathNavigator.

Example 15.19. Accessing Request Parameters in a Form Template

public void FormEvents_Loading(object sender, LoadingEventArgs e)
{
    // Get the request parameter using InputParameters:
    string itemId = e.InputParameters["itemId"];
    // Get the request parameter directly from the request:
    itemId = HttpContext.Current.Request.QueryString["itemId"];

    XPathNavigator form = MainDataSource.CreateNavigator();

    if (!String.IsNullOrEmpty(itemId))
    {
        // Set the parameter for the web service query
        DataSources["GetItemData"].CreateNavigator().SelectSingleNode(
            "/dfs:myFields/dfs:queryFields/tns:GetItemData/tns:itemId",
            NamespaceManager ).SetValue(itemId);

        // Query web service and create navigator
        DataSources["GetItemData"].QueryConnection.Execute();
        XPathNavigator itemdata = DataSources["GetItemData"].CreateNavigator();

        // Fill the Name field with the value from the web service
        XPathNavigator nodeName = form.SelectSingleNode(
"/my:ItemForm/my:Name", NamespaceManager);
        nodeName.SetValue(itemdata.SelectSingleNode(
"dfs:myFields/dfs:dataFields/tns:GetItemData/tns:GetItemDataResult/tns:ItemName",
            NamespaceManager).Value);

        // Fill the Price field with the value from the web service
        XPathNavigator nodePrice = form.SelectSingleNode(
            "/my:ItemForm/my:Price", NamespaceManager);
        nodePrice.SetValue(itemdata.SelectSingleNode(
"dfs:myFields/dfs:dataFields/tns:GetItemData/tns:GetItemDataResult/tns:ItemPrice",
            NamespaceManager).Value);
    }
}

Warning

As always when working with request parameters, keep in mind that they can be easily modified by users. You must use the same precautions as in any other web page when working with request parameters. Always check the validity of the data passed to your form.

Summary

This chapter described how InfoPath forms can be used to create professional SharePoint applications that handle complex user input. InfoPath 2010 has greatly improved browser support and is easier to use when designing forms for the SharePoint environment.

Starting with a description about the internals of the InfoPath form templates, this chapter covered all the topics a developer needs to understand when working with InfoPath forms. Although designing form templates may not be a common developer task, basic information on how to design a browser-enabled form template was provided, together with the different ways to deploy the results to SharePoint.

Programming InfoPath form templates offers developers a powerful way to integrate form templates into complex business processes and develop intelligent form templates. However, not only can you use custom code to enrich business logic within InfoPath form templates, but you can also use it to customize form template—hosting inside SharePoint. Along with some basic configuration tasks, this chapter described the possibilities for programmatically changing the behavior of InfoPath Forms Services within SharePoint.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.61