Microsoft InfoPath 2010
The official blog of the Microsoft InfoPath team

  • Microsoft InfoPath 2010

    Use Visual Studio to create InfoPath forms… without code

    • 11 Comments
    Although the primary purpose of Visual Studio 2005 Tools for Office (InfoPath 2007 Support) is to add C# and Visual Basic code to your InfoPath form template, you can still take advantage of hosting InfoPath inside Visual Studio to design forms that don't have any code.
     
    When you create a new InfoPath form template project in Visual Studio, by default, it will be created with code enabled.  To obtain a form without code, you need to explicitly remove the code from the form by using the remove code button in the programming tab of the form options dialog.
     
     
    After clicking on this button, you might be confused to see that the code file is still present in the project.  Don’t worry about this.  When you build the project, the hosted designer will not add the output assemblies to the form template.
     
    How it works
    After a new project is created, the “enabled” attribute of the “managedCode” element in the manifest.xsf defaults to “yes”.  Clicking the remove code button sets this attribute to “no”.
     
    <xsf2:managedCode … enabled="no"></xsf2:managedCode>
     
    This attribute is set back to “yes” when you insert an event handler using the hosted InfoPath designer.
     
    After a success build, the output assemblies will only be included with the form template when this attribute is set to yes.
     
    - Gary
    Software Development Engineer
  • Microsoft InfoPath 2010

    Another Way of Sorting Repeating Data

    • 12 Comments

    If you have ever attempted to sort repeating node data (i.e. a Repeating Table or Repeating Section) on an InfoPath form, you will find this functionality is not available through the UI. However, using .NET classes you can easily implement a sorting routine that will work in both client and browser scenarios. We discussed one way to make this happen through custom code in a recent article; this post will show a different way to make it happen. We will take a look at how to implement this functionality along with taking advantage of some new features in InfoPath 2007:

    • Dynamic button labels
    • Complex default value on the Button label to change the caption based on the sort order of the selected field (discussed in this article)

    In this sample scenario, let’s assume you are capturing the following data in a Repeating Table:

    • Last Name (name: LastName)
    • First Name (name: FirstName)
    • Age (name: Age)

    In addition, you want to allow your users to select the field they want to sort on (using a button in the column header) and clicking the button will toggle the sort between Ascending and Descending. Here is a sample form showing those options:

    ** NOTE: Notice the “(Asc)” in the Last Name button label? We’ll show you how to do that at the end of this post!

    The data structure for the above sample is as follows:

    So in this scenario, the user would simply click the button above the field they want to use to sort the data and by default, the first click would sort the data in Ascending order and clicking it again would sort the data in Descending order. Let’s now go ahead and take a look at the code on the click event of the buttons that implements this functionality.

    When each button is clicked, the first thing we do is set the value of the SortOrder and SortField nodes. For ease of implementation, we created a “SpecifySortOptions” procedure that is called from the click event of each button:

    SpecifySortOptions("LastName",XmlDataType.Text,e.ControlId);

    When each button is clicked we call this procedure passing it the field we want to use for sorting (in this case, LastName), the data type of this field (XmlDataType.Text) and the ControlID of the button that was clicked. (The ControlID is used in the Expression for the Default Value property of each button to determine how to change the label.)

    Here is the SpecifySortOptions procedure:

    public void SpecifySortOptions(string SortField, XmlDataType dataType, string ControlID)

    {

    //Create Navigator objects for the main DOM and

    //for the SortOrder and SortField fields

    XPathNavigator xn = this.MainDataSource.CreateNavigator();

    XPathNavigator xnSortOrder = xn.SelectSingleNode("/my:myFields/my:SortOrder", this.NamespaceManager);

    XPathNavigator xnSortField = xn.SelectSingleNode("/my:myFields/my:SortField", this.NamespaceManager);

     

    //Check to see if the value of the SortField is equal

    //to the ControlID that we passed to this procedure. If

    //it is the same and the SortOrder field is an SortOrder

    //emptry string or is set to "Desc" then set the field to

    //"Asc". If the SortField value does not equal the

    //ControlID that we passed to this procedure, then that

    //would mean either the SortField is an empty string or

    //it was set to another field - either way, we will

    //then want the SortOrder value to be "Asc"

    if (xnSortField.Value == ControlID)

    {

       if (xnSortOrder.Value == "" || xnSortOrder.Value == "Desc")

          xnSortOrder.SetValue("Asc");

       else

          xnSortOrder.SetValue("Desc");

    }

    else

       xnSortOrder.SetValue("Asc");

     

    //Call the SortTheData() procedure passing in the values

    //specified above

    SortTheData(SortField, xnSortOrder.Value, dataType);

     

    //Set the SortField value to the current ControlID

    xnSortField.SetValue(ControlID);

    }

    After calling the SpecifySortOptions procedure from the click event of each button, this procedure calls the SortTheData procedure, which accepts a string value for the sort field (strSortField), a string value for the sort order (strSortOrder) and an XmlDataType value (dataType) for the type of data being sorted. This is the code that will actually perform the sorting.

    The first thing we need to do is this procedure is create “XPathNavigator” objects for the main DOM:

    //Create a Navigator object for the main DOM

    XPathNavigator xn = this.MainDataSource.CreateNavigator();

    We then will create an XmlSortOrder object so we can specify either an Ascending or Descending sort. In this sample, we will specify an Ascending sort as the default; however, we will check the value of strSortOrder and if this is set to “Desc”, change the XmlSortOrder object accordingly:

    XmlSortOrder sortOrder = XmlSortOrder.Ascending;

    if (strSortOrder == "Desc")

    sortOrder = XmlSortOrder.Descending;

    To actually perform the sort, we will be using the “AddSort” method of an XPathExpression object – as such, we need to create an XPathExpression object for the repeating (group) node that we are going sort:

    XPathExpression xe = xn.Compile("/my:myFields/my:group1/my:group2");

    Now we can use the AddSort method on the Expression object using the field name (strSortField) that we passed into this procedure, the sort order using the sort order object (sortOrder) we created above and the data type using the data type object (dataType) we passed into this procedure:

    xe.AddSort("*[local-name()='" + strSortField + "']", sortOrder, XmlCaseOrder.None, "", dataType);

    We need to specify a NamespaceManager for the Expression object and for this we will use the SetContext method:

    xe.SetContext(this.NamespaceManager);

    The next step is to create an XPathNodeIterator object, passing it our XPathExpression object, so we can iterate all the nodes now that they are sorted - in addition, we will use this object (in the lastNode expression below) to get a count of the total nodes in this repeating group:

    XPathNodeIterator xi = xn.Select(xe);

    In the end, the way this procedure works is to delete the existing “un-sorted” nodes and add back the “sorted” nodes via the XPathNodeIterator object. So the next step is to now delete the existing “un-sorted” data. To do this, we will create XPathNavigator objects to reference the first and last nodes in this repeating group and then use the DeleteRange method to delete those nodes:

    XPathNavigator firstNode = xn.SelectSingleNode("/my:myFields/my:group1/my:group2[1]", this.NamespaceManager);

    XPathNavigator lastNode = xn.SelectSingleNode("/my:myFields/my:group1/my:group2[" + xi.Count + "]", this.NamespaceManager);

    firstNode.DeleteRange(lastNode);

    At this point, we have the sorted data in memory and the un-sorted data has been removed so we are ready to add that sorted data back to the form. For this process, we will use the XPathNodeIterator object we created earlier to iterate over the nodes.

    while (xi.MoveNext())

    {

    //Create string variables to hold the values of each field

    //as we iterate the nodes

    string strLastName = xi.Current.SelectSingleNode("my:LastName", this.NamespaceManager).Value;

    string strFirstName = xi.Current.SelectSingleNode("my:FirstName", this.NamespaceManager).Value;

    string strAge = xi.Current.SelectSingleNode("my:Age", this.NamespaceManager).Value;

     

    //Call the AddNewRow method to append a new row

    // to the repeating group

    AddNewRow(xn.SelectSingleNode("/my:myFields/my:group1", this.NamespaceManager));

     

    //Since we are continually appending new rows, the 

    //"last" row will always be the one where we need

    //to set the values - so here we will create a

    //Navigator object for this newly added row - we

    //will use this for setting the field values below

    XPathNavigator xnNewRow = xn.SelectSingleNode("/my:myFields/my:group1/my:group2[last()]", this.NamespaceManager);

     

    xnNewRow.SelectSingleNode("my:LastName", this.NamespaceManager).SetValue(strLastName);

    xnNewRow.SelectSingleNode("my:FirstName", this.NamespaceManager).SetValue(strFirstName);

     

    //Since the Age field is numeric, it will contain

    //the "nil" attribute. We need to remove this

    //arrtibute prior to programmatically setting the

    //value. To do this, we'll call the DeleteNil

    //procedure passing it the node that contains

    //(or may contain) the nil attribute

    DeleteNil(xnNewRow.SelectSingleNode("my:Age", this.NamespaceManager));

     

    //Now we can set the value of the Age field

    xnNewRow.SelectSingleNode("my:Age", this.NamespaceManager).SetValue(strAge);

    }

    In the while loop above, we used the “AddNewRow” and “DeleteNil” procedures – these are documented below:

    public void AddNewRow(XPathNavigator docXN)

    {

    //Create a Navigator object to reference the node

    //we will be adding. To do this, we can use the

    //templates' "Manifest.xsf" file to get the

    //appropriate node to add. As you can see, this is

    //specific to the control's "name", which you can

    //get from the Advanced tab on the Properties window

    //for the repeating control. Once you have this,

    //use the "Save As Source Files" command from the 

    //File menu in InfoPath and locate the appropriate

    //expression in your Manifest.xsf file

    XPathNavigator xnNode = this.Template.Manifest.SelectSingleNode("//xsf:xDocumentClass/xsf:views/xsf:view/xsf:editing/xsf:xmlToEdit[@name='group2_1']/xsf:editWith/xsf:fragmentToInsert/xsf:chooseFragment/my:group1", this.NamespaceManager);     

     

    //Append the node from the Manifest file to the main DOM

    docXN.SelectSingleNode("/my:myFields/my:group1", this.NamespaceManager).AppendChild(xnNode.InnerXml);

    }

     

    public void DeleteNil(XPathNavigator node)

    {

    //Check to see if the nil attribute exists

    //and if so, delete it

    if (node.MoveToAttribute("nil", http://www.w3.org/2001/XMLSchema-instance))

        node.DeleteSelf();

    }

    And that’s it! You now have the functionality of sorting data in a repeating node. For reference, the complete code for this sample is attached.

    Now – about that button label…how did we do that??!

    With InfoPath 2007, we have a new feature that allows you to specify a dynamic value for the button label. To do this, simply click the “fx” button next to the label property and you can choose to use an expression of a field/group from your form:

    However, for this sample the conditional logic for the button label is quite complex: we need to determine which button was clicked and whether we should show “(Asc)” or “(Desc)” next to the correct label. For this, we used the process demonstrated in this blog post: Conditional Default Values.
    So here is the logic that needed to be implemented when each button is clicked; for example, for the Last Name button:

    • See if the SortField value (which is set to a button’s ControlID in the SpecifySortOptions procedure) is equal to the clicked button’s ControlID and if the SortOrder value is either an empty string or equal to “Asc”
      • If it is, then set the label to: Last Name (Asc)
    • See if the SortField value is equal to the clicked button’s ControlID and the SortOrder value is “Desc”
      • If it is, then set the lable to: Last Name (Desc)
    • If neither of the above are true, then a different button must have been clicked so set the label to: Last Name

    This is the logic that needs to be implemented for each button. Here is a sample expression for the LastName field:

    concat(substring("Last Name (Asc)", 1, ((my:SortOrder = "" or my:SortOrder = "Asc") and my:SortField = "btnLastName") * string-length("Last Name (Asc)")), substring("Last Name (Desc)", 1, (my:SortOrder = "Desc" and my:SortField = "btnLastName") * string-length("Last Name (Desc)")), substring("Last Name", 1, not(my:SortField = "btnLastName") * string-length("Last Name")))

    Each of the above “substring” expressions are tested in order – so if the SortOrder field does not equal an empty string or does not equal “Asc” and the SortField value does not equal “btnLastName” then we test the next condition. If the SortOrder value does not equal “Desc” and the SortField value does not equal “btnLastName” then we test the last condition. And here we only need to check the value of my:SortField – if this does not equal “btnLastName” then we know a different button was clicked and we only want the label to display “Last Name”.

    So there you have it! A way to sort data in your repeating table and a really cool way to let the user know which field they clicked for sorting and in which order the data has been sorted!

    ** NOTE: It seems we may have a bug with our expression box in that it will accept the entire conditional statement noted above but once you close and re-open the box, the string gets truncated. Once you have this working, you may want to keep that expression saved in a text file.

    Scott Heim
    Support Engineer

  • Microsoft InfoPath 2010

    InfoPath 2003 Toolkit for Visual Studio 2005 Beta 2

    • 1 Comments

    The InfoPath 2003 Toolkit for Visual Studio .NET 2003 has been updated for Visual Studio 2005 and is included as a separate install in Visual Studio Tools for Office 2005 Beta 2. It will automatically upgrade Visual Studio .NET 2003 projects so you can leverage your existing work.

    “Support for InfoPath means you can add business logic to your form using managed code instead of script. Managed code allows you to use the Microsoft .NET Framework common language runtime (CLR) to write code in Microsoft Visual C# or Microsoft Visual Basic, and to make calls into the .NET Framework class library for advanced tasks such as digital signature processing and encryption/decryption. Visual Studio integration includes F1 Help support, full-featured debugging, and Microsoft IntelliSense in the code editor. IntelliSense provides statement completion, members lists, and inline parameter information on the InfoPath object model.”
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_vsto2005_ta/html/OfficeWhatsNewInVSTO2005

    Here’s how to get it:

    MSDN Subscribers

    Log into MSDN Subscriber Downloads at http://msdn.microsoft.com/subscriptions/

    On left hand side go to:

    Developer Tools / Visual Studio 2005 / Visual Studio 2005 Beta 2 / English / Office InfoPath 2003 Toolkit for Visual Studio 2005

    Non-MSDN Subscribers

    Go here: http://lab.msdn.microsoft.com/vs2005/get/

    Click “Order Visual Studio Beta 2” to get it on CD while supplies last.

    The InfoPath Toolkit will be on its own CD in that set.

  • Microsoft InfoPath 2010

    Add items to a SharePoint list using managed code

    • 16 Comments

    In this video demo, Phil Newman shows how you can write managed code in an InfoPath form to add items to a SharePoint list, and then publish this form as a sandboxed solution to SharePoint.

    In InfoPath 2010, forms with code can now be published directly to SharePoint without requiring the farm administrator to approve and upload them! These forms run in a sandboxed environment which protects other resources on the SharePoint server from malicious code.

    Get Microsoft Silverlight

    For more details on publishing InfoPath forms with code as sandboxed solutions to SharePoint, see Phil’s earlier post Introduction to Sandboxed Solutions - Sort data in repeating tables using managed code.

    Here’s the code that was used in this demo:

    NOTE: To develop code using the SharePoint object model, you need to add a reference to Microsoft.SharePoint.dll to your VSTA project. This DLL is installed in %CommonProgramFiles%\Microsoft Shared\Web Server Extensions\14\ISAPI with your licensed copy of Microsoft SharePoint Server.

    public void school_Changed(object sender, XmlEventArgs e)
    
    {
    
      using (SPSite FormSite = new SPSite(ServerInfo.SharePointSiteUrl.ToString()))
    
      {
    
        using (SPWeb FormWeb = FormSite.OpenWeb())
    
        {
    
          //Get the list and query for the item - "Schools" is the name of the list I am retrieving
    
          SPList LookupList = FormWeb.Lists["Schools"];
    
          SPQuery MyQuery = new SPQuery();
    
          //"Title" is the field where I keep the school name
    
          ///my:myFields/my:school is the xpath to the school field
    
          MyQuery.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + GetDomValue("/my:myFields/my:school") + "</Value></Eq></Where>";
    
          SPListItemCollection ReturnedItems = LookupList.GetItems(MyQuery);
    
          //Add the item to the lookup list if no items were returned in the query
    
          if (ReturnedItems.Count == 0)
    
          {
    
            SPListItem NewItem = LookupList.Items.Add();
    
            ///my:myFields/my:school is the xpath to the school field
    
            NewItem["Title"] = GetDomValue("/my:myFields/my:school");
    
                            
    
            //Set AllowUnsafeUpdates = true to update the database
    
            FormWeb.AllowUnsafeUpdates = true;
    
            NewItem.Update();
    
            FormWeb.AllowUnsafeUpdates = false;
    
          }
    
        }
    
      }
    
    }
    
    private string GetDomValue(string XpathToGet)
    
    {
    
      return this.CreateNavigator().SelectSingleNode(XpathToGet, this.NamespaceManager).Value;
    
    }
  • Microsoft InfoPath 2010

    Layout Tips & Tricks

    • 9 Comments

    2D vs. Flow

    One of the first things that experienced form designers will notice when using InfoPath is that layout of controls is not on a 2D design surface – it’s what we call “flow-based”. Controls function like images – or even character glyphs – in an application like Word. You can drag them around and insert them between words and use blank lines or spaces for positioning. To those designers who are used to precise layout using pixel grids or absolute coordinates, this can be disconcerting.

    To experienced web designers, however, this model is very familiar. Web pages have to be designed to layout dynamically based on the target device. When you’re designing a web page you simply don’t know how wide the browser window which will eventually display the page is, how large the fonts are for the user viewing the page, or even what color settings are applicable. And, of course, different browsers display the same content differently even if all other variables are the same.

    InfoPath templates face a similar set of challenges – but in this case, it’s the data and the form that is dynamic. A variable number of records can appear, parts of the form can show and hide, and users can type different amounts of text into controls which grow. A fixed 2D layout for controls simply wouldn’t work.

    Couple that with a desire to have our views be compatible with web standards (XSLT outputting XHTML), and you can see why we built InfoPath with a flow-based layout mechanism.

    Layout Tables

    A lot of the coolest features in the various Office System applications are likely to fall into two buckets: either you’ve never heard of them, or you couldn’t live without them. Here are a few: Format Painter, Styles & Formatting, Fill Down, and Pivot Tables. Once you’ve used any of those, it’s hard to imagine not having them.

    Tables for layout are like that.

    Web designers know that the trick for good dynamic layout is to use tables. Rather than absolute positions, tables allow for 2D layout of controls by expressing constraints and relative positioning. Even tools like the WinForms designer in Visual Studio .NET are moving in this direction, encouraging the use of docking and panels instead of Top/Left/Width/Height. This makes layout tweaks easier and can even make things like localization much more straightforward.

    A few tips for creating layout using tables:

    • If you’re copying an existing paper form, try sketching out a grid for it using a pencil and a ruler. Count how many rows and columns you need, insert that table, and then start inserting controls into the appropriate cells.
    • InfoPath provides a Layout task pane in design-mode which helps you get started using tables, and exposes some of the actions like Merge and Split Cells in a more convenient fashion.
    • When you drag a control into a table cell its width will be set to 100% automatically. Consider using separate cells for static text and for controls.
    • If you are working from a schema, try dragging a group into the view – for example, “myFields”. One of the options should be Controls in Layout Table which automatically creates a two column table with a standard form layout, containing controls with width set to 100%. You can resize the controls automatically by resizing the layout table.

    In the InfoPath 2003 SP-1 Preview we’ve added a few more table features:

    • a “fly-out” Insert Table button on the toolbar to make getting just the right table into the view easier
    • Draw Table – which definitely fits in with the Format Painter as one of the lesser known but essential tricks in your form design arsenal

    If you’ve never used the Draw Table tool, you should try it. Select Table | Draw Table. This will show the Table toolbar, and enter a mode where you can drag out a rectangle using the mouse to create the first cell, and then draw lines across it to split the cell into two. Keep drawing lines to keep splitting cells. You can change the Border Style on the toolbar to change the style of the borders you create, or use the Eraser tool to erase borders – merging cells.

    Layout “Grid”

    Here’s a cool trick from the team. In the SP-1 Preview, there exists the availability to include a background image.  Here’s a sample grid image:

    Copy the above image and save it to your system as a bmp (no loss in fidelity).  Now go into the View properties dialog, click on ‘Use a background picture’.  In the ‘Files of type’ dropdown, select ‘All Files (*.*)’ and finally select the grid image you just saved.  Back in the View Properties dialog, check “Tile horizontally” and “Tile vertically”.  Click OK.

    Now you have yourself a grid by which to align your controls and text by – this is especially useful when aligning controls between layout tables, aligning tables themselves, or in cases where tables just aren’t appropriate.  When you are ready to publish the form, just go back to the properties dialog and take out the background image.   

  • Microsoft InfoPath 2010

    Introduction to Sandboxed Solutions - Sort data in repeating tables using managed code

    • 10 Comments
    Hi. My name is Phil Newman and I'm a program manager on the InfoPath team. In this post, I'd like to introduce you to one of my favourite new features in InfoPath 2010 - Sandboxed Solutions. In InfoPath 2010, forms with code can now be published directly to SharePoint without requiring the farm administrator to approve and upload them! These forms run in a sandboxed environment which protects other resources on the SharePoint server from malicious code.

    In this short video demo, I show how you can add the ability to sort repeating tables in your forms using code.  I use picture buttons in the heading of the repeating table to trigger the code which sorts the table based on the values in the columns. 

    Get Microsoft Silverlight

    About the Code

    In a nutshell, the code puts the XML from the repeating table into an array, sorts the array using built-in .Net functionality, and then writes back into the XML to update the table.

    //Sorts a repeating table.  Takes the parent group node and the index of the column to sort by.

    private void SortTable(string xpathToSort, int columnToSortBy)

    {

    //get the values in an array

    string[][] ValuesToSort = GetRepeatingTableValues(xpathToSort);

    //sort the array

    Array.Sort(ValuesToSort, new StringArrayComparer(columnToSortBy));

    //write the values back to the xml

    SetRepeatingTableValues(xpathToSort, ValuesToSort);

    }

    //Takes an array of arrays and inserts it into a repeating table

    //Assumes that the array and table are the same size

    private void SetRepeatingTableValues(string xpathToSet, string[][] tableValues)

    {

    //Create a navigator on main node supplied in the parameters

    XPathNavigator mainGroup = this.CreateNavigator().SelectSingleNode(xpathToSet, this.NamespaceManager);

    //Clone the first child node of the main navigator and populate it with data

    XPathNodeIterator tableRows = mainGroup.SelectChildren(XPathNodeType.Element);

               

    //iterate through the existing XML and update the values from the sorted array

    for (int i = 0; i < tableValues.Length; i++)

    {

    tableRows.MoveNext();

    XPathNodeIterator thisRow = tableRows.Current.SelectChildren(XPathNodeType.Element);

    for (int j = 0; j < tableValues[0].Length; j++)

    {

    thisRow.MoveNext();

    thisRow.Current.InnerXml = tableValues[i][j];

    }

    }

    }

    //Returns an array of arrays of strings representing the values in a repeating table

    private string[][] GetRepeatingTableValues(string xpathToGet)

    {

    XPathNavigator myNav = this.CreateNavigator();

    int rows, cols;

    XPathNodeIterator tableNodes;

    //figure out the dimensions of the table

    tableNodes = myNav.SelectSingleNode(xpathToGet, this.NamespaceManager).SelectChildren(XPathNodeType.Element);

                rows = tableNodes.Count;

               

    //move to the first row to count the columns

    tableNodes.MoveNext();

    cols = tableNodes.Current.SelectChildren(XPathNodeType.Element).Count;

    //create an array to store the values

    string[][] tableValues = new string[rows][];

    //get all the rows in the table

    tableNodes = myNav.SelectSingleNode(xpathToGet, this.NamespaceManager).SelectChildren(XPathNodeType.Element);

    //iterate through the rows and write the inner xml of each element in each row to the array

    for (int i = 0; i < rows; i++)

    {

    tableNodes.MoveNext();

    XPathNodeIterator childNodes = tableNodes.Current.SelectChildren(XPathNodeType.Element);

    string[] rowValues = new string[cols];

    for (int j = 0; j < cols; j++)

    {

    childNodes.MoveNext();

    rowValues[j] = childNodes.Current.InnerXml;

    }

    tableValues[i] = rowValues;

    }

    return tableValues;

    }

    //Comparison implementation for array or arrays

    class StringArrayComparer : IComparer

    {

    private int iColumn;

    public StringArrayComparer(int iColumn)

    {

    this.iColumn = iColumn;

    }

    int IComparer.Compare(Object x, Object y)

    {

    string[] xAsString = (string[])x;

    string[] yAsString = (string[])y;

    return xAsString[iColumn].CompareTo(yAsString[iColumn]);

    }

    }

    Requirements for publishing your forms with code as Sandboxed solutions:

    • The Sandboxed code service need to be enabled on the farm
    • You must be a site collection administrator on the site collection you’re publishing to
    • Your form must be domain trust
    • Your form template must be an InfoPath 2010 template
    • InfoPath 2007 form code needs to be upgraded to InfoPath 2010 form code

    Complete sandboxed solution documentation is available here.  Note that InfoPath takes care of packaging and activating the solution, all you need to do is publish your form to a document library or as a site content type.

    I look forward to hearing your comments about this new feature. Let me know what you think!

    Phil

  • Microsoft InfoPath 2010

    Cool Forms! Task Form

    • 8 Comments

    This week’s cool form was submitted by Sean Cantellay of Cantellay Consulting. The form allows the user to select a SharePoint task from the right and view it in the form on the page. The task has been broken up into four views and the tab buttons moves the user through the different views. The user can also Escalate the task to another SharePoint group by clicking the Escalate button and selecting the group.

    Click on images for larger pictures.

    ViewTwo

    ViewThree

    ViewFour

    EsclateView

    If you have a “cool” form that you would like to share with us, please send an e-mail with the following details to coolform@microsoft.com -

    • Attach 1 or 2 screenshots of your form
    • Provide a brief description of the form
    • You may also attach the XSN file (optional)

    The most popular submissions will be featured on our blog in future posts.

    Check out other Cool Forms here.

  • Microsoft InfoPath 2010

    Use Rules and Filters to Create Cascading Dropdowns in Forms

    • 11 Comments

    Hi, my name is Anson Hidajat and I’m a program manager on the InfoPath team. In this week's “5 for forms” video demo, I will show how you can use rules and filters to create cascading dropdown lists in a tennis tournament bracket application.

    Get Microsoft Silverlight

    Enjoy and please send us your feedback!

  • Microsoft InfoPath 2010

    Using SQL Server 2005 Web Services with InfoPath

    • 11 Comments

    Here’s your problem: You want to use a stored procedure in a database to access your data through InfoPath, but you don’t really want to have to write script for every query to change the stored procedure’s query parameters.  We’ve all been there.

    Well, stop your coding, right now, because SQL Server 2005 allows you to create SOAP Web Service “endpoints” that act as a type of exposed stored procedure over HTTP.  Among other cool things, this will allow you to have the parameters you need exposed as query parameters in InfoPath’s data source.  It's easy to set up in SQL Server 2005 using the CREATE ENDPOINT T-SQL statement.  For example, let's say there is a simple Stored Procedure called "getAge" that takes an integer value and returns every person in a table that has that age.  The SQL statement to expose that Stored Procedure as a document literal SOAP Web Service could look like this:

    CREATE ENDPOINT getSpecifiedAgeEndpoint

    STATE = STARTED

    AS HTTP

    (

       SITE = 'myserver',

       PATH = '/getspecifiedagewebservice',

       AUTHENTICATION = ( NTLM ),

       PORTS = ( CLEAR )

    )

    FOR SOAP

    (

       WEBMETHOD 'GetRecordsWithSpecifiedAge'

       (

          NAME = 'AdventureWorks.dbo.getAge',

          SCHEMA = DEFAULT,

          FORMAT = ROWSETS_ONLY

       ),

       WSDL = DEFAULT,

       BATCHES = DISABLED,

       DATABASE = 'AdventureWorks'

    )

    The web service will then be located at http://myserver/getspecifiedagewebservice?wsdl.  Note that this web service will not be exposed through IIS; It’s all happening directly from SQL Server 2005.  One method will be exposed at the URL called “GetRecordsWithSpecifiedAge”.  For more information on getting the endpoint up and running correctly, see this MSDN article.

    Note that a few rules apply to the settings that you put in the CREATE ENDPOINT statement that will make it so your Web Service plays nice with the InfoPath Rich Client.  That is, you are probably better off keeping the FORMAT = ROWSETS_ONLY setting as it appears above.  If not, then your web service will return a good deal more information about the query itself than just the rowset data you want, but it will still work for you.  Additionally, setting BATCHES = DISABLED will disable the sqlbatch webmethod from being automatically available on the web service, a powerful webmethod that you should probably keep disabled if you don’t intend to use it.

    At that point, you should be able to design a form template against the web service like any other.  Using SQL Server 2005 rowsets with browser-enabled form templates is currently not a supported scenario; we’ll keep you posted on possible workarounds.

    Also note that when you are designing a main web service against one of these web services that returns row data, InfoPath will warn you in the Data Connection wizard that the web service may return multiple datasets, and that’s an InfoPath no-no.  Under most circumstances, only one dataset will be returned (a dataset can still have multiple tables) so you can usually safely thank InfoPath for letting you know, and continue on.

    Travis Rhodes
    Software Design Engineer in Test

  • Microsoft InfoPath 2010

    Peer to Peer Solutions using SharePoint Workspace 2010

    • 4 Comments

    In the 2nd of 2 videos about InfoPath 2010 and SharePoint Workspace integration, Shirish Pulikkal from the InfoPath test team shows how to create and maintain an Asset Tracking list for both online and offline use, using InfoPath designer and SharePoint Workspace.

    The Scenario: In the 1st video, Taking a list offline using SharePoint Workspace 2010, Shirish showed how to take a SharePoint Asset Tracking list offline in SharePoint Workspace. Smaller organizations with budget constraints may not have access to a SharePoint Server. In this video we show you how to create and maintain an Asset Tracking list for both online and offline use, using just InfoPath and SharePoint Workspace.

    The Process: We use an Asset Tracking form and Categories form for the demo. Initially the Categories form is imported into SharePoint Workspace and we enable lookup to the list tool containing the Categories form. Next we design a new form for Asset Tracking from within SharePoint Workspace and add a SharePoint Workspace data connection to the Categories form. Then we import the Asset Tracking form in list tool in SharePoint Workspace, publish the tool and make the form available to other users subscribed to the workspace to create new list items. This is an example of a peer to peer scenario. The changes you make in your workspace will be immediately visible to other users subscribed to your workspace.

    Get Microsoft Silverlight
  • Microsoft InfoPath 2010

    Designing browser-enabled forms for performance in InfoPath Forms Services (Part 3)

    • 6 Comments

    Part 3 – Postbacks and the conditions that make them expensive

    Welcome to the third article in our series on optimizing the performance of InfoPath browser-enabled forms. In our first article, we defined performance in terms of responsiveness (and identified postbacks as a major cause of poor performance). In our second article we listed a number of conditions that cause postbacks. This article continues our examination of postbacks, looking at conditions that make postbacks more expensive, reducing the responsiveness and scalability of a form system.

    What is an “expensive” postback?

    So what do we mean when we say a postback is “expensive”? Simply that it uses more server resources and takes more time to process the request and generate a response. For an individual form session, the result might be that form updates feel sluggish to the user. For a server processing many requests, the result might be that the performance of all requests is reduced as more resources are consumed.

    Most issues that involve expensive postbacks happen when the server must process form data changes, execute data connections, or run business logic that involves form code and event handlers. Postbacks are also more expensive when the amount of data is large, such as when there are attachments or pictures, digital signatures, or when the form is large and contains a lot of XML. Also, complicated XPaths or inefficient schema constructs demand additional processing resources. These conditions are exacerbated when they require SQL Session state management.

    The following items are some of the things that can increase the cost of postbacks.


    Session state

    For InfoPath Form Services, session state is a mechanism for maintaining the state of a form during a user’s form-filling session. For each session, it contains information about both the form data and the state of the form itself. Form Services uses session state to coordinate form changes between the browser and the form server and to improve server performance by reducing the communication required to synchronize them.

    This session state data is maintained in a SQL Server database by the Session State service, a shared service used by Form Services to keep track of open sessions for each form user connected to the server. This shared service is implemented by the underlying ASP.NET Session state for the farm rather than InfoPath Form Services, so if other Office products are deployed on the same server, the session service may also be used to maintain the state of user sessions for those applications as well. Depending on the server load, this could lead to contention for server resources between InfoPath Form Services and other products.

    Maintaining session state data in a SQL Server database helps improve network bandwidth by reducing the communication between the browser and the Web Front End (WFE) server. However, there is a cumulative performance impact on the WFE and computer running SQL Server as the number and size of the sessions increase. As a user’s session data grows, transferring, loading, and saving the session data takes longer, and more memory is consumed on the WFE. One way session size can grow happens when a user opens multiple forms in the same browser session. In this case, data for each form is combined in a single session, which reduces performance due to the large amount of session data that must be managed. The best way to avoid this condition is to add a button on the form that submits and closes the form (quitting the browser also closes the session, but adding a button allows users to keep their browser open after completing their work in the form). If the computer running SQL Server is separate from the server running Forms Services, which is common, then there is also an impact on the communication channel between the SQL Server and WFE servers. This can quickly become a bottleneck when a large number of multiple concurrent sessions must be managed.

    For smaller sessions, InfoPath Form Services can use Form View as an alternate method for managing the state of a session. Form View is implemented by using ASP.NET View State and the session data is kept as part of the HTML page and sent from the browser to the server on every postback rather than being kept in the SQL Server database. The Form View session is maintained on the browser side, and all session data is included in each postback to the server, up to a default maximum size of 40KB. If the View State session data grows above 40KB, it automatically switches to session state and is managed using the session state database on the SQL Server of the farm. Form View uses more network bandwidth than session state, but decreases load of the computer running SQL Server or the communication channel between servers. Consequently, for environments with smaller groups of users, we recommend configuring InfoPath Form Services to use Form view. For environments that must support many users, session state reduces the exchange of View State session data, reducing the size of postbacks, and generally produces the best performance.

    There are several specific conditions that increase the size of a session, making postbacks more expensive due to the added session state management load. For each postback request, the form’s state must be restored on the server, then all changes must be processed, saved, and sent back in a response to the browser. The form’s state is stored in either View state or Session state and needs to be restored by server when the next postback request for the form comes from the browser. The larger the amount of data involved, the more it slows down saving and restoring form state on each postback.

    • Data Adapters
      • When a data connection returns data, it is stored in the form’s state, either View state for small sessions or the session state database for larger sessions. The larger the amount of data, the more it slows loading and saving updates to the session state database and the form XML.

    • Attachments or pictures
      • A file attachment control increases the maximum session size by 50 percent. If the maximum size is normally set at 4MB, adding an attachment control to the form template increases it to 6MB. This additional space is allocated to accommodate the base64 encoded binary data of the attachment.

      • Consider the number of attachment controls you add to the form template, especially if the attachments or pictures might be large.

      • If you expect that number of forms sessions with large attachments or pictures will be low, the performance impact will be limited to individual editing sessions. If you expect that many of the sessions will contain large attachments, the performance hit is more likely to reduce the scalability of your form system.

      • If you need to accommodate multiple attachments, or very large attachments, you might want to investigate developing a custom solution so that attachments are not stored in the form, but are stored in a location outside the form, such as a SharePoint document library or a database.

    • Digital Signatures
      • Multiple signatures can inflate the data size of an XML form by 500KB or more for each signature. Each signature is stored as base64 encoded data.

      • Although Internet Explorer uses an ActiveX control to handle signatures and other browsers embed the signature in the form, all signatures increase the size of the session. For all browsers, the added size of forms containing digital signatures makes postbacks more expensive.


    Submitting forms to a SharePoint library

    Completed forms are commonly submitted to a SharePoint library. However, libraries are limited to 2000 documents per folder, so as this limit is approached, you will see performance problems. If you anticipate reaching that limit, you can design your form system to submit to an alternate destination. The simplest approach is to make sure that each type of form submits to a separate SharePoint library or folder rather a single library or folder containing multiple types of forms; this approach only defers the problem though. Another alternative might be to use a workflow to move submitted files from the library. A more sophisticated approach is to submit to a Web service. This will require custom development for the Web service, but it allows the most flexibility and scalability since the completed forms can be stored in either a SharePoint library or in a database. A solution that submits through a Web service to a database offers the best performance and scalability for large form systems.


    First request optimization

    InfoPath Form Services uses a technique called first request optimization to improve the loading performance of a form the first time it is requested. First request optimization involves pre-rendering an instance of the form from the form template when the form template is published. This form instance does not require a session state database entry (because there is no user session yet for an initial request). When first requested by a user, the pre-rendered instance of the form is sent to the browser for rendering so the user doesn’t have to wait while the server initializes the session and loads its version of the form.

    However, there are form features that will disable first request optimization. Initial requests for forms that cannot use first request optimization are more expensive, reducing responsiveness and slowing the loading of the form. The following conditions are examples of things that prevent this optimization:

    • The use of current time and data functions as default values

    • Secondary data source queries that execute on load (except XML files that are part of the form)

    • Rules or business logic that run on load

    • The use of a username for a default value

    • Any other environment-related or dynamic information that requires server processing

    When you publish a new form template, you can determine whether first request optimization is being used by checking for the presence of an ASP.NET session ID cookie immediately after requesting a new form (you can use an HTTP scanner tool such as Fiddler2 to check for the cookie in the response). If there is no cookie, then the form is using first request optimization. Perform an action that triggers a postback, such as switching views, and you will find a session ID cookie.


    Business logic changes to XML and cascading events

    When a postback involves business logic that makes changes to the form XML on the server, each change to the XML causes events to fire. This can cause an expensive chain of processing operations if the event handling is set up so that an XML change causes a cascade of events that make additional XML changes. Although the number of nested changes is restricted, there is no restriction on how many XML nodes are changed by a single event listener. Consequently, if an event listener changes more than one XML node and each change causes other listeners to fire and make changes to other XML nodes, then the total number of events invoked and XML changes made could be significant. The processing required to execute the cascade of events can use significant server resources, reducing throughput, scalability, and responsiveness. This situation is similar to the event handling issue discussed in the previous article on causes of postbacks, and likewise, it is important for performance and scalability that you understand and carefully scope events to reduce unnecessary server stress.


    Custom hosting pages

    Another issue discussed in the previous article on causes of postbacks addresses an advanced form scenario that involves using a custom ASP.NET page to host the InfoPath Form control. Since the emphasis here is on conditions that make postbacks more expensive, it is worth noting that although a custom solution offers significant flexibility, you also give up some of the optimizations provided for forms published using the InfoPath Form Designer. One of the optimizations you lose is that postbacks that need to communicate with the hosting page cannot communicate using partial postbacks, and instead must use more expensive full page postbacks. However, if the hosting page just needs to display a form (but doesn’t need to listen for a submit to host event), then there is no change in the form’s postback behavior and partial postbacks can be used. Also, as noted previously, with each postback there is additional processing on the server because the ASP.NET page controls must be rebuilt; and if the page is hosted on a SharePoint site, it also must initialize the complete SharePoint page infrastructure as well.


    Additional considerations

    As you might expect, this list of conditions that can make postbacks an expensive operation is not comprehensive. In fact, almost any postback can be expensive, depending on type and extent of the changes involved. We’ve highlighted some important issues above and in the previous article on postbacks. If you consider the other issues listed in that article - complex calculations and XPaths, out-of-context and multiple binding - you can see that they also imply performance and scalability impacts arising from expensive processing operations on the form server. If something causes a postback because it requires the processing power of the server, then it necessarily adds to the server load, affecting resource utilization, throughput, and scalability. These issues become more important as the number of concurrent users increases, and as the size and complexity of the forms increases.


    What’s next?

    The next article in our series on understanding and optimizing the performance of browser-enabled forms will address conditions that affect form rendering in the browser. We’ll also look at an important tool provided by the InfoPath Designer for optimizing browser-enabled forms and controlling postbacks, the Design Checker.

     

  • Microsoft InfoPath 2010

    Cool Form! MS Store Inventory Checklist

    • 7 Comments

    This week's cool form is an inventory check list form that is used in the Microsoft Company Store. The form contains 2 views.

    The 1st view contains a set of checks that need to be completed by store employees.

    The 2nd view displays the list of checks that have not yet been completed by the user.

     

    If you have a “cool” form that you would like to share with us, please send an e-mail with the following details to coolform@microsoft.com -

    • Attach 1 or 2 screenshots of your form
    • Provide a brief description of the form
    • You may also attach the XSN file (optional)

    The most popular submissions will be featured on our blog in future posts.

    Check out other Cool Forms here.

  • Microsoft InfoPath 2010

    E-Mailing a Custom View

    • 15 Comments

    Lately, we've had a lot of interest in e-mailing a custom view with InfoPath forms that are submitted via e-mail.  There are a few simple tricks that will allow you to do this.

    Before we start, note that, in the InfoPath rich client, you have the option to "Send to Mail Recipient" from the file menu in the Editor.  In this case, you're stuck sending the currently active view of the form.  The user filling the form would have to manually click or change data in order to fire an event to switch to a custom view.  While this is feasible, we can do better with a pre-defined e-mail submit data connection.

    To define an e-mail submit data connection in the InfoPath Designer:

    1. Click "Tools" >> "Data Connections…"

    2. Click "Add…"

    3. Select "Create a connection to" >> "Submit data" and click "Next >"

    4. Select "As an e-mail message" and click "Next >"

    5. Enter an e-mail address in the "To" header field, or bind it to a field in your form template.

    6. Fill out any other e-mail header information and finish the wizard.

    7. Click "OK" / "Finish" / "Close" to get out of the wizard and finalize your e-mail submit data connection.

    Now that we've defined the e-mail submit data connection for our form template, we can move on to the custom view portion…

    The easiest option is to send a blank view.  To accomplish this, you'll simply want to switch views before you submit.  This is easily accomplished using a rule on button click.  Here are the steps, in the InfoPath Designer, to configure the "Main Submit" toolbar button to send the blank view:

    1. Create a blank view

      1. On the "View" menu, click "Manage Views…"

      2. In the Views TaskPane, click "Add a new view…"

      3. Type a name for the view and click "OK".

    2. Configure main submit to submit the blank view with the e-mail

      1. Click "Tools" >> "Submit Options…"

      2. Check the "Allow users to submit this form" checkbox.

      3. Select the "Perform custom action using Rules" radio button.

      4. Click the "Rules..." button.

      5. Click "Add..." in the "Rules for Submitting Forms" dialog.

      6. Click "Add Action..." in the "Rule" dialog.

      7. Select "Switch Views" and select the blank view in the "View" drop-down list box.

      8. Click "OK" to close all the dialogs.

    Now, when the user clicks "Submit", the view will first be switched to the blank view, and then the form will be submitted to the mail recipients.  InfoPath sends the active view contents in the body of the e-mail message, so the blank view will be sent in the message body!

    But now the next obvious question is, "Wait a second, I thought we were sending custom views, not just blank ones!"  Good call.  InfoPath Forms Services treats the "switched-to" view a bit differently than the InfoPath rich client.  In browser-enabled form templates filled out in the browser, you can add controls, text, pictures, etc. to the blank view to which we switched before submitting, and the message body will display the data in the custom view, along with the Introduction specified in the e-mail submit data connection wizard.  In the InfoPath rich client, you'll still only see the blank view due to view-switching concurrency limitations.  So we need an alternate solution…

    Basically, instead of e-mailing a custom view, we'll e-mail custom view content.  We'll have two sections in one view:  one to hold the controls where the user can fill out the form, and one where the custom "view" contents will be stored.  Then, at submit time, we'll run a rule to first hide the editing section and show the custom e-mail body section, and then submit via our pre-defined e-mail submit data connection.  This works identically in the browser and the InfoPath rich client Editor.  Here are the high-level steps:

    1. Insert two "Section" controls into the form view.  Name one "EditSection" and the other "EmailSection".

    2. Fill the sections with the relevant controls, formatting, etc.  Create your "custom view" inside the "EmailSection" and create the normal form-filling "view" in the "EditSection".

    3. Create a "True/False (boolean)" data source node.  Name it "ShowCustomEmailSection", and set its default value to "FALSE".

    4. Add conditional formatting to hide and show the "EmailSection" and "EditSection" sections.

      1. Set the "EditSection" conditional formatting to "hide this control" when "ShowCustomEmailSection" is TRUE.

      2. Set the "EmailSection" conditional formatting to "hide this control" when "ShowCustomEmailSection" is FALSE.

    5. Configure your submit button as above with the blank view case, but, instead of adding a rule action to switch views before submitting, add a rule action to set the value of the "ShowCustomEmailSection" field to the "true()" function.  This will conditionally hide the "EditSection" and show the "EmailSection".  All that will show up in the message body is an HTML rendering of the contents of the "EmailSection".

    And that's it!  Note that you may have to set the "Postback Settings" for the relevant controls to "Always" for browser-enabled form templates to get the conditional formatting to work as expected.

    Forrest Dillaway
    Software Design Engineer in Test

  • Microsoft InfoPath 2010

    XPath Powers: Calculating Totals

    • 6 Comments

    InfoPath makes it trivial to track totals for repeating structures, such as customer orders. Just create a repeating table of line items, and sum up the totals for individual line items. However, sometimes, totals for line items may not be available; it is still possible to perform dynamic calculations across the repeating structure, even when interim results (line item totals) are not stored in the data source. This article will explain a way to make this work without code.


    Let's explore the simple case first.

     Form at Runtime Data Source
      

    Line item total is set by using a default value (price * quantity) on the lineItemTotal node. Creating an order total is just a matter of adding an expression box that uses the built-in SUM function:

    sum(my:group1/my:lineItems/my:lineItemTotal)

    And voila, we're done, totals will be calculated correctly.


    The reason why we are here: the complex case.

    What if the interim results (line item totals in our scenario) cannot be persisted in the data source? This situation might arise if you're operating on a fixed schema, or if you're an "XML purist" (I know I am :-)), arguing that there is unnecessary redundancy in your XML if you store calculated values.

    The goal is still the same - but the data source is different.

     Form at Runtime Data Source
         

    The line item total would be an expression box instead of the text box; it would be calculated simply as (price * quantity).

    But how do we calculate the order total? Your first instinct may suggest to use sum (price * quantity), but you'll soon discover that the SUM XPath function only takes a nodeset...

    Let's recall the clever technique of iterating through repeating items by using just XPath: it was described in detail in this article. Let's use the following value for the order total expression box:

    sum(xdMath:Eval(my:lineItems, "my:price * my:quantity"))

    Why does this work? Let's go inside-out:

    1) The eval function evaluates the price * quantity expression in the context of line items, and returns a nodeset with the results.
    2) The sum function takes in a nodeset as a parameter, and sums up its contents, giving us the desired total.

    I'm attaching a sample form template that has this technique implemented; save the XSN locally before opening it up.

    This method works in InfoPath 2003, 2007, and is supported in browser-enabled form templates.

    Alex Weinstein
    Program Manager

  • Microsoft InfoPath 2010

    Don't settle for just one: Adding multiple default rows

    • 10 Comments
    Since I realize not everyone has installed the Beta yet (you can do it!), I figure it's time for a trick everyone can play with, even those still using InfoPath 2003.
     
    Starting with more than one row in a repeating table
    You may want to do this if you have a form where you know everyone's going to fill out at least five rows, or maybe some people will even print our your form before typing in their answers (I never!). You might even want to have five rows exactly, and then disable adding or deleting rows (in Repeating Table properties), but still use a repeating table to get the data structure you want.
     
    Regardless of your scenario, here's how to do it:
    1. Open the form in design mode
    2. Click Default Values on the Tools menu
    3. In the data source, select the group that's bound to the row of the repeating table
    4. Click the down arrow next to the group name
    5. Select "Add another row below"
     
     
    You can even specify different values for the columns of each row using the bottom of that dialog. And of course this works for any repeating item in your data source, not just those bound to repeating tables.
     
    Keyboard trick!
    Save yourself a few clicks by typing the "Insert" key instead of using the menu. Each time you type "insert" it will add another row. Those two clicks per row can really add up when you have a lot of rows! If you type it a few too many times, you can also use the "Delete" key to remove the offending rows. 
     
    Got your own tricks to share?
    As usual, if you've got your own tips in this area, or a cool reason to use this trick, please leave us a comment for the team to see and the community to gain.
     
    Enjoy,
    ned
  • Microsoft InfoPath 2010

    How to Integrate the .NET Framework SDK Documentation with VSTA

    • 8 Comments

    The .NET Framework 2.0 SDK documentation includes the Visual Basic and Visual C# language references, as well as the documentation for the .NET Framework classes. You can download and integrate this documentation into the Help viewer for the Visual Studio 2005 Tools for Applications (VSTA) integrated development environment (IDE) that ships with InfoPath 2007. After doing so, the NET Framework 2.0 SDK documentation will be available along with the "InfoPath Developer Reference for Managed Code Form Templates" documentation in VSTA IDE Help viewer for use offline.

     
     
     
     
    .NET Framework SDK Help in the VSTA Help Viewer
     
    Important   If you are running under Windows Vista with user account control, you must start InfoPath 2007 as an administrator before performing the following procedure. To do that, navigate to C:\Program Files\Microsoft Office\Office12, right-click INFOPATH.EXE, and then click Run as Administrator. If you are not running InfoPath as an administrator, you will be unable to complete the following procedure.
     

    To integrate the .NET Framework 2.0 SDK documentation with the VSTA IDE Help

    1. Start InfoPath 2007, and open or create a form template in design mode.
    2. On the Tools menu, click Programming, and then click Microsoft Visual Studio Tools for Applications.
    3. In VSTA, click Index on the Help menu.
    4. Search for Collection Manager, Help, to open the Visual Studio 2005 Tools for Applications Combined Help Collection Manager topic.
    5. Select the check box for the Microsoft .NET Framework 2.0 SDK Documentation in the list of available help collections at the bottom of the topic below Collections available for the default combined Help collection.
      If the .NET Framework 2.0 SDK documentation does not appear in the list of available Help collections, you must install the .NET Framework 2.0 SDK. To install the .NET Framework 2.0 SDK, see http://go.microsoft.com/fwlink?LinkId=9832&clcid.
    6. Click the Update Help Collection button.
     
    You will be asked to close all instances of the VSTA IDE and the Help viewer, Microsoft Document Explorer. When you restart VSTA, the.NET Framework 2.0 SDK documentation will be available in the Help viewer.
     
    - Mark Roberts, Programmer-writer
  • Microsoft InfoPath 2010

    Microsoft Office InfoPath 2003 Technical FAQ and the InfoPath Viewer

    • 6 Comments

    Looking for some of our answers to questions we get a lot?  Pull up the Microsoft Office InfoPath 2003 Technical FAQ - if you don't find the answer you need in the FAQ, please ask your question on the newsgroup microsoft.public.infopath where MVPs, experienced InfoPath users, and Microsoft InfoPath team members can all help.

    One question that comes up often regards a no-cost InfoPath Viewer.  Here are three Q&A's in the FAQ worth pointing out:

    Q. Do employees need to have InfoPath installed on their PCs in order to fill out forms created with InfoPath? Is InfoPath required for viewing or reading an InfoPath form?

    A. Information workers will need to have InfoPath 2003 installed on their PCs to enter information into InfoPath forms and to take advantage of the rich client functionality such as structural editing, business-logic validation, rich-text formatting, AutoCorrect, and spell-checking. That said, you can read an InfoPath form that has been saved to .MHT in your browser or within an HTML-enabled e-mail client, as the body of your mail message. Because InfoPath generates XML belonging to any customer-defined schemas, other software could be used to reuse and display that XML document.
     
    Q. How do users fill out an InfoPath form if they do not have InfoPath?

    A. In order to fill out forms created in InfoPath and to take advantage of InfoPath’s rich-client functionality, data validation and offline capabilities, users will need a copy of InfoPath installed on their workstation.

    It is possible to build browser-based solutions based on InfoPath forms. For example, you can build a solution in InfoPath (building a schema and Web services) that can be used for collecting information within the firewall, then use the same schema and Web services for building an ASP.NET solution for collecting information outside the firewall. For business solutions that require a “reach” (browser-based) solution, yet still use the power of InfoPath for the parts of the process that occur within an organization (where InfoPath can easily be deployed), there are two options:

    • Use ASP.NET forms in the solution to front-end the process. Data is gathered in the browser-based forms, then moved into the InfoPath forms where available. This combines the reach experience for initial data collection and the rich experience of interacting with that information via InfoPath. Customers can use the same schema and Web services for both the InfoPath and ASP.NET solutions.
    • Work with one of the many partners that have developed solutions based on InfoPath including Sourcecode, Teamplate, Ultimus and Cardiff.

    Q. Do I need to touch every desktop to deploy InfoPath? Can you host an InfoPath form in the browser?

    A. In order to fill out or design an InfoPath form, InfoPath needs to be installed on the desktop. However, once you have deployed InfoPath, you can easily roll out the form templates that users need to use InfoPath. InfoPath provides transparent deployment and maintenance of solutions via a Web-like model that downloads solutions on demand. InfoPath form templates are downloaded silently and seamlessly to the client when a user clicks on a link to an InfoPath form or clicks on an InfoPath attachment.


    A process to create an InfoPath Viewer experience if read-only is all you want: note that if you just want to be able to have a read-only rendering of an InfoPath form beyond what InfoPath can generate directly (save as MHT or via an email body), you should take a look at the SDK downlevel tool (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ipsdk/html/ipsdkUsingTheDownLevelTool.asp ) which provides a way to modify your form XML to pull in a stylesheet to use for rendering the form when InfoPath is not on the user's machine.

     

  • Microsoft InfoPath 2010

    Problems When Calling into Script Functions in a Task Pane from Managed Code

    • 1 Comments

    We have been receiving questions about problems deploying some InfoPath solutions created with the InfoPath 2003 Toolkit that call into script functions in a task pane from managed code. These solutions work on the developer's machine, but then fail when deployed on user's machines if the MSHTML primary interop assembly (PIA) - microsoft.mshtml.dll - is missing.

    This problem is caused by InfoPath object model members that return types from the MSHTML PIA. The MSHTML PIA is installed by default with Visual Studio .NET 2003, but is not installed by InfoPath 2003 SP1 or with the .NET Framework. As a result, when the solution is deployed on a machine missing the MSHTML PIA, the solution throws an exception.

    There are two ways to resolve this issue: 1) Install and register the MSHTML PIA on the user's machine, or 2) Use late binding in your form code to call such functions.

    Installing the MSHTML PIA on User's Machines

    The MSHTML PIA is a redistributable component installed with Visual Studio .NET 2003 (as defined in the <drive>:\Program Files\Microsoft Visual Studio .NET 2003\redist.txt file), so you can deploy it on all client machines where you want the solution to run. Refer to the End User License Agreement (EULA) for your edition of Visual Studio .NET 2003 for terms and conditions on redistributing components.

    The MSHTML PIA (microsoft.mshtml.dll) needs to be copied to the user's machine, installed in the Global Assembly Cache (GAC) using the Global Assembly Cache tool (gacutil /i microsoft.mshtml.dll), and then registered using the Assembly Registration Tool (regasm microsoft.mshtml.dll).

    Using Late Binding to Call Script Functions From Managed Code

    You may also consider using late-bound calls to objects previously passed by the task pane script to the managed code in your form code. The following is a code fragment that shows how to do this by using the InvokeMember method of the System.Type class in the .NET Framework. Note that the managed code requires FullTrust permissions to work with late-bound calls. For more information on FullTrust permissions and how to deploy form templates that require this permission set, see Understanding Fully Trusted Forms.

    Taskpane.htm:

    <HTML>
    <script>
       function Initialize()
       {
          var XDoc = window.external.XDocument;
          XDoc.Extension.SetTaskPaneWindow(window);
       }

       function MyScriptFunc(s)
       {
          window.alert(s);
       }
    </script>

    <BODY onload="Initialize();" />
       // Remaining taskpane HTML goes here.
    </BODY>
    </HTML>

    FormCode.cs:

    private XDocument      thisXDocument;
    private Application    thisApplication;
    private object         taskPaneWindow;
       ...

    // Note: The MatchPath attribute should match your control's ID.
    [InfoPathEventHandler(MatchPath="CTRL1_5", EventType=InfoPathEventType.OnClick)]
       public void CTRL1_5_OnClick(DocActionEvent e)
       {
          object[] args =  new object[] {"Hello from InfoPath script"};

          // Call into script through CLR late binding using the InvokeMember method.
          taskPaneWindow.GetType().InvokeMember(
             "MyScriptFunc",              // late-bound method
             BindingFlags.InvokeMethod |  // binding flags
             BindingFlags.DeclaredOnly |
             BindingFlags.Public |
             BindingFlags.Instance,
             null,                        // binder object
             taskPaneWindow,              // target object
             args);
       }

       public void SetTaskPaneWindow(object window)
       {
          taskPaneWindow = window;
       }

  • Microsoft InfoPath 2010

    Introducing the InfoPath SP1 Master/Detail Control

    • 21 Comments

    Applies To: Microsoft Office InfoPath 2003 SP-1 Preview

    InfoPath SP-1 introduces a number of exciting new built-in controls.  One of which is the Master/Detail control.  After InfoPath 2003 was released, one of the most common questions on the InfoPath newsgroups was how to implement a Master/Detail type of control in InfoPath.  Although this was possible in InfoPath 2003 prior to SP-1, doing so was not easy or straightforward.  For this reason, InfoPath 2003 SP-1 now includes built-in support for the Master/Detail control.

    The Master/Detail control allows you to designate one control as a master that drives the data in another control which is called the detail.  When the user selects an item in the master, the corresponding data in the detail is displayed.

    When designing a form template in InfoPath design mode, inserting a Master/Detail control into your form is easy. There are actually two ways to do so.  The first way is to use the Master/Detail control in the Controls toolbox.  Inserting the Master/Detail control from the Controls toolbox actually inserts two controls – a Repeating Table that is designated as the master and a Repeating Section that is designated as the detail.  When you insert the Master/Detail control this way, as long as the “Automatically create data source” checkbox in the Control toolbox is checked, a simple data structure is created in the data source. This structure consists of a group node containing one repeating group node that, in turn, contains four child fields. The master and detail are both bound to the inner repeating group node. In this case, the master and detail are said to be linked by position in the tree.  This basically means that if you select the third item in the master control, for example, the data for the third item is displayed in the detail control. This enables you, for example, to build a form that contains basic customer information, such as customer name and SSN, in the master and more detailed information about that customer such as address and phone number, in the detail.

    The second way to create a Master/Detail relationship is by manually specifying which control is the master and which is the detail. Although this is a bit more difficult than choosing the Master/Detail control from the Controls toolbox it does give you more control over how the master is linked to the detail. (As mentioned earlier, one way of linking a master control to a detail control is by position. The second way to link a master to a detail is by key field. This type of linking allows you to specify a primary key/foreign key type of relationship where the value of the primary key in the master determines which detail data is displayed. This type of linking is only available when creating a Master/Detail relationship manually.)

    To create a Master/Detail relationship manually, perform the following steps:

    1. Insert a Repeating Table control. This control will act as the master. (Only Repeating Tables can act as master controls.)
    2. Open the Repeating Table Properties dialog either by double-clicking on the Repeating Table tab at the bottom of the control or by selecting the Repeating Table and then clicking on the Format | View Properties menu item.
    3. Click on the Master/Detail tab
    4. Click the “Set as master” option button and then type a name into the “Master ID” text box. This ID will be used to specify the master to link to when designating another control as the detail.
    5. Click OK to close the dialog and commit the changes to the Repeating Table properties. (At this point, you will notice that the tab at the bottom of the Repeating Table now contains the text “(master)” which designates that this control is now a master control.)
    6. Now, insert another Repeating Table or a Repeating Section control. This control will act as the detail control. (If you want to link the master to the detail by position, it is better to insert a Repeating Table or Repeating Section control that is bound to the Repeating Table you created in step 1. Link by position is the default behavior when inserting the Master/Detail from the Controls toolbox as mentioned earlier.)  If you insert a new Repeating Section control, you will want to add controls inside the Repeating Section in order to display the detail data.
    7. Open the properties dialog for the Repeating Table or Repeating Section as in step 2 above.
    8. Click on the Master/Detail tab
    9. Click the “Set as detail” option button.
    10. From the “Link to Master ID” dropdown, choose the ID that you created in step 4 above.
    11. Now, you have to specify how the master and detail are linked. By default, the master and detail are linked by position. Since we already talked about this type of linking above, click the “By key field” option button instead.
    12. In order for this type of Master/Detail relationship to work, you need to specify which field in the data source is the master key and which field is the detail key.
      1. Click on the data source button to the right of the “Key field (master)” edit box and choose the field from the master that should be used as the master key.
      2. Then, click on the data source button to the right of the “Key field (detail)” edit box and choose the field from the detail that should be used as the detail key.
    13. Click OK to close the properties dialog and commit the changes. (At this point, you will notice that the tab at the bottom of the Repeating Table or Repeating Section now contains the text “(detail)” which designates that this control is now a detail control.)

    Now, when you use your form, you will notice that when you select an item in the master, only those detail items whose detail key matches the master key of the currently selected item in the master control will be displayed. 

    Obviously, if there is no data, no details will be displayed.  InfoPath provides a nice way to deal with this situation. When walking through the steps to manually create as Master/Detail relationship above, you may have noticed the option “Copy key field from selected master when inserting detail” which is checked by default.  This option designates that when inserting a new detail item, the value of the master key of the item that is currently selected in the master control will be automatically copied to the detail key in the new detail item. This is quite convenient when creating Master/Detail data from scratch.

    As you can see, creating a Master/Detail relationship in InfoPath 2003 SP-1 is very easy and is just one of the many new features that were added in direct response to customer feedback.

  • Microsoft InfoPath 2010

    Take a list offline using SharePoint Workspace 2010

    • 5 Comments

    In this short video demo, Shirish Pulikkal from the InfoPath test team shows how you can customize a SharePoint list in InfoPath designer and work with the list offline in SharePoint Workspace.

    The Scenario: A fictitious company Fabrikam wants to track assets in their lab using SharePoint list. They want to be able to track assets both in the online and offline case. Fabrikam has decided to use InfoPath to customize the list and SharePoint workspace to enable working offline with the list.

    The Process: We start by customizing the form for the SharePoint list in InfoPath designer and add a secondary data connection to pull data from another SharePoint list. Then we publish the form back to the SharePoint list and sync it in SharePoint Workspace. Now we can create list items while working offline in SharePoint Workspace and items can be synced to SharePoint server when we get back online.

    Get Microsoft Silverlight

  • Microsoft InfoPath 2010

    Using Relative URLs with the ServerInfo Class in InfoPath 2010

    • 4 Comments

    Hi, my name is Jill Anderson and I am a tester on the InfoPath team. In this post, I would like to introduce you to the one of the newest members of the InfoPath Object Model, the "ServerInfo" class.  For InfoPath forms published to a SharePoint server, the members of this class give you context about that particular site. Documentation about this new class can be found at: http://msdn.microsoft.com/en-us/library/microsoft.office.infopath.serverinfo.aspx.

    In this short video demo, I show you how you can use the members of this class to enable your form to submit data using a relative URL.  This enables you to package a Site Collection as a WSP and move it to a new server.  With these changes, the submit data connection moves to the new server as well.

    Initial Setup:

    To make sure that my form template was correctly associated with my SharePoint Form Library both before and after the Site Collection Migration, I published it as a Content Type (http://office.microsoft.com/en-us/infopath-help/create-a-sharepoint-library-or-site-content-type-for-your-form-template-HA010103005.aspx ). The ability to publish a Sandboxed Solution as a Content Type is a new feature for Office 2010.

    Afterwards, I associated this content type with the correct SharePoint Form Library on the SharePoint Server. The steps to do this are as follows: 

    1. Create a new "Form Library"
    2. Open the newly created "Form Library"
    3. Open the "Library Settings" located under the "Library" Tab on the Ribbon
    4. Open "Advanced Settings" and set "Allow management of content types?" to "yes".
    5. Under "Content Types" select "Add from existing content types"
    6. Add the content type you published to the SharePoint server.

    Sample Code:

    This is the code I used to relativize the submit to the SharePoint site.

    /// <summary>
    
            /// Submits the form to the SubmittedTimeCards form library on SharePoint and calls a function to update the Vacation 
    
            /// and Sick Balance for the employee.
    
            /// </summary>
    
            /// <param name="sender">The source of the event.</param>
    
            /// <param name="e">Provides data for the Microsoft.Office.InfoPath.FormEvents.Loading event.</param>
    
            
    
            public void FormEvents_Submit(object sender, SubmitEventArgs e)
    
            {
    
                FileSubmitConnection fileSubmit = (FileSubmitConnection)this.DataConnections["SharePoint Library Submit"];
    
                // Refreshing the Total number of hours and total pay for this given form.
    
                this.CalculateWorkWeekHours();
    
                this.CalculateTotalTypeHours();
    
                this.CalculateTotalPay();
    
                // Update the new Sick leave and Vacation Balance.
    
                this.DeductVacationAndSickPay();
    
                // Relative the SharePoint Submit location to current SharePoint site.
    
                fileSubmit.FolderUrl = this.ServerInfo.SharePointSiteUrl.ToString() + "SubmittedTimeCards/";
    
                fileSubmit.Execute();
    
                // If the submit operation is successful, set
    
                e.CancelableArgs.Cancel = false;
    
            }
    
    
    

    Additional Links

    For more information about creating and publishing Sandboxed Solutions see Phil Newman's post on
    Introduction to Sandboxed Solutions - Sort data in repeating tables using managed code
    Jill

  • Microsoft InfoPath 2010

    Designing browser-enabled forms for performance in InfoPath Forms Services (Part 6)

    • 7 Comments

    Part 6 – Addendum: Links to related performance resources


    Welcome to the sixth article in our series about designing InfoPath browser-enabled forms for better performance and scalability. In our previous articles we defined performance in terms of responsiveness, listed a number of conditions that cause postbacks, and looked at some of conditions that make postbacks more expensive, reducing the responsiveness and scalability of a form system. We also described some of the issues that affect form-rendering performance in the browser and suggested using the Design Checker to monitor browser compatibility issues while designing a form template in the InfoPath Designer. Finally, we listed some useful performance monitoring counters available in PerfMon.

    In this addendum, we list a variety of links to additional resources you might want investigate if you are interested learning more about designing forms with InfoPath 2007. In keeping with our theme, the emphasis is on performance, but you will also find other related resources that you can use to broaden your understanding of the online forms environment. Since InfoPath is built on SharePoint technologies, the following resources provide information not only on InfoPath Forms Services and browser-enabled forms, but also SharePoint, ASP.NET, and SQL Server. In addition, we’ve included some general resources on monitoring and testing, and thrown in a few good blogs as well.

    Hope you’ve found this series helpful in demystifying InfoPath browser-enabled forms performance. Be sure to let the InfoPath team know if you have comments or questions about your own forms requirements by adding comments here or on the InfoPath newsgroup listed below!

    Thanks,

    Brad Valantine
    Technical Writer


    InfoPath

    Improving the Performance of InfoPath 2007 Forms
    http://msdn2.microsoft.com/en-us/library/bb380251.aspx
    A whitepaper about performance and the InfoPath rich client. Because of differences between the client and browser-enabled forms, not everything applies to Forms Services and browser forms, but a must read nonetheless.

    InfoPath Forms Services best practices
    http://technet.microsoft.com/en-us/library/cc261832(TechNet.10).aspx

    Microsoft Office Forms Server TechNet TechCenter
    http://technet.microsoft.com/en-us/office/bb267350.aspx

    InfoPath Forms Services roadmap
    http://technet.microsoft.com/en-us/library/cc262885.aspx

    InfoPath 2007 features that are unavailable in InfoPath Forms Services
    http://office.microsoft.com/en-us/infopath/HA102105871033.aspx

    Forms Server 2007 Home Page
    http://office.microsoft.com/en-us/formsserver/FX100490391033.aspx

    InfoPath 2007 Home Page
    http://office.microsoft.com/en-us/infopath/FX100487661033.aspx

    Planning and architecture for Office Forms Server 2007
    http://technet.microsoft.com/en-us/library/cc303371(TechNet.10).aspx

    Plan InfoPath Forms Services
    http://technet.microsoft.com/en-us/library/cc262498(TechNet.10).aspx

    Office Developer Center: InfoPath 2007 Resource Center
    http://msdn.microsoft.com/en-us/office/aa905443.aspx

    InfoPath Forms Services Architecture
    http://msdn2.microsoft.com/en-us/library/ms772323.aspx

    Form Development and Deployment Lifecycle
    http://msdn.microsoft.com/en-us/library/ms772031.aspx

    Creating InfoPath Form Templates That Work With Forms Services
    http://msdn2.microsoft.com/en-gb/library/aa945450(VS.80).aspx

    Support: Microsoft Help and Support: Forms Server 2007 Solution Center
    http://support.microsoft.com/ph/11846


    SharePoint

    Plan for performance and capacity (Office SharePoint Server)
    http://technet.microsoft.com/en-us/library/cc262971(TechNet.10).aspx

    Plan for performance and capacity (Windows SharePoint Services)
    http://technet.microsoft.com/en-us/library/cc288124(TechNet.10).aspx

    White paper: Intel Performance Testing of Windows SharePoint Services (WP)
    http://technet.microsoft.com/en-us/library/cc288383(TechNet.10).aspx

    How to Optimize a SharePoint Server 2007 Web Content Management Site for Performance
    http://msdn.microsoft.com/en-us/library/bb727371.aspx

    White paper: Planning and Monitoring SQL Server Storage for Windows SharePoint Services: Performance Recommendations and Best Practices
    http://technet.microsoft.com/en-us/library/cc287996(TechNet.10).aspx

    ASP.NET

    ASP.NET Performance
    http://msdn2.microsoft.com/en-us/library/44e5wy6k.aspx

    ASP.NET Session State Overview
    http://msdn2.microsoft.com/en-us/library/ms178581.aspx

    Developing High-Performance ASP.NET Applications
    http://msdn2.microsoft.com/en-us/library/5dws599a.aspx

    Monitoring ASP.NET Application Performance
    http://msdn2.microsoft.com/en-us/library/3xxk09t8.aspx


    SQL Server

    Performance (Database Engine)
    http://msdn.microsoft.com/en-us/library/bb510669(SQL.100).aspx

    Monitoring (Database Engine)
    http://msdn.microsoft.com/en-us/library/bb510705(SQL.100).aspx


    Monitoring and Testing

    Life-Cycle Performance Testing for Eliminating Last-Minute Surprises
    http://msdn2.microsoft.com/en-us/library/bb905531.aspx


    Server Performance and Scalability Killers
    http://msdn2.microsoft.com/en-us/library/ms951773.aspx

    Performance Counters in the .NET Framework
    http://msdn.microsoft.com/en-us/library/w8f5kw2e.aspx


    Books 

    Designing Forms for Microsoft Office InfoPath and Forms Services 2007 (Microsoft .NET Development Series)
    By Scott Roberts and Hagen Green
    Publisher: Addison-Wesley (c. 2007)
    ISBN 0321410599
    http://www.informit.com/store/product.aspx?isbn=0321410599

    A couple of great online books from the folks in Patterns and Practices:
    Improving .NET Application Performance and Scalability
    http://msdn2.microsoft.com/en-us/library/ms998530.aspx

    Performance Testing Guidance for Web Applications
    http://msdn2.microsoft.com/en-us/library/bb924375.aspx

     

    Blogs and Newsgroups

    Pashman's InfoPath Goldmine: Tips and Tricks for Tuning Forms Services Performance
    http://blogs.msdn.com/timpash/archive/2007/08/02/tips-and-tricks-for-tuning-forms-services-performance.aspx

    Performance Research, Part 1: What the 80/20 Rule Tells Us about Reducing HTTP Requests
    http://yuiblog.com/blog/2006/11/28/performance-research-part-1/
    The first article in a series about research done by Yahoo into web page performance optimization.

    Agile Testing: Performance vs. load vs. stress testing
    http://agiletesting.blogspot.com/2005/02/performance-vs-load-vs-stress-testing.html

    Ben Curry: Using Performance Monitor (perfmon.exe) to Monitor SharePoint Server 2007
    http://mindsharpblogs.com/ben/archive/2007/02/14/1569.aspx

    Ben Curry: SharePoint Server 2007 Performance Counters
    http://mindsharpblogs.com/ben/archive/2008/05/07/4806.aspx

    Thom Robbins .NET Weblog: InfoPath Tips and Tricks
    http://blogs.msdn.com/trobbins/archive/tags/InfoPath+Tips+and+Tricks/default.aspx

    Joel Oleson's Blog - SharePoint Land:
    Performance & Scale
    http://blogs.msdn.com/joelo/archive/tags/Performance+_2600_amp_3B00_+Scale/default.aspx

    Good List of Performance Counters
    http://blogs.msdn.com/joelo/archive/2007/01/16/good-list-of-performance-counters.aspx

    S.Y.M. Wong-A-Ton: Enterprise Solutions
    http://enterprise-solutions.swits.net/

    Paul Vick - Panopticon Central: The Ten Rules of Performance
    http://www.panopticoncentral.net/archive/2004/02/10/270.aspx

    Technorati - infopath Blogs, Photos, Videos and more on Technorati
    http://technorati.com/tag/InfoPath

    Discussions in Infopath General Questions
    http://www.microsoft.com/office/community/en-us/default.mspx?dg=microsoft.public.infopath&lang=en&cr=US
    Use this newsgroup to communicate with the InfoPath community.

    MSDN Forums: SharePoint - InfoPath Forms Services
    http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=1206&SiteID=1
    This forum is another place you can ask questions about Forms Services.

     

  • Microsoft InfoPath 2010

    REMINDER: Learn about InfoPath 2010 in Free Web Casts

    • 0 Comments

    If you want to learn more about InfoPath and SharePoint 2010 directly from the Microsoft product team, then sign up for the InfoPath 2010 Academy Live Series.

    There are 2 remaining sessions in the series. The next session “Form-Driven Mashups using InfoPath and SharePoint 2010", presented by Nick Dallett, an InfoPath program manager lead, will take place on Wednesday, April 7th from 8:30 AM to 10:00 AM (PST).

    If you missed our first 2 sessions, “An introduction to SharePoint applications using InfoPath 2010” and "Building SharePoint Applications with InfoPath 2010", you can view them on demand here. Just click the “Register Now” button.

    This is a great opportunity to learn all about our new features and scenarios directly from the product team, so sign up now!

    infopath_banner_ad_1_3

  • Microsoft InfoPath 2010

    Use patterns (e.g., digits or quotes) to validate data in InfoPath

    • 3 Comments

    Example 1: How do I restrict the user from entering special characters into certain fields in the InfoPath Form?

    Note: This example assumes you are running InfoPath 2003 with the SP-1 feature enhancements enabled. [Added 6/21/04]

    The easiest way to do this is to use pattern for data validation. For example, you might want a user to enter data in the ###-##-#### format for the Social Security Number field. If the user’s input does not match this format, you may want to throw an alert. You can achieve the above by doing the following:

    1. In Design mode, insert a Textbox Control
    2. Double click on the Textbox Control to get the properties dialog box
    3. Click on Data Validation | Add
    4. Choose “does not match pattern” from the second dropdown and “select a pattern” from the third dropdown
    5. Click on “Social Security number” from the standard patterns dialog

      Picture of the Data Entry Pattern dialog
    6. Click OK to accept the changes
    7. In the Data Validation dialog, choose “Dialog box alert” from the Error alert type dropdown and specify some alert message

      Picture of the Validation dialog
    8. Click OK to accept the changes
    9. You can test your form by clicking on the Preview Form button, in the toolbar  

    Example 2: I cannot put a double quote (“) or an apostrophe (‘) in the pattern builder. How do I validate data against a pattern that contains a double quote (“)?

    You can validate data against a pattern that contains double quotes by using Jscript regular expression. For example, you might want a user to enter data in the “###” format (a pattern contains double quotes) for a field. If user’s input does not match this format, you may want to throw an alert. You can achieve the above by doing the following:

    1. In Design mode, insert a Textbox Control
    2. Double click on the Textbox Control to get the properties dialog box
    3. Click on Data Validation
    4. In the Script section, choose “OnAfterChange” from the dropdown and Edit

    Picture of the Data Validation dialog

    1. Add the followings to your code  

    function msoxd_my_field1::OnAfterChange(eventObj)

    {

    // Write code here to restore the global state.

                    if (eventObj.IsUndoRedo)

                        {

    // An undo or redo operation has occurred and the DOM is  read-only.

                                    return;

                         }

     

    // A field change has occurred and the DOM is writable. Write code here to respond to the changes

     

                    // Specify your pattern using Jscript regular expression

                    var re1 = new RegExp(“\x22\\d\\d\\d\x22”);

     

                    // Get the field value

    var s = XDocument.DOM.selectSingleNode(“my:myFields/my:field1”).text;

     

    // Find a match within string s

    if (re1.exec(s) = = null && eventObj.Operation = =  “Insert”)

                    XDocument.UI.Alert(“User input does not match the required pattern”);

                    }

     

    1. After editing all the code, click OK to accept the changes
    2. You can test your form by clicking on the Preview Form button, in the toolbar
  • Microsoft InfoPath 2010

    Open your rolodex from InfoPath using the Contact Selector

    • 8 Comments
    Speaking of Outlook integration, Microsoft Office 2007 includes a new control that enables you to choose one or more e-mail address from the address book.
     
    You can add this control to InfoPath’s list of custom controls by using the Add or Remove Custom Controls wizard like you would for any other ActiveX control.  When registering the control, you can choose most of the default options. However, you must choose "Field or Group (any data type)" in the "Specify Data Type Options" page of the wizard. If you don't choose this binding type, the control will be disabled when you try to fill out the form.
     
    When you insert this control in a form template, it looks like this:
     
     
    When you insert this control in design mode, only a group node is added to the data source. You must manually add additional fields in order for this control to work correctly. To determine the final data structure should be, open the properties dialog for the control and click on the "Items" tab. This tab lists the schema structure that is required.
     
    As I mentioned, you must manually add these fields to the data source. This can be quite painful if you want to use the control in a lot of form templates. However, here’s a little trick.  You can create a Template Part that contains only the data structure and no controls in the view. Now, when you need to use the Contact Selector, first insert the Template Part to create the data structure.  (This will insert an empty Section control into the view which you can then remove.)  Then, go to the data source, right-click on the group node that was inserted, and select Contact Selector from the More menu.
     
    Template Parts don't support ActiveX controls so you can't insert the Contact Selector into the template part which would make this even easier. However, using this empty template part that contains only the data structure is still easier than creating the structure from scratch each time.
     
    Scott Roberts
    Senior Development Lead
Page 4 of 12 (298 items) «23456»