Partager via


Introduction to Programming in InfoPath 2010

Hello, my name is Christopher Brotsos, and I’m a Program Manager on the InfoPath team. In this post, I’m going to show you how to add business logic to your forms using managed code.

Imagine a scenario where the accounting department at Contoso, Inc. tracks corporate assets through an Asset Management System built on SharePoint. One module in the system allows employees to order office equipment such as laptops, conference phones, and ergonomic chairs through an InfoPath form. At first, the order form was built using only declarative logic. It could enforce required fields, surface validation messages, and submit the form to SharePoint without any code.

As the ordering process grew more complex, users started adding additional requirements to the system. The variety of inventory available to employees increased, so they wanted a way sort items by name and description real-time in the order form. Contoso also started shipping their office equipment out of three warehouses. This prevented the warehouse crew from fulfilling complete orders, and as such, the system needed to track shipping status and quantity of individual items in the order. To meet the new requirements, Contoso added the following features to the form:

  • A custom sort interface
  • Logic for managing complex data when the form is submitted
  • Logic to add items to a SharePoint list

Sort interfaces, sophisticated submit routines, and database (i.e. list) management are common requirements for forms. Fortunately, this functionality can be added to InfoPath forms with a few lines of code. Let me explain these features, the code required to build them, and the prerequisites for developing managed code in InfoPath in more detail.

Equipment Request Form

The employee orders module in the Asset Management system consists of three core components:

  1. A SharePoint form library, “Equipment Orders”, where users go to fill out the Equipment Order Request form shown below.
  2. A SharePoint list, “Equipment Inventory”, which stores the items available for users to order. This list contains fields specifying items’ names, descriptions, and quantities used to populate the Equipment Order Request form.
  3. A SharePoint list, “Equipment Shipping”, which stores a list of items ordered by users that have been scheduled for shipping. This list contains fields for the names and quantities of items being ordered as well as the name of the user who placed the order.

The Equipment Request Form enables users to sort through Contoso’s available inventory and submit a request to the warehouse for shipping.

Equipment Order Request Form

The order form is a repeating table, where each row in the table represents the name, description, and quantity of the item being ordered.

Equipment Order Request Form 

Sorting data in the form

The Equipment Order Form has a Picture Button Control displaying an arrow next to each of the column labels.

Equipment Order Request Form

The buttons are used to sort the order items in ascending order by the respective column. When the user clicks the button, the values in the selected column are compared, and the rows of data are sorted based on the comparison result.

The sorting routine in this example is based on a complete solution provided by Hagen Green. Read through his post to learn how to provide a descending sort which also takes localization and data types into consideration.

 private string GetValue(string xpath)
{
  // return the value of the specified node
  XPathNavigator myNav = this.MainDataSource.CreateNavigator().SelectSingleNode(xpath, NamespaceManager);
  if (myNav != null)
    return myNav.Value;
  else
    return "";
}
private void Swap(string xpath1, string xpath2)
{
  // swap two rows of the table 
  XPathNavigator item1 = this.MainDataSource.CreateNavigator().SelectSingleNode(xpath1, NamespaceManager);
  XPathNavigator item2 = this.MainDataSource.CreateNavigator().SelectSingleNode(xpath2, NamespaceManager);
  if (item1 != null && item2 != null)
  {
    // Make a copy of item1
    // Move item2 to item1
    // Make the original item2 be item1 that we cloned earlier
                
    XPathNavigator item1Clone = item1.Clone();
    item1.ReplaceSelf(item2);
    item2.ReplaceSelf(item1Clone);
  }
}
private void SortOrder(string sortBy)
{
  string itemsToSort = "/my:myFields/my:Order/my:OrderItem";
  XPathNodeIterator items = this.MainDataSource.CreateNavigator().Select(itemsToSort, NamespaceManager);
  if (items != null)
  {
    int numItems = items.Count;
    // basic bubble sort implementation
    for (int i = 1; i < numItems; i++) // xpath is 1-based
    {
      for (int j = i + 1; j <= numItems; j++)
      {
        // swap (i,j) if necessary
        string iValue = GetValue(itemsToSort + "[" + i + "]" + sortBy);
        string jValue = GetValue(itemsToSort + "[" + j + "]" + sortBy);
        if (String.Compare(iValue, jValue, true) > 0)                       
          Swap(itemsToSort + "[" + i + "]", itemsToSort + "[" + j + "]");
                        
      }
    }
  }
}
public void ItemNameSort_Clicked(object sender, ClickedEventArgs e)
{
  // Sort order by ItemName
  // Repeat this code for the other buttons
  string sortBy = "/my:ItemName";
  SortOrder(sortBy);
}

Managing complex data during submit and updating SharePoint lists using the SharePoint object model

The user is eventually going to finish selecting items and submit the order. Each item ordered through the form is handled independently because, for example, an item in the order may be delayed or shipped from a remote warehouse. So, we need submit logic which will break up the complex data (i.e. the repeating table of items being ordered) into individual rows, and add a shipping request to the Equipment Shipping list for each item-quantity pair. After an item is added to the Equipment Shipping list, a SharePoint workflow is used to track status and manage the Inventory Equipment list’s quantity values.

  1. The first thing you’ll need to do is use the Submit Options button on the Data tab in the ribbon to add a custom submit handler to your VSTA project.

    Submit Options

  2. Add a reference to Microsoft.SharePoint.dll to your VSTA project. This will allow you to develop code using the SharePoint object model. This DLL is installed in %CommonProgramFiles%\Microsoft Shared\Web Server Extensions\14\ISAPI with your licensed copy of Microsoft SharePoint Server.

  3. Add custom submit logic to create a SharePoint list item for each item in the order form. See the code below for an example, and notice the use of the ServerInfo class. The ServerInfo class is new to InfoPath 2010 and allows you to write portable code with relative references to SharePoint server URLs.

 

 public void FormEvents_Submit(object sender, SubmitEventArgs e)
{
  // Loop through each item-quantity pair in the order form.
  // Submit pairs to the Equipment Shipping list.
  // Note: Workflow will handle updating item quantities and track shipping status.
  using (SPSite mySite = new SPSite(ServerInfo.SharePointSiteUrl.ToString()))
  {
    using (SPWeb myWeb = mySite.OpenWeb())
    {
      XPathNodeIterator orderItems;
      if (myWeb != null && myWeb.Lists["Equipment Shipping"] != null)
      {
        SPList shippingList = myWeb.Lists["Equipment Shipping"];
        myWeb.AllowUnsafeUpdates = true;
        orderItems = this.MainDataSource.CreateNavigator().Select("/my:myFields/my:Order/my:OrderItem", NamespaceManager);
        if (orderItems != null)
        {
          while (orderItems.MoveNext())
          {
            // Add rows from the form where user selected an item and specified a quantity.
            string itemName = orderItems.Current.SelectSingleNode("./my:ItemName", NamespaceManager).Value;
            string itemQuantity = orderItems.Current.SelectSingleNode("./my:ItemQuantity", NamespaceManager).Value;
            if (itemName != string.Empty && itemQuantity != string.Empty)
            {
              SPListItem shipItem = shippingList.AddItem();
              shipItem["Title"] = itemName;
              shipItem["Quantity"] = itemQuantity;
              shipItem.Update();
            }
          }
        }
      //cleanup
      //signal successful submit
      //return
      myWeb.AllowUnsafeUpdates = false;
      e.CancelableArgs.Cancel = false;
      return;
      }
    }
  }
}

Along with the features covered above, you’ll find that code is useful for implementing complex data validation logic and managing content from multiple data sources. Such requirements are especially common when your forms are part of an advanced application. You can learn more about validation and working with the InfoPath DOM in our MSDN XmlEvent.Validating documentation and our post on working with InfoPath data sources programmatically. You can also review the InfoPath and SharePoint object models on MSDN for a more granular view into programming with InfoPath 2010.

If you’d like to get started with programming in InfoPath, then please read on. The rest of this post introduces our system requirements, integrated development environment, and programmability user experience.

How to add code to an InfoPath form

To add code to an InfoPath form:

  1. Make sure you meet the minimum system requirements.
  2. Install Visual Studio Tools for Applications (VSTA).
  3. Choose a programming language.
  4. Add event handlers and code.

Minimum system requirements

The minimum system requirement to get started with InfoPath 2010 development is Microsoft .NET Framework 2.0, but we suggest you install Microsoft .NET Framework 3.5 SP1 if you’re developing for the SharePoint platform. You can install all versions of Microsoft .NET Framework from http://www.microsoft.com/downloads.

Installing Visual Studio Tools for Applications

Visual Studio Tools for Applications (VSTA) is an optional installation component available in Microsoft Office 2010 setup. To install VSTA:

  1. Launch Office 2010 setup from your Office 2010 installation media or from the Control Panel Programs and Features application.
  2. If you’re installing a new copy of Office 2010, click the Customize button in the installer. If you’ve already installed Office 2010, choose the Add or Remove Features radio button in the installer.
  3. Set the Visual Studio Tools for Applications option to Run from My Computer and continue through the setup wizard.

Office Setup

Choosing a programming language

InfoPath 2010 allows you to program in C# and Visual Basic .NET. If you want to program with Visual Basic, you do not need to do anything to select your programming language when designing InfoPath 2010 compatible forms. If you plan on programming with C#, or adding code to InfoPath 2007/2003 compatible forms, you can change the programming language by clicking the Language button in the Code group of the Developer tab.

Developer Tab

After you click the Language button, you can change your programming language by using the Form template code language drop down:

Form Options

Hint: You can change the default language for InfoPath 2010 compatible forms by using the Options menu in the Backstage.

  1. Click the File > Options tab
  2. Click the More Options button in the General category of the InfoPath Options dialog
  3. Change the Programming language dropdowns in the Programming Defaults section of the Design Options

Options

Adding event handlers

The Developer tab is the primary entry point for programming in InfoPath 2010. It’s designed to help you add event handlers compatible with the controls and mode of the form you are designing. For example, if you don’t have a control selected on your form view, then you’ll only be able to select the events that apply to the entire form. Notice that the Loading and View Switched event below are enabled, but the entire Control Events group is disabled.

Developer Tab

But, as soon as I select a text box on the form, the Control Events group lights up.

Developer Tab

Notice that the Sign, Context Changed, and Changing events are disabled in both screenshots of the Developer tab. That’s because I’m working with a browser compatible form, and those events are only available for InfoPath Filler forms.

Note: You’ll find a table of all events, and their compatibility, towards the end of this section.

Certain control and form programming events can be accessed through buttons on other tabs in the ribbon. If you add a Picture Button control on the form view, highlight the button, and then click on the Properties tab then you’ll find the Custom Code button enabled. Clicking the Custom Code button in the ribbon will add an OnClick event for the Picture Button control.

Custom Code Button

In the Equipment Order Request form, we added a Submit event handler to add items to a SharePoint list. To do this, navigate to the Data tab, and click the Submit Options button in the Submit Form group.

Submit Options Button

This will launch the Submit Options dialog where you can check “Allow users to submit this form”, “Perform custom action using Code”, and then click the Edit Code button.

Submit Options

The Fields task pane is another main entry point to add event handlers. In the next screenshot, I access the Validating and Changed events for ItemDescription by right clicking the field in the Fields task pane and scrolling through its context menu.

Fields Taskpane

The following tables provide a list of all events and compatibility in InfoPath 2010. Note that InfoPath forms trigger three types of events: Form Events, Data Events, and Button Events. Aside from the button event, InfoPath event handling is different from other web programming paradigms (e.g. WinForm and HTML forms); events are fired when the data changes, not when control state changes. As such, you should consider the optimal configuration for your forms’ post-back settings to provide the best performance while still ensuring that events get fired when necessary. See our performance post on MSDN to learn more about general performance and event handler post-backs.

Tables

After you’ve designed your form and authored the source code, the final step is to publish the form. Your InfoPath form with code can be published to SharePoint and to client machines, but you need to make a security decision before you publish: configure the form as domain trust or full trust.

 

Domain trust forms can be published to SharePoint as Sandboxed Solutions directly from the InfoPath 2010 Designer. With Sandboxed Solutions, SharePoint Server farm administrators can restrict the resources available to the code and developers cannot access resources subject to operating system security. This establishes a safe environment where Site Collection administrators can publish code to SharePoint without the overhead of administrator approval! For more details about Sandbox Solutions (and another method for sorting repeating tabular data), see our Introduction to Sandboxed Solutions post from Phil Newman.

Note: Publishing full trust forms to a client-side environment requires that the form is signed with a code-signing certificate or installed through a custom MSI built in Visual Studio. Publishing a full trust form to SharePoint requires a farm administrator to activate the solution through the SharePoint Central Administration portal.

Best Practice: You should always use the lowest level of trust possible when publishing forms.

Summary

Most forms you design with InfoPath 2010 are not going to require code, but when they do, just install Visual Studio Tools for Applications and you’re ready to start programming. To add code, select the language of your choice, and use entry points in the Ribbon and Fields task pane to automatically insert event handlers. Finally, decide whether or not your form requires full-trust, and publish it to SharePoint or a client environment accordingly. If you’re interested in learning more about the InfoPath and SharePoint programmability, please visit http://www.msdn.com and keep checking for updates here on the InfoPath blog.

Comments

  • Anonymous
    April 23, 2010
    Is there any good reason why Visual Studio 2010 does not support InfoPath development any more? Simon

  • Anonymous
    April 26, 2010
    Simon, thanks for your question. We want everybody who works with InfoPath 2010 to be able to leverage all three versions of our managed OM, the optimized design experience, and the best publish story from a single development environment that ships with Office; VSTA is that story. That said, we’d love to hear about your experience and what type of InfoPath development projects you work on. In particular, do you have Visual Studio Tools for Office projects that you need to migrate or do you need additional guidance?  If so, feel free to start a thread on http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010customization/threads.

  • Anonymous
    July 26, 2010
    Infopath 2007 Form Template project type is not available in VS2010 ??!! - any plan for its future release?

  • Anonymous
    July 26, 2010
    Anyone can help to address this issue: social.msdn.microsoft.com/.../1a77db33-6bcd-44f2-84a5-e4f89b8b8a7b

  • Manifest.xsf either not opened or crash VS2008 when try to open it -- HELP!!!
  • Anonymous
    August 03, 2010
    Hello Chris, First thanks for this great article ! I have problem publishing forms with code (sandboxed solution) on my dev farm installed on windows 7 (standalone install). The sandboxed solution cannot be deployed. If I do the same on another farm (Windows 2008 R2 farm install) everything works fine. Is there any know issue with Windows 7 ? regards, Ludovic,

  • Anonymous
    September 06, 2010
    Hi, Can you send me a VB code to save to a Access table?. (when you define 2 related tables how principal connection, the send using data base disapear.) Thanks. rvalle@sefin.gob.hn

  • Anonymous
    November 01, 2010
    Very well presented! Good for quick review of the basic features!! Thanks.

  • Anonymous
    November 19, 2010
    Everybody who works with InfoPath should not have to use the same version of InfoPath. The idea that all Microsoft customers must use the same version of a product to have an optimized design experience is a bit like saying that there is no such thing as a product version. An optimized experience is one that fits with the developer's platform tools and strategies. When libraries created by a developer are unavailable for newer solutions, the workflow is diminished. The same issue exists for SQL server. VSTA NEEDS to be brought up to the latest build of Visual Studio and this NEEDS to happen in order for customers (like me) to adopt it as a solution and developer "story". I wouldn't be looking to "Migrate" so much as begin working with VSTA. If your "story" is about excluding customers who are wise not to constrain their development paradigm with dated development tools, then maybe a good discussion topic for the forum would be, "how some teams at Microsoft love to ignore the customers".  Just say'n. ;) The same 'story' exists with Workflow foundation and .NET 4.0 on SharePoint 2010. WPF and Blend seem to stay up-to-date on these versions, so what's the problem? I hope you don't take the feedback personally, but instead really think about the way your team and others in the office teams have isolated themselves from the Visual Studio tech strategy and frameworks.

  • Anonymous
    November 19, 2010
    Everybody who works with InfoPath should not have to use the same version of InfoPath. The idea that all Microsoft customers must use the same version of a product to have an optimized design experience is a bit like saying that there is no such thing as a product version. An optimized experience is one that fits with the developer's platform tools and strategies. When libraries created by a developer are unavailable for newer solutions, the workflow is diminished. The same issue exists for SQL server. VSTA NEEDS to be brought up to the latest build of Visual Studio and this NEEDS to happen in order for customers (like me) to adopt it as a solution and developer "story". I wouldn't be looking to "Migrate" so much as begin working with VSTA. If your "story" is about excluding customers who are wise not to constrain their development paradigm with dated development tools, then maybe a good discussion topic for the forum would be, "how some teams at Microsoft love to ignore the customers".  Just say'n. ;) The same 'story' exists with Workflow foundation and .NET 4.0 on SharePoint 2010. WPF and Blend seem to stay up-to-date on these versions, so what's the problem? I hope you don't take the feedback personally, but instead really think about the way your team and others in the office teams have isolated themselves from the Visual Studio tech strategy and frameworks.

  • Anonymous
    December 06, 2010
    I created an InfoPath form similar to this for a SharePoint 2010 environment (I did not bother with sorting as I am focusing on the submission code). Once the form was working properly, I published it to a client machine and then later to a SharePoint form library.  In both cases, when I tested the form on a machine that did not have SharePoint installed, the form loaded properly but threw the following error when the submit event handler was called:  "System.IO.FileNotFoundException Could not load file or assembly 'Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies." The laptops that will be running the final project will not have SharePoint installed and will be working offline more often than not.

  • Anonymous
    December 21, 2010
    The comment has been removed

  • Anonymous
    April 14, 2011
    Who can I contact in Microsoft to get InfoPath developments integrate back in to Visual studio 2010? I had a BMW in InfoPath 2003 and 2007, now I’m getting a FORD. Classic Microsoft!

  • Anonymous
    December 01, 2011
    When I am trying to connect SPsite .. get error -- .net - FileNotFoundException with the SPSite constructor ( can't have 64bit platform option in VSTA)

  • Anonymous
    December 11, 2011
    System.IO.FileNotFoundException in vsta infopath 2010 , I am struggling issue from longtime. working with admin farm and system. database owner access. thanks

  • Anonymous
    January 27, 2012
    I cannot figure out why the custom button I created does not allow me to click on Custom Code in the ribbon.  Is there a setting I can toggle to enable this?

  • Anonymous
    January 27, 2012
    Hi "CustomCodeButton", My first thought is that the programmability option/VSTA (Visual Studio Tools for Applications) is not installed on your computer. What happens if you try this key combination: ALT + SHIFT + F12 Does it launch the VSTA code editor or do you get a message about VSTA not being installed? If it is the latter, then go to your Programs and Features (Add/Remove Programs in XP) applet in the Control Panel, click the Change button for your Office installation and set InfoPath to "Run All from My Computer" - this should install all options. Scott

  • Anonymous
    February 01, 2012
    I have the same problem. When I issue Alt-Shift-F12, nothing happens. What SHOULD happen?

  • Anonymous
    February 01, 2012
    The comment has been removed

  • Anonymous
    May 02, 2012
    Can I use Infopath Full Trust for SharePoint State Machine workflow if publish to a network?

  • Anonymous
    May 21, 2012
    I also miss the InfoPath project type in Visual Studio 2010. I still keep Visual Studio 2008 and InfoPath 2007 for custom forms development. I feel like Visual Studio 2010 / InfoPath 2010 have taken a step backwards in forms development.

  • Anonymous
    August 02, 2012
    I an not able to install VSTA for Infopath 2010. All the requeirements appear to be satisfied.

  • Microsoft .NET Framework 2.0 Service Pack 2
  • MSXML 4.0 SP2 (KB941833)
  • MSXML 4.0 SP2 (KB954430)
  • MSXML 4.0 SP2 (KB973688)
  • MSXML 6.0 Parser (6.10.1129.0). Please advice me some help.
  • Anonymous
    September 06, 2012
    This might not be the right place to ask, though I have looked around. A question regarding forms and compatiblity- A coworker designed a very useful form; however it was made using Infopath 2007. Now that Infopath 2010 is here, an entire section of our team cannot use the form. Is there a way to save the form/convert it so that my coworker doesn't have to recreate it from scratch? I'm reading up on the Compatiblity Pack, but I'm not sure if that addresses our issue. Thank you for any clarity you can provide!

  • Anonymous
    September 10, 2012
    Hi RTractor, If the form template (the XSN file) was created in InfoPath 2007 and saved in the 2007 format, then anyone with InfoPath 2010 should be able to open, edit, etc. that form without issue. You should not need to recreate anything to get it to work for users with InfoPath 2010. Are they getting an error? What behavior are they experiencing? Scott

  • Anonymous
    April 08, 2013
    After you’ve designed your form and authored the source code, the final step is to publish the form. Your InfoPath form with code can be published to SharePoint and to client machines, but you need to make a security decision before you publish: configure the form as domain trust or full trust.

  • Anonymous
    September 11, 2013
    Microsoft Developer's Network Blog is a representation of it's products.  Nice framework, but they're not getting the picture... literally.

  • Anonymous
    November 28, 2013
    is it possible to submit n normal blank infopath form's content to a list on sharepoint (NOTE: Not a list form)

  • Anonymous
    April 16, 2014
    asd

  • Anonymous
    July 31, 2014
    Which version of Visual Studio do I use to program code into InfoPath? There are these versions: Visual Studio Express 2012 for Windows 8 Visual Studio Express 2012 for Web Visual Studio Express 2012 for Windows Desktop Visual Studio Team Foundation Server Express 2012 Which one for InfoPath? I also know that you need to install the resources pack.

  • Anonymous
    October 17, 2014
    I'm able to interrogate lists on my SharePoint (Foundation!) 2010 server using code in VSTA, but, not using the SharePoint dll described above (I get the IO.FileExceptions, too) Instead, I had to reference the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime libraries to leverage the client object model.

  • Anonymous
    November 07, 2014
    Hi, I developed a customized solution in infopath using vb.net. My form connects to sql server through data connection. Can I get the steps to publish my customized form. As I am getting lots of errors and share point team says that customized coding solutions need administrative privileges n take lots of downtime.... Can u please assist me steps if u choose low security to publish the form on share point.... Please would really appreciate it