Event Handling In InfoPath

Within the InfoPath 2007, there is the option to handle events using an item called the Event Manager. Similar to the event receiver architecture provided by other facilities of SharePoint, the Event Manager provides mechanisms by which forms can provide and respond to event capturing. Writing code that is consumed by the Event Manager is done using Visual Studio Tools for Application (VSTA), and when choosing to program events off the InfoPath design surface it will attempt to open the VSTA IDE.

The Event Manager is called from the InternalStartup() method, which controls the events that are registered when a form is initially loaded. Each event that should be captured can be registered within the InternalStartup() method and then delegates can be constructed to encapsulate a reference to a method which handles the events tripped custom code.

There are several events that can be captured and managed when leveraging the Event Manager.

Event Capturing Available Through the Event Manager

Event Type
Event Capture
Control Event OnClick When a user clicks a control in InfoPath ClickedEventHandler(object sender, Microsoft.Office.InfoPath.ClickedEventArgs e)
Form Event OnSaveRequest When a user saves an InfoPath Form SaveEventHandler(object sender, Microsoft.Office.InfoPath.SaveEventArgs e)
Form Event OnContextChange When a user changes a Form Context, such as when a form is submitted SubmitEventHandler(object sender, Microsoft.Office.InfoPath.SubmitEventArgs e)
Form Event OnSign When a user signs an InfoPath form with a digital signature SignEventHandler(object sender, Microsoft.Office.InfoPath.SignEventArgs e)
Form Event OnMergeRequest When a user merges a set of InfoPath forms (merge operation) MergeEventHandler(object sender, Microsoft.Office.InfoPath.MergeEventArgs e)
Form Event OnSwitchView When an InfoPath view is changed (switch view operation) ViewSwitchedEventHandler(object sender, Microsoft.Office.InfoPath.ViewSwitchedEventArgs e)
Xml Event OnBeforeChange Before a passed XPath node is changed, wire an XML event XmlChangedEventHandler(object sender, Microsoft.Office.InfoPath.XmlEventArgs e)
Xml Event OnValidate When an XPath node is being validated, wire an XML event XmlChangingEventHandler(object sender, Microsoft.Office.InfoPath.XmlChangingEventArgs e)
Xml Event OnAfterChange After an XPath node is changed, wire an XML event XmlValidatingEventHandler(object sender, Microsoft.Office.InfoPath.XmlValidatingEventArgs e)
Registering View Delegate in InternalStartup()

Using the InfoPath event handlers is as straight-forward as the event receiver/listener architecture that is present with SharePoint content types and list definitions. The event being captured must be registered within the InternalStartup() method by standard declaration. Wiring an event to display a message box telling the user they are switching views requires registering the event first.


void InternalStartup(object sender, EventArgs e)   
((FormControl)sender).EventManager.FormEvents.ViewSwitched +=        new ViewSwitchedEventHandler(OnSwitchView);    

View Delegate
Once the handler has been registered within the InternalStartup() method, the event handler that it is called can be declared by a delegate.
public delegate void ViewSwitchedEventHandler(object sender,         Microsoft.Office.InfoPath.ViewSwitchedEventArgs e)  
MessageBox.Show(“You are switching InfoPath Views!”);  

With the event wired as such, whenever a user switches InfoPath views, a message box displays, confirming that they are switching views. More elegant event handlers could be developed depending on the event capturing logic that is required; however the overall concept remains the same.

By the same token, it is possible to validate the XML fields so a user entering null values into an InfoPath form is passed a message.

Register Event in InternalStartup()
First, register the XML event handler in the InternalStartup() method. Since it is an XML event, an XPath statement is required in order for InfoPath to know which control to validate against.
public void InternalStartup()
EventManager.XmlEvents[“/my:myFields/my:ProSharePoint2007Field “].Validating += new XmlValidatingEventHandler(ProSharePoint2007Field_Validating);
Once the event handler has been registered, the actual event logic can be wired to the event to be called when the XML event is tripped.
Validating a Null Value with Event Handling
Use a String.IsNullOrEmpty if check on the value being passed into the InfoPath control to verify a null entry. Otherwise, you can use the Errors.Add method in order to point each error to the XML node, or InfoPath field the error is associated with; in this case the ProSharePoint2007Field. The other error handling method in the below code is the Error.Delete method which removes the error handler if no errors are encountered in the InfoPath field. Any number of string comparison options that are available through the .NET framework could be leveraged if you’re looking for a more elegant error-checking mechanism.

public void ProSharePoint2007Field_Validating(object sender, XmlValidatingEventArgs e)


if (!String.IsNullOrEmpty(e.NewValue))    


Errors.Add(e.Site, “ProSharePoint2007Field “, “Null Values are not allowed!”);    




Errors.Delete(“ProSharePoint2007Field “);    





Working With InfoPath Controls on the Design Surface and Building a Basic InfoPath Form

The InfoPath design surface provides many methods to build and enhance an InfoPath form with custom actions such as conditional formatting, rules, and other formidable functionality. There are several options available from the control level menu that a developer can leverage to circumvent having to write custom code to achieve certain form tasks. We have already explored how to use a template part in order to build a reusable InfoPath form piece similar to user controls in Visual Studio development that can be dragged onto the InfoPath design surface after a user has imported the .XTP file. Building a custom form with the native InfoPath controls is no different, and can be accomplished within the same amount of steps. For our purposes, we will explore some of these inherent surface design options to create a simple form that will query user ID’s from a SQL database. It is important to realize that if extending this form to submit user ID’s to a database, a Web Service has to be generated for the database since a Web Form cannot submit to the SQL database directly, which is why in the Main Data Connection Details the Type is set to retrieve data from the database. Although all of the inherent features will not be presented, there are some indispensable pieces of functionality that are intuitive to use within an InfoPath form which can be seen in the following list

  • Changing Data Binding. When working with the data binding options on the InfoPath design surface, each of the controls is bound to certain fields within the data connection source. At times, it may be beneficial to change the binding of the control to a different field or group. Changing the data binding allows you a visual selection of the available fields and groups to which the selected control can append itself.
  • Conditional Formatting. Conditional formatting allows you to wrap logic around a control where the display formatting will be adjusted based on whether conditions are met. This same type of feature is available within SharePoint XSLT data views. Conditional formatting generally works by building up an XSL if/when statement that will output the control field data with the rule satisfaction criteria.
  • Data Validation. Data validation provides a method that the InfoPath control can use to verify that input data conforms to the rules implemented by the validation method.
  • Rules. A rule directs InfoPath to take an action when a specified condition is met. The first step in creating a rule is to give it a friendly name. Next, the conditions of the rule have to be set. Lastly, the actions that should be taken when the conditions are satisfied have to be set, which can be things ranging from displaying a message to a user to querying values out of a data source.
  • Programming. The programming menu allows developers to enter the VSTA development environment to add different event handlers to the InfoPath control, such as changing, validating, and changed events.
  • Logic Inspector. The logic inspector will allow you a view into all the different pieces of functionality that are set on a control such as validation, calculated values, rules, and programming.

In order to build the basic InfoPath ID form, select Design a Form Template from the File Menu. On the New Form Template screen you can create several types of templates based on the data connections that you wish to use which will create a boilerplate form.,. If desired, you could optionally create a blank InfoPath form template and add the relevant data connections in order to iterate through external datasource values, for more information regarding data connections see the next section. For the ID Form, the values are going to be stored in a SQL database and the form will be available to the users on the web. Select Database and Enable browser-compatible features only to ensure that we are backward compatible with the controls being used on the form (See Figure14-12).

Figure 14-12

Once the form has been defined with the data connection that it is going to used, InfoPath requires more information in regards to where the data should be massaged from. Although this type of activity is also manageable from code, choose the Select Database option in order to point to the ID database that only has an ID column in it. The SQL statement that is generated is fairly simple in order to get the values out of the database, it should be simply select “ID” from “dbo”.”ID” as “ID”. This will translate the ID query into the comparable XPath statements for the query fields /dfs:myFields/dfs:queryFields/q:ID/@ID and for the data fields /dfs:myFields/dfs:dataFields/d:ID/@ID.

When creating a new InfoPath Form based on a database connection, InfoPath will attempt to parse out methods that are required for you to interact with the database. You can either use the Run Query options which will allows you to run the desired query or simply Right-click on the ID field from the Data Source task pane, and select the control that you want to format the dataset as, in this case instantiating a control for the ID node. This will put the desired control onto the design surface based on the node from the desired dataset.

Once you can see that the form is receiving data from the SQL database correctly, you can use the other inbuilt InfoPath controls in order to enhance the form with validation and logic. Right-click on the ID Text Box control, and select Conditional Formatting. Using Conditional Formatting you can hide this control if there are no ID’s present when attempting to iterate through the dataset received from the database used in order to populate the control. In order to set up the rule, select the ID field and create the condition is blank. Afterwards, set the action to Hide this Control. (See Figure 14-15)

Figure 14-15

The final results should show the summary of the formatting conditions (See Figure 14-16).

Figure 14-16

Using Data Validation is a powerful option in order to verify the data that is placed into an InfoPath control. The data validation that is presented is very broad and powerful user interface piece of functionality in order to inform the user that the data that they are entering is of appropriate form. Right-click on the ID Text Box control, and select Data Validation. Once the validation dialog is open, setup a new validation rule that will display A bad ID has been returned message to the user when the number 1 is entered into the textbox (See Figure 14-17).

Figure 14-17

Then, as you can see when 1 is entered into the ID textbox it will inform the user that a bad ID has been entered (See Figure 14-18).

Figure 14-18

Rules are a compelling option that you can use in order to set a condition, and once the condition is met to execute some sort of action. The actions that can be taken when executing a rule are:

  • Show a Dialog Box Message
  • Show a Dialog Box Expression
  • Set a Fields Value
  • Query Using a Data Connection
  • Submit Using a Data Connection
  • Open a New Form To Fill Out

Similar to the Data Validation that was previously setup, rules are method that can be used in order to display a message box to the user if a certain condition is met, but can be extended much farther to include more custom logic. In order to see the execution of a more complex rule, examine the setting of an alternative control when the primary control value meets a condition. Drag another Text Box control onto the design surface, and set the Field Name property to Copy Test. Once this control is on the page, Right-click on the ID Text Box control, and select Rules. Create a new Rule that will trip when the Text Box value entered equals 1. In the rule dialog, set the action so that it will set the Copy Test field value to string Copy_Test when the condition is met (See Figure 14-19).

Figure 14-19

Once all of these settings are made on the TextBox, you can view the changes that have been made using the Logic Inspector which will provide an inventory of all of the customizations that have been made for the InfoPath form (See Figure 14-20). This list can then be printed out in order to maintain an audit interface of all the customizations that have been added

Figure 14-20


Architecture of the InfoPath Template (.XSN)

InfoPath templates use several child files and one overlying manifest bundled within an .XSN file.  However, there are both packaged and unpackaged InfoPath template states. One of the states is the form template, saved as the bundled .XSN file, which contains all InfoPath source files that although packaged can be extracted using either the InfoPath client or command line operations. Since an .XSN file is basically an archived cabinet file, you can unpackage an .XSN by using the following command; just replace the %system% placeholder with the system directory path and the %filename% placeholder with the path to the .CAB file:

%system%extrac32.exe /e /a %filename%
In order to repackage the extracted files into the .XSN cabinet, you can use the MAKECAB command form the command line as well. As a secondary option, to save the source files directly from the InfoPath client, you can simply use the Save Source Files option as opposed to saving the entire .XSN. There will be some file types that are not included in this breakdown, such as custom packaged .htm, JavaScript, VBScript, and compiled code files since they are unique to specific forms and are not universal across all .XSN’s.  By understanding the structure of what makes up an InfoPath form template, you can be more adequately prepared for programmatically manipulating form templates using programming approaches that provide more insight into the underlying plumbing of what builds the overall InfoPath template. Several ways to influence templates will be easily available which will allow you as a developer to develop scripting functions that you can optionally use in order to do actions such as bulk changes to XML attributes that make up the InfoPath file.
Manifest.XSF (Form Definition File
Manifest.XSF  is the overall manifest file, which although carries a unique file extension, is just a plain XML file. The most important function of the Manifest.XSFis providing the description of all the other child files that comprise the InfoPath template wrapped within the parent element, within  the child sub element. Each of the files that are included within the InfoPath form template are specified using the   element, which also further defines the properties of the files using. The manfiest.XSF also keeps other relevant global information regarding the template that can be modified by a developer such as menu items, along with some elements that are reserved by Microsoft, such as the element, and some elements that are typically not modified, such as the since InfoPath generated W3C.XSD schema document is typically used for traditional forms development.

During the course of creating a new custom form, you can modify some elements, although there are numerous elements that are not presented in the entire .XSF schema. The following table points out the relevant ones that appear within a default manifest.xml file when non-complex solutions are being used such as the case with the ID form being created, and some that you may typically manually modify.
Basic Elements of .XSF File


The view.xml file defines the available InfoPath views, back referenced by the manifest.XML in the element. The View files typically follow a numerically incremented pattern, where the first is view1.xml and the subsequent ones increase by an augmentation of one digit. The XSL will transform the selected XML input into an HTML view appending both the required CSS styles and the related InfoPath control values by using a xd:binding and xd:xctname attribute. The output when using the view.XSL file is a form that looks similar to how the InfoPath Form will be rendered and presented for web consumption.

Within the XSLT, the controls that are added to the template can be explicitly declared, by adding them within the XSLT file. Using the xd:binding attribute, InfoPath will take that element and push it to the XML source tree. Binding InfoPath controls such as the TextBox control will follow this schema.
The xd:binding attribute assimilates an XPath expression in order to bind the XML source tree, as shown in the my:pro2007Dev expression.
The xd:xctname attribute couples with the xd:binding attribute in order to define the type of control it is referencing. In the example code there is the reference to xd:xctname=”PlainText which means that the particular control is a TextBox InfoPath control.
The MySchema.XSD document controls the schema reference that is made from the manifest.XML declaration in the   element. This will default to the source files directory that the InfoPath solution file is unpackaged from. In the there are values which will classify the namespaces being used for the InfoPath solution package, and the rootSchema=”yes” attribute will by default  be set to the MySchema. The MySchema.XSD is based on the W3C XML Schema (WXS) which controls whether the InfoPath XML being passed in is valid or not. If the XML Schema file is not valid the form will be considered corrupt by the InfoPath Designer.

The sampledata.XML file specifies the default values that should be displayed to the user when first loading the InfoPath form. In the SampleData.XML file there is only the definition of the fields that are being used, their type, and the option to supply a default value by calling the element out by its name, along with specifying the value that should be set as the default. When you declare a new InfoPath control, it contains a self-terminating element at the top that you can set a default value for. To do so, simply state proSharePoint, which populates a TextBox control with string proSharePoint.
The template.XML file contains the XML information that is edited with InfoPath; however it’s only a sample illustration document provided within the overall InfoPath solution file. The template.XML provides an instance of the form will look to a user. The fields within the template.XML file are defined in the familiar my:field syntax.
There also is some interesting data that is included at the top of the document that related to problems that occur during the rendering of the InfoPath form. In the template.xml file there are the following header elements.
This section provides an important concept because it partially defines how InfoPath renders forms. By correlating an instance to a form, several form instances can be created out of a singular form template. The manifest location is kept in the href attribute, thereby allowing the template association over remote pipes so that a form template can be published to a collaborative location such as SharePoint and called be various segments. The element is known as the InfoPath Processing Instructions (PI’s), which is why there is a PIVersion numeric. The processing instructions define how to relate the data instances to the InfoPath form. If a form is not rendering correctly, InfoPath will look at the values as provided in the PI element in order to attempt to load the form within the InfoPath Smart Client.





Description of Element


Views that are available to the InfoPath Form. Any views placed within this element are the views used within the .XSN, pointing to the related View.XSL files. This and the are required elements in the .XSN without which the template is considered to be corrupted.
Form behavior when in InfoPath Design Mode and the application that was used in form creation. Can also house information that appears in design time in the InfoPath Smart Client.


Allows modification of the merge forms option, typically by using the useScriptHandler attribute to append event capturing.


Describes the overall update behavior if an antiquated forms requires increment to a new version.


Points to the template.xml included with the .XSN for when a user chooses to provide input to the form.


Provides the option of including packaged updates, such as forms services packs, for minor forms upgrades as they occur.