Showing posts with label InfoPath. Show all posts
Showing posts with label InfoPath. Show all posts

Friday, 13 July 2012

InfoPath 2010 – Error “The amount of data that was returned by a data connection has exceeded the maximum limit that was configured by the server administrator.”

the error message on the screen, (below is an example)

DataConnErr


So lets talk thru the issue.


Problem


So they are using SharePoint 2010 Enterprise, and InfoPath Form Services.  The form in question is a monster custom InfoPath form.  It uses every custom option you can think of, with popup tool tips, custom controls, workflows tied it, and has Java and .NET running some logic.  Generally a “WHY, WHY WOULD YOU DO IT” form.


The size of the form can also be huge when saved with about 5 different Rich Text fields that customers and Support folks put links, images, etc. in.  I have seen forms go in 12 mb in size. 


When they attempt to load these files, or open a view with all these files in it (7500 list items) the are getting that lovely warning.




“The amount of data that was returned by a data connection has exceeded the maximum limit that was configured by the server administrator. Form elements, such as drop-down lists may be blank.”



Solution


So this is an easy fix.


Go to Central Administration > General Application Settings > Configure InfoPath Form Services


Down on the page you are going to see a Data Connection Response Size.  It is defaulted to 1500 kilobytes.


033111_1610_DataConnect2

Change that setting to support your needs, in this case 4500 kilobytes solved the problem.

Once adjusted…..TADA it was reacting just fine, all was well and the Support team was back in action.

Conclusion

So you might ask was this the best solution.  NO, but this was a quick fix.  What additional information should you take from this use case…….FORM REWORK.

The form is out of control,  a new requirements gathering and analysis should be performed to determine a solution that will limit the risk of data size, large list sizes, and responses.  I do expect this content to be moved to a SQL Table, and the use of External Content Types, and Dataviews to support interaction in SharePoint.

Remember that there is a lot of size limitations and thresholds available in SharePoint Central Administration.  Any service you are using can run into this. It is important to have your service limitations documented, and have a running log of these error your SharePoint Admin can reference.  Also this change needs to be documented in the Governance Control documentation, and should be brought up in the next SharePoint Steering Committee.  Use it as an opportunity, not a scar.

Wednesday, 16 May 2012

Retrieve the current username for an FBA user in IP2010

have to use fully trusted forms...might as well use administrator approved forms as well so you dont have to mess with certificates...and use some code like this:

int index = 0;
userName = (this.Application.User.LoginName);
if (userName.Contains("sqlmembershipprovider"))

{
index = userName.IndexOf("sqlmembershipprovider|") + 22;
userName = userName.Substring(index, userName.Length - index);
}

Wednesday, 18 April 2012

InfoPath Forms Server, Data Sources and Authentication



OK, So I put together a nice little InfoPath form, nothing too flash – it collects some data about a site and sub sites and then goes ahead and calls a web service to create the site, sub sites and sets permissions.

Problem is that while the form works fine in the InfoPath client if I try to use it as a browser enabled form in SharePoint (which I need to do) it fails to make the data connection calls.

It’s a permission thing, basically SharePoint doesn’t pass the user credentials to the web service so the web service denies the connection.

Trying to work around it, I first thought it was to do with form trust so I fully trusted the form which meant that when I deployed it it forced me to deploy it as an administrator approved form. In simple terms it saves the form on the file system, the administrator uploads it to the central form template library (Central Administration > Application Management > Manage Form Templates) and deploys it to a site collection. This puts a feature wrapper around the form and deploys it as a content type. Apply the content type to a library and hey presto…

So I did that and it still didn’t work, that’s when I figured it was authentication and not trust that was causing the issue.

Basically to use data connections in InfoPath Forms Server (IFS from now on) you will need to create a Universal Data Connection (UDC) and store it in a Data Connection Library (DCL)… ’nuff acronyms ;-)

  • UDC = a file that stores (in plain text!) authentication details and the details of the web service (or whatever) you need to connect with.

  • DCL = just like it sounds this is where you put the UDC


So how do you write a UDC?


There’s a decent overview here: http://blogs.msdn.com/infopath/archive/2006/10/02/Data-Connections-in-Browser-Forms.aspx and if you’re anything like me you’ll want to see an example so here we go:
<?xml version="1.0" encoding="UTF-8"?>
<?MicrosoftWindowsSharePointServices ContentTypeID="0×010100B4CBD48E029A4ad8B62CB0E41868F2B0"?>
<udc:DataSource MajorVersion="2" MinorVersion="0" xmlns:udc="
http://schemas.microsoft.com/office/infopath/2006/udc">
<udc:Name>CreateSite</udc:Name>
<udc:Description>CreateSite</udc:Description>
<udc:Type MajorVersion="2" MinorVersion="0" Type="WebService">
<udc:SubType MajorVersion="0" MinorVersion="0" Type=""/>
</udc:Type>
<udc:ConnectionInfo Purpose="ReadWrite">
<udc:WsdlUrl>
http://hp-vs-moss2007:555/HP.WebServices.CreateWorkspace.asmx?wsdl</udc:WsdlUrl>
<udc:SelectCommand>
<udc:ServiceUrl>
http://hp-vs-moss2007:555/HP.WebServices.CreateWorkspace.asmx</udc:ServiceUrl>
<udc:SoapAction>HP.WebServices.CreateWorkspace/Create</udc:SoapAction>
</udc:SelectCommand>
</udc:ConnectionInfo>
</udc:DataSource>

You’ll notice that in my example above there are no authentication details. Well…that’s because I forgot to put them in! And what I actually found was that simply by using the UDC method authentication started working, I haven’t had time to look into this but I assume this is because by the very virtue of using a UDC connection held in a SharePoint library PassThrough authentication is being used. I then started adding some cod ethat runs under elevated privileges and ran into some problems, so put the authentication details back in again ala:

How do you ‘do’ one of these DCL things?


That’s easy ;-) It’s just like a document library in SharePoint. Go the the root of your site collection (that usually a site like http://server/sites/xxxx) and click Site Actions then Data Connection Library, give it a name and hey presto.

Now upload your UDC to your DCL and remember to approve the UDC.

Getting it to work with Infopath


This bit is the simple bit

  1. You create a new data connection (Tools -> Data Connections -> New -> Search for Connections on MOSS -> Add your site -> Select the UDC)

  2. And then use it as you would any other data connection


So what have you achieved?


Well you’ve kind of abstracted web service and InfoPath form so you now need to go through the UDC to get to the web service calls, of course you can go direct to the web service for normal InfoPath forms but not for web based forms. Is it good thing? Not sure, I’ve read posts saying that it makes things better because your connections are in a central library and can be shared between forms and I guess that’s something but then I can secure my form library, web service, web application etc anyway so do I really need another layer of security?

Anyway, it’s the only way it works so you’re stuck with it for now.

 

Friday, 13 April 2012

Submitting to 'this' document library

Have you ever needed to develop an InfoPath form template that submits back to a SharePoint document library but you did not initially know the server or library name when developing the form? Or have a scenario where your InfoPath form template could be published (or added as a content type) to multiple SharePoint document libraries and you need the submit location to be dynamic? Well read on to find out how you can do this!

When you create an InfoPath form template that needs to be able to submit to a SharePoint document library, you need to specify that connection in the initial design of the form template. However, at run time you can use managed code to determine the server and library name where the form was launched and then modify the “FolderUrl” property of the submit data connection so the form is submitted to the appropriate library.

So let’s get started setting up this sample. The C# walkthrough below uses the new InfoPath 2007 managed object model; below, you will find attached the same logic implemented in InfoPath 2003 managed object model and in InfoPath 2003 JScript.

Step 1: Create a sample InfoPath Form Template

Create a browser-compatible form template as following:

  1. Add 3 text box controls, all with a data type of text, named as follows: strFormURL, strLocation and strFolderName

  2. Add a “Submit” data connection named “Mainsubmit”:

    • Set the document library name to a dummy SharePoint document library (i.e. http://server/dummyLib)

    • Use the concat function to concatenate the strFolderName field and _Test for the File Name property: concat(my:strFolderName, "_Test")

    • Enable the Allow overwrite if file exists property



  3. Set the Security Level of the form to Full Trust and sign the form template with a digital certificate

  4. Enable the Submit functionality (Tools | Submit Options) and choose the “Perform custom action using code” option


Now that we have the form, controls and submit functionality, let’s add the code to make this process work:

 

Step 2: Add the code

  • Click the Edit Code button on the Submit Options dialog

  • Create the following FormState Dictionary object – this will be used to store the form’s location when the form is initially opened:


private object _strUri
{
get { return FormState["_strUri"];
set { FormState["_strUri"] = value; }
}

 

  • Add the following code to the Forms Loading event:


// Get the Uri (or SaveLocation in a browser form) of where
// the form was opened.
// See if the form was opened in the browser

Boolean OpenedInBrowser = Application.Environment.IsBrowser;

// If so, we will get the "SaveLocation" from the InputParameters

if (OpenedInBrowser)
_strUri = e.InputParameters["SaveLocation"].ToString();
else

//If it was opened in the client, we will get the Uri
_strUri = this.Template.Uri.ToString();

 

// Populate the fields on the form - keep in mind, this

// not necessary - this is simply to see the results

PopulateLibInfo(OpenedInBrowser);

 

  • Add the following procedure to the Forms class:


private void PopulateLibInfo(Boolean OpenedInBrowser)

{

// Create a Navigator object for the main DOM
XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();

 

 

// Create Navigator objects for each field

XPathNavigator xnFormURL = xnDoc.SelectSingleNode("my:myFields/my:strFormURL", this.NamespaceManager);
XPathNavigator xnLocation = xnDoc.SelectSingleNode("my:myFields/my:strLocation", this.NamespaceManager);

XPathNavigator xnFolderName = xnDoc.SelectSingleNode("my:myFields/my:strFolderName", this.NamespaceManager);

 

// Get the Uri stored in the FormState Dictionary variable

string strUri = _strUri.ToString();

 

// Create a variable to store the path (URL) to the document library

string strPath = "";

if (OpenedInBrowser == true) {

//If we are open in the browser, the strUri value is just

//the server name and library - so we just need to get

//the URL without the last "/"

strPath = strUri.Substring(0, strUri.LastIndexOf("/"));

} else {

// Parse just the path to the document library -

// this would return something like this:

//  http://server/library

strPath = strUri.Substring(0, strUri.IndexOf("Forms") - 1);
}
// Now, parse the URL to where the document library resides;
// this would return something like:

//    http://server or http://server/site
string strLoc = strPath.Substring(0, strPath.LastIndexOf("/"));

 
// Lastly, parse the URL to return just the document library name -

// in this case,we are looking for the last "/" character

// knowing that what comes after this is the document library name

string strFolder = strPath.Substring(strPath.LastIndexOf("/") + 1);

 

// Populate the fields on the form – we will use these

// values in the Submit process

xnFormURL.SetValue(strUri);

xnLocation.SetValue(strLoc);

xnFolderName.SetValue(strFolder);
}

 

  • Add the following code to the form’s Submit event:


// Create a Navigator object for the main DOM
XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();
// Create Navigator objects for the fields we will

// use to modify the FolderUrl
XPathNavigator xnLocation = xnDoc.SelectSingleNode("my:myFields/my:strLocation", this.NamespaceManager);
XPathNavigator xnFolderName = xnDoc.SelectSingleNode("my:myFields/my:strFolderName", this.NamespaceManager);

 

// Get a reference to the submit data connection

FileSubmitConnection fc = (FileSubmitConnection)this.DataConnections["Main submit"];

 

// Modify the URL we want to submit to by concatenating the

// xnLocation and xnFolderName values

fc.FolderUrl = xnLocation.Value + "/" + xnFolderName.Value;

 

// Execute the submit connection

try

{

fc.Execute();

e.CancelableArgs.Cancel = false;

}

catch (Exception ex)

{

e.CancelableArgs.Cancel = true;
}

 

  • Build and save the project

  • Publish and test


And that is it! You now have an InfoPath form template that will submit to whatever document library the form was opened from so you do not need to know this information when designing the template.

The xsi:nil attribute in InfoPath

Have you ever tried to programmatically set a value on a field only to get a “schema validation” error? Many times, this error is caused by the “nillable” attribute being present on the node. The nillable attribute is a special attribute that can appear on an xsd:element within an XML schema. If an element has the xsi:nil attribute specified, it indicates that the element is present but has no value, and therefore no content is associated with it.

However, if you attempt to programmatically set a value on this node and the nillable attribute is present, you will get an error similar to: “Schema validation found non-data type errors.” You will find the nillable attribute is typically present on the following data types:

  • Whole Number (integer)

  • Decimal (double)

  • Date (date)

  • Time (time)

  • Date and Time (dateTime)


To resolve this error, your code will simply need to test if the nil attribute is present and if so, remove that attribute before setting the value on the node. The following sample procedure takes an XpathNavigator object, checks that node for the nil attribute and if it exists deletes the attribute:
public void DeleteNil(XPathNavigator node)

{

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

node.DeleteSelf();

}

The above procedure is generic - you can easily call this procedure as needed before programmatically trying to set the value of a field. As an example, this code is called from the click event of a button:
//Create a Navigator object for the main data source

XPathNavigator xn = this.MainDataSource.CreateNavigator();

 

//Create a navigator object for the field (node)

//where we want to set the current date value

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

 

//Check if the "nil" attribute exists on this node

DeleteNil(xnfield1);

 

//Create a new dateTime object for the current date

DateTime curDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);

 

//Set the value of field1 to the current date in the

//correct format: yyyy-mm-dd

xnfield1.SetValue(curDate.GetDateTimeFormats().GetValue(5).ToString());

Create function in infopath form from sharepoint list value

First, you need to set an onChange event on your 2 dropdown boxes. To do so, right click your dropdown boxes --> programming --> change event. This will create a visual studio project with an empty function for your dropdown box. In this function, write this code (or something similar) :

XPathNavigator root = MainDataSource.CreateNavigator();
string FirstName = root.SelectSingleNode("<XPath of your FirstName dropdown box>", NamespaceManager).Value;
string LastName = root.SelectSingleNode("<XPath of your LastName drop down box>", NamespaceManager).Value;


SPSite oSiteCollection = newSPSite(<URL of your server, eg http://portal/>);
SPWeb oWebsiteSrc = oSiteCollection.AllWebs["<URL of the site containing the sharepoint list, eg /sites/finance/expenseaccount>"];
SPList oList = oWebsiteSrc.Lists["<Name of your list>"];

string camlQuery = "<Where><And><Contains><FieldRef Name='Name of the FirstName column'/><Value Type='Text'>" + FirstName + "</Value></Contains><Eq><FieldRef Name='Name of the LastName column' /><Value Type='Text'>" + LastName + "</Value></Eq></And></Where>";
SPQuery query = newSPQuery();
query.Query = camlQuery;


SPListItemCollection collListItemsSrc = oList.GetItems(query);

root.SelectSingleNode("<XPath of your Age Field>", NamespaceManager).SetValue(collListItemsSrc[0].GetFormattedValue("<Name of the Age column>"));

 

An error occurred accessing a data source : Browser enabled infopath Error in MOSS 2007

“An error occurred accessing a data source.”
Generally it is due to database or webservice connection. If you are getting this error
Then
1. First make sure the user has sufficient permission to access the database/web service.
2. In infopath ->Tools ->Form Options ->Security and trust ->Uncheck “Automatically determine security level” (If database/webservice is on same domain then select domain else select proper option)
3. Convert your data connection in udcx file.
For this, create a data connection library in MOSS.
Now open infopath form -> tools->Data connections
Select data connection and click on “Convert… “ button.
Give data connection library url with file name.
4. Now open Data Connection Library and Right click on udcx file -> “Approve/Reject” -> Select Approve and click OK.
5. Goto Central Administration ->Application Management->configure infopath form services->
“Allow user form templates to use authentication information contained in data connection files” option must be checked.

 An error occurred accessing a data source : Browser enabled infopath Error in MOSS 2007

If your database/web service is placed on another domain then you need to check next option “Allow cross-domain data access for user form templates that use connection settings in a data connection file”.

Hope, It helps!!!

Add a Custom Style Sheet to Infopath

InfoPath view .xsl files contain three or four standard internal style sheets, depending on whether you have specified a color scheme. These can be identified by the attributes controlStyle='controlStyle', tableEditor="TableStyleRulesID", languageStyle='languageStyle', and themeStyle='urn:office.microsoft.com:themeBlue'. Never modify any of these standard internal style sheets. InfoPath often regenerates these, which will cause you to lose any changes you make to them.

You can add your own custom internal or external style sheet to any or all of the view .xsl files in your form template. The best place to add it is after the InfoPath standard style sheets because styles have reverse order precedence, meaning the last value for an identical selector property wins. If both you and InfoPath have specified a value for the border property of the table selector, whichever one appears last will override the value for the same selector property of any preceding style sheet.

You might use HTML and class selectors when writing your own styles. ID selectors will not be useful because InfoPath will not allow you to place an ID attribute on an element in the XSL. This is because InfoPath autogenerates ID attributes when it creates the view.

 






div {...} <!-- HTML Selector: This will work fine. -->
.myClass {...} <!-- Class Selector: This will work fine. -->
#myId {...} <!-- ID Selector: Not useful. You cannot use custom IDs on elements -->

 


INTERNAL STYLE SHEETS


Internal style sheets are stored directly in the view .xsl file, just as the InfoPath standard style sheets are. If you want to use the same styles across multiple views you will need to copy the styles from one view .xsl file to another. Let's review the steps to add an internal style sheet.


Add a custom internal style sheet:

  1. Choose Extract Form Files from the File menu.

  2. Select a location to save your extracted form files to, and then click OK.

  3. Close InfoPath to release the lock it places on your form files.

  4. Using a text editor, open your view .xsl file.

  5. Add the following code just below the last style element:


 






<style title="myCustomStyleSheet" type="text/css">
table { FONT-FAMILY: Courier New; BORDER: solid 1px black; }
</style>

 

  1. Save your view .xsl file, and then close the text editor.

  2. Reopen your form template by right-clicking the manifest.xsf file and choosing Design.


Your custom styles should now be visible in the designer. Internal styles must be updated per view .xsl file, which can create inconsistencies if you forget to update one of the .xsl files. If you want to use the same styles across multiple views, you should consider using external style sheets instead. You can always override external styles for a particular view by using a combination of external and internal style sheets.


EXTERNAL STYLE SHEETS


External style sheets exist in separate .css files. They must be added to the form template as resource files as well as referenced in any view .xsl file that will use them. By using external style sheets you maintain a consistent set of styles across all of the views that reference them. Let's review the steps to add a custom external style sheet named myCustomStyleSheet.css.

Add a custom external style sheet as a resource file:

  1. Choose Resource Files from the Tools menu.

  2. In the Resource Files dialog box, click Add.

  3. In the Add File dialog box, navigate to and select the myCustomStyleSheet.css file, and then click OK. Figure 1 shows the file added as a resource.

  4. Click OK to close the Resource Files dialog box.


 

Figure 1. The myCustomStyle.css file has been added as a resource file.

Link to a custom external style sheet from your view .xsl file:

  1. Choose Extract Form Files from the File menu.

  2. Select a location to save your extracted form files to, and then click OK.

  3. Close InfoPath to release the lock it places on your form files.

  4. Using a text editor, open your view .xsl file.

  5. Add the following code just below the last style element:


 

 






<link href="mySstyle.css" rel="stylesheet" type="text/css"/>

 

 

  1. Save your view .xsl file, and then close the text editor.

  2. Reopen your form template by right-clicking the manifest.xsf file and choosing Design.


Your custom styles should now be visible in the designer. If you added the link element to the view .xsl file before you added the .css file as a resource, or if you later update the resource file, your updates will not be visible in the designer until you save and reopen your form template. They will, however, be visible in the form preview before you save and reopen your form template.

As long as your internal and external style sheets appear last you should not have any trouble with InfoPath overriding any of your values. However, if a scenario is encountered where a value in one of the InfoPath standard style sheets is still causing you trouble by overriding your value, add the !important declaration to yours. This will force your value to always be chosen.

 






table { FONT-FAMILY: Wingdings !important; }

 

Finally, it should be noted that inline styles are normally chosen over internal or external styles because they appear last. The !important declaration on an internal or external style will override a value on an inline style unless the inline style also uses the declaration. In other words, the !important declaration also follows the reverse order precedence.

Friday, 17 February 2012

How to use Form Templates for InfoPath Forms Services inside Project Server 2010/SharePoint 2010 Web Application

1- After you deploy your InfoPath form, you should see this screen form Central Administration -> General Application Settings -> Manage Form Templates
(then install it and you can enable it from your Site Collection Features as well)

3- So, you need to create new Form Library that will use InfoPath Form Template:

4- From Library Settings, Advanced Settings, Set Allow management of content types equal True

5- then add your Forms Services to form content and make it the default - Add Content Type and select your InfoPath Form Template:

6- Finally, you have a form library of content InfoPath Forms Services:

 

Submitting InfoPath to a SharePoint List

As you know, submitting to a Microsoft Windows SharePoint form library from an InfoPath form is quite simple: just add a “submit” type of data connection to InfoPath and away you go. However, submitting to a SharePoint List is another matter. In this post, we will take a look at the steps necessary to enable this functionality.

Step 1: Create the list

1. Create a new custom list named: MyContacts
2. From the Settings button choose List Settings
3. Click Create Column
4. Add the following columns/data types:

  • FirstName, Single line of text

  • LastName, Single line of text

  • Email, Single line of text

  • Phone, Single line of text


The next step is to create a Collaborative Application Markup Language (CAML) template that contains the same XML nodes as the columns we added to our list – this will be used as a secondary data connection in the InfoPath Form Template.

Step 2: Create the CAML template

1. Launch Notepad (or any text editor)
2. Copy and paste the following code to the Notepad document:
<?xml version="1.0" encoding="UTF-8"?>
<Batch OnError="Continue">
<Method ID="1" Cmd="New">
<Field Name='Title'></Field>
<Field Name="FirstName"></Field>
<Field Name="LastName"></Field>
<Field Name="Email"></Field>
<Field Name="Phone"></Field>
</Method>
</Batch>

3. Save this as: Add List Item Template.xml

 

Step 3: Create the InfoPath Form Template

1. Create a new, blank, browser-compatible form template
2. Add a “Receive” type secondary data connection to the Add List Item Template.xml file created in Step #2. (Make sure the options “Include the data as a resource file in the form template” and “Automatically retrieve data when the form is opened” are enabled.)
3. Add a “Receive” type secondary data connection to the “MyContacts” SharePoint List created in Step #1 and make sure the option “Automatically retrieve data when the form is opened” is enabled.
NOTE: Be sure to include the “Title” field along with the custom fields we created.

Each SharePoint list is created with a unique identifier called a GUID. In order to submit items to a SharePoint list, you must know the unique GUID for that list. These next steps will enable you to identify the GUID for your “MyContacts” list.

Step 4: Identify the list GUID

1. Open a browser and navigate to the MyContacts list
2. From the Settings menu choose List Settings
3. In the browser’s address bar you will see the URL appended with “List=”



 

4. Copy everything after the equals sign and paste this into a text editor as we will need this value later on.

NOTE: We will need the list GUID to be formatted as “{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”. If your GUID appears as above with the hyphens and braces “escaped” (i.e. %7B for the braces and %2D for the hyphens) then you will need to replace the escaped characters with the braces and hyphens so when we use this GUID later, it will appear as: {1E76517B-2C36-4473-A420-A737D98589BC}

Step 5: Add controls to the InfoPath Form Template

1. Open the Data Source Task Pane
2. From the Data Source dropdown box choose the “MyContacts” connection



3. Right-click on “MyContacts” and choose Repeating Table – this will add a repeating table bound to that connection to your View
4. From the Data Source dropdown box choose Main
5. Add a text box to the “myFields” node named: ListName and set the Default Value property to the GUID value of your list – we will use this node to specify the list when we perform the Submit operation



 

To update the SharePoint list we will be using the “UpdateListItems” method of the SharePoint “lists.asmx” web service. This web method requires a couple of parameters (the list name and what gets updated) – now that we have added the “ListName” node which contains the GUID and we have the Add List Item Template XML data connection which describes our data structure we have all the necessary information to add the “UpdateListItems” web method!

Step 6: Add the “lists.asmx” web service

1. Add a new “Submit” type of web service data connection to the “lists.asmx” web service – this is typically located at: http://servername/_vti_bin/lists.asmx
2. Select the “UpdateListItems” operation
3. Double-click the “listname” parameter and assign the “my:ListName” node as the value



4. Double-click the “updates” parameter, select the “Add list Item Parameter” data source, select “Batch” and click OK
5. For the “Include” option select “XML subtree, including selected element”



6. Complete the Data Connection Wizard

Now that we have all the connections that are required, we now need to add the “submit” functionality to the form template.

Step 7: Add Submit functionality

1. Display the Data Source Task Pane
2. From the Data Source dropdown box choose the Add List Item Template data connection
3. Drill down through the data source, right-click on the Field node and choose Repeating Table



 

We need to change the text box control in the “Name” column to Read-only – if these values were to be changed it would affect the CAML and the submit would fail.
• Double-click on the text box in the Name column of the Repeating Table
• Select the Display tab
• Enable the Read-only property and click OK
• Add a new Button control to the View
• Double-click the button to display the Properties
• Click the Submit Options button
• Enable the option “Allow users to submit this form”
• Enable the option “Perform custom action using Rules” and click the Rules button
• Click the Add button
• Click the Add Action button
• From the Action dropdown box choose “Submit using a data connection”, select the “Web Service Submit” data connection and click OK
• Click the Add Action button
• From the Action dropdown box choose “Query using a data connection”, select the “MyContacts” data connection and click OK (this will automatically refresh the list in InfoPath so you can see the newly added record)



• Click OK until you are back to your form

NOTE: If you want to automatically clear out the submitted values, add another action to this Rule to “Set a field’s value” and the only option you need to specify is the “Field” option – select the “Field” node from the “Add List Item Template” data connection and then simply leave the Value option blank.

Step 8: Test!

1. Click the Preview button to preview the form
2. Fill in values for each of the fields: Title, First Name, Last Name, E-mail and Phone



3. Click the Submit button – the contact information should be submitted successfully and the “MyContacts” list automatically updated!

SharePoint 2010 Fields Validation

In SharePoint 2007 we have many issues with field validation when we add a new item to the list. So I solved it with JavaScript and I solved it with InfoPath Forms but it has never been easy.

In SharePoint 2010 we have great tools to perform field validation on the page without spending hours.

The first option is very intuitive. You can set the basic validation using the usual calculated fields functions during the creation of your field. You can use Excel functions just like I used it in the picture below to find out if some text appears in the field value or not. You can also build any other validation you want.



The User description field will show your users explanation about the content you want to see in the field. It will appear in red text under your field, like the example below.



Here are a few examples of field validation functions:

E-mail validation:

=AND((FIND(“@”,[E-mail filed])<>0),( FIND(“.”,[E-mail filed])<>0))

The AND function allows you to check more than one condition.

Today date validation:

=[Date field]>Today()

The second way to perform field validation is to edit the list forms using the InfoPath application.

This gives you really powerful abilities to edit your list forms. If you choose this method you’ll have much more options to design and validate your fields. For example: you can change the color of your field if it has not passed validation.

So, how do we do it?

Enter your list and click the “Customize Form” link. This link will open the InfoPath application (so make sure InfoPath is installed at your machine first). This button will design the “New”, “Edit” and “Design” forms but you will need to design it only once.



When the InfoPath form is opened you will see all the fields of your list at the left side of the window and you can add these fields to the form.

Let’s create some validation! Choose the field you want to validate and click the “Add Rule” button on the Ribbon.



Then click the “New” button and create a new Validation rule. You can also add a formatting rule to change the design of your fields that based on similar conditions. This is the “Conditional Formatting”, just a little redesigned.

Add a new validation rule. Click on “None” link under the “Condition” title to create new conditions.







Now it’s time to publish the form back to our SharePoint list. This is very easy to do. Just press the “File” option in the Ribbon and press the big “Quick Publish” button. That’s all. Now you have this validation in your SharePoint list forms.



Introduction to Programming in InfoPath 2010

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

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

  • A custom sort interface

  • Logic for managing complex data when the form is submitted

  • Logic to add items to a SharePoint list


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

Equipment Request Form


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

  1. A SharePoint form library, “Equipment Orders”, where users go to fill out the Equipment Order Request form shown below.

  2. A SharePoint list, “Equipment Inventory”, which stores the items available for users to order. This list contains fields specifying items’ names, descriptions, and quantities used to populate the Equipment Order Request form.

  3. A SharePoint list, “Equipment Shipping”, which stores a list of items ordered by users that have been scheduled for shipping. This list contains fields for the names and quantities of items being ordered as well as the name of the user who placed the order.


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

Equipment Order Request Form

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

Equipment Order Request Form

Sorting data in the form


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

Equipment Order Request Form

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

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

{

  // return the value of the specified node

  XPathNavigator myNav = this.MainDataSource.CreateNavigator().SelectSingleNode(xpath, NamespaceManager);

  if (myNav != null)

    return myNav.Value;

  else

    return "";

}

private void Swap(string xpath1, string xpath2)

{

  // swap two rows of the table

  XPathNavigator item1 = this.MainDataSource.CreateNavigator().SelectSingleNode(xpath1, NamespaceManager);

  XPathNavigator item2 = this.MainDataSource.CreateNavigator().SelectSingleNode(xpath2, NamespaceManager);

  if (item1 != null && item2 != null)

  {

    // Make a copy of item1

    // Move item2 to item1

    // Make the original item2 be item1 that we cloned earlier


    XPathNavigator item1Clone = item1.Clone();

    item1.ReplaceSelf(item2);

    item2.ReplaceSelf(item1Clone);

  }

}

private void SortOrder(string sortBy)

{

  string itemsToSort = "/my:myFields/my:Order/my:OrderItem";

  XPathNodeIterator items = this.MainDataSource.CreateNavigator().Select(itemsToSort, NamespaceManager);

  if (items != null)

  {

    int numItems = items.Count;

    // basic bubble sort implementation

    for (int i = 1; i < numItems; i++) // xpath is 1-based

    {

      for (int j = i + 1; j <= numItems; j++)

      {

        // swap (i,j) if necessary

        string iValue = GetValue(itemsToSort + "[" + i + "]" + sortBy);

        string jValue = GetValue(itemsToSort + "[" + j + "]" + sortBy);

        if (String.Compare(iValue, jValue, true) > 0)

          Swap(itemsToSort + "[" + i + "]", itemsToSort + "[" + j + "]");


      }

    }

  }

}

public void ItemNameSort_Clicked(object sender, ClickedEventArgs e)

{

  // Sort order by ItemName

  // Repeat this code for the other buttons

  string sortBy = "/my:ItemName";

  SortOrder(sortBy);

}

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


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

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

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

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




public void FormEvents_Submit(object sender, SubmitEventArgs e)

{

  // Loop through each item-quantity pair in the order form.

  // Submit pairs to the Equipment Shipping list.

  // Note: Workflow will handle updating item quantities and track shipping status.

  using (SPSite mySite = new SPSite(ServerInfo.SharePointSiteUrl.ToString()))

  {

    using (SPWeb myWeb = mySite.OpenWeb())

    {

      XPathNodeIterator orderItems;

      if (myWeb != null && myWeb.Lists["Equipment Shipping"] != null)

      {

        SPList shippingList = myWeb.Lists["Equipment Shipping"];

        myWeb.AllowUnsafeUpdates = true;

        orderItems = this.MainDataSource.CreateNavigator().Select("/my:myFields/my:Order/my:OrderItem", NamespaceManager);

        if (orderItems != null)

        {

          while (orderItems.MoveNext())

          {

            // Add rows from the form where user selected an item and specified a quantity.

            string itemName = orderItems.Current.SelectSingleNode("./my:ItemName", NamespaceManager).Value;

            string itemQuantity = orderItems.Current.SelectSingleNode("./my:ItemQuantity", NamespaceManager).Value;

            if (itemName != string.Empty && itemQuantity != string.Empty)

            {

              SPListItem shipItem = shippingList.AddItem();

              shipItem["Title"] = itemName;

              shipItem["Quantity"] = itemQuantity;

              shipItem.Update();

            }

          }

        }

      //cleanup

      //signal successful submit

      //return

      myWeb.AllowUnsafeUpdates = false;

      e.CancelableArgs.Cancel = false;

      return;

      }

    }

  }

}

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

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

How to add code to an InfoPath form


To add code to an InfoPath form:

  1. Make sure you meet the minimum system requirements.

  2. Install Visual Studio Tools for Applications (VSTA).

  3. Choose a programming language.

  4. Add event handlers and code.


Minimum system requirements


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

Installing Visual Studio Tools for Applications


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

  1. Launch Office 2010 setup from your Office 2010 installation media or from the Control Panel Programs and Features application.

  2. If you’re installing a new copy of Office 2010, click the Customize button in the installer. If you’ve already installed Office 2010, choose the Add or Remove Features radio button in the installer.

  3. Set the Visual Studio Tools for Applications option to Run from My Computer and continue through the setup wizard.


Office Setup

Choosing a programming language


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

Developer Tab

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

Form Options

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

  1. Click the File > Options tab

  2. Click the More Options button in the General category of the InfoPath Options dialog

  3. Change the Programming language dropdowns in the Programming Defaults section of the Design Options


Options

Adding event handlers


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

Developer Tab

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

Developer Tab

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

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

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

Custom Code Button

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

Submit Options Button

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

Submit Options

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

Fields Taskpane

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

Tables

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

 

Domain trust forms can be published to SharePoint as Sandboxed Solutions directly from the InfoPath 2010 Designer. With Sandboxed Solutions, SharePoint Server farm administrators can restrict the resources available to the code and developers cannot access resources subject to operating system security. This establishes a safe environment where Site Collection administrators can publish code to SharePoint without the overhead of administrator approval!

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

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

Summary


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

Monday, 19 December 2011

Use Form Templates of InfoPath Forms Services in SharePoint 2010 Web Application

how to develop and deploy Form Templates for InfoPath Forms Services inside PS 2010 and applying some code behind using PSI to get Projects List as example. let's start :)
1- follow this article to develop and deploy your InfoPath Form (with code behind or not)
2- After you deploy your InfoPath form, you should see this screen form Central Administration -> General Application Settings -> Manage Form Templates
(then install it and you can enable it from your Site Collection Features as well)

3- So, you need to create new Form Library that will use InfoPath Form Template:

4- From Library Settings, Advanced Settings, Set Allow management of content types equal True

5- then add your Forms Services to form content and make it the default - Add Content Type and select your InfoPath Form Template:

6- Finally, you have a form library of content InfoPath Forms Services:

 

Friday, 16 December 2011

How to create a custom validation error message that contains the name of the control that is being validated in InfoPath

Microsoft Office InfoPath can automatically check the data that you enter in a form. InfoPath displays an error message if the value of the data does not match the condition that is specified by the data validation rule. The error message can appear in either of the following ways:

  • Dialog box error message: This is a data validation error message that opens a dialog box that displays a custom error message when data that is not valid is entered in a control.

  • Inline error message: This is a data validation error message that is available from the control. InfoPath marks a control with a dashed red border when that control contains data that is not valid. To view the inline error message from the control, the user right-clicks the control or hovers the pointer over the control to see the error message as a screen tip.


This article provides an example of how to create an inline error message from the user interface or from a script. This sample form you create will mark the "Age" text box control when the user-supplied value is less than 30 or more than 65. This inline message for this error will contain the name of the control.

Design the Form


In InfoPath 2010



  1. Start InfoPath.

  2. Create a new form.

  3. In the Fields task pane, right-click myFields , and then click Add .

  4. In the Add Field or Group dialog box, type Age in the Name text box.

  5. In the Data Type list, select Whole Number (integer), and then click OK .

  6. Move the Age field to the form.


In InfoPath 2003 or InfoPath 2007



  1. Start InfoPath. Create a new form.

  2. In the Design Tasks task pane, click Data Source to open the Data Source task pane.

  3. In the Data Source task pane, right-click myFields, and then click Add. In the Add Field or Group dialog box, type Age in the Name text box. In the Data Type list, select Whole Number (integer), and then click OK.

  4. Move the Age field to the form.


Add Data Validation by Using the User Interface


In InfoPath 2010



  1. Click to select the Age text box control.

  2. On the Home tab, click Add Rule, click Is Not Between, and then click Show Validation Error.

  3. In the ScreenTip text box of the Rules pane, type The value of the Age field must be greater than 30 and less than 65.


In InfoPath 2003 or InfoPath 2007



  1. Right-click the Age text box control, and then click Text Box Properties. In the Text Box Properties dialog box, click Data Validation.

  2. In the Data Validation (Age) dialog box, click Add.

  3. In the condition operator drop-down list, select is less than.

  4. In the condition value drop-down list, select Type a number, and then type 30.

  5. Click And.

  6. Change the new drop-down list box from And to Or.

  7. In the second condition operator drop-down list, select is greater than.

  8. In second condition value drop-down list, select Type a number, and then type 65.

  9. In the ScreenTip text box, type The value of the Age field must be greater than 30 and less than 65.

  10. Click OK three times to dismiss all the dialog boxes.


Add Data Validation by Using a Script


In InfoPath 2003, you can use a script for data validation.

  1. Right-click the Age text box control, and then click Text Box Properties. In the Text Box Properties dialog box, click Data Validation.

  2. In the Data Validation (Age) dialog box, select OnValidate from the Events list, and then click Edit.

    Microsoft Script Editor starts.

  3. Add the following code to the OnValidateevent for the Age field:


    function msoxd_my_Age::OnValidate(eventObj)
    {
    // Clear any previous errors for this node.
    XDocument.Errors.Delete(eventObj.Site,"InvalidValue");

    //Set the valAge variable to the value that is entered in the Age field.
    var valAge = parseInt(eventObj.Site.text);

    //If the value that is entered in the Age field is less than 30 or
    //greater than 65, add a passive error to the collection of the error.
    if ((valAge < 30) || (valAge > 65))
    {
    XDocument.Errors.Add(eventObj.Site,"InvalidValue","The value of the "
    + eventObj.Site.baseName + " field must be greater than 30 and less than 65.");

    }

    }



  4. Save the changes. Close Script Editor.

  5. Click OK to close the Data Validation (Age) dialog box, and then click OK to close the Text Box Properties dialog box.


Test the Form



  1. On the toolbar, click Preview Form.

  2. In the Age field, type 29, and then click outside the field.

    Notice the dashed red border that highlights the control. This indicates that the value is not valid.

  3. Move the pointer over the control.

    Notice that the screen tip displays the custom error message. The error message includes the name of the control that contains the data that is not valid.

Wednesday, 20 April 2011

How to Enqueue Submits While Offline



How to Enqueue Submits While Offline


Scenario:


User fills out forms for a particular form template while the laptop is disconnected from the network.  Upon reconnection, seamlessly syncrhonize the offline forms to a Windows SharePoint Services form library.



Solution:


Using OnSubmitRequest, you can have the code save to the offline folder depending on if we're offline or not, as in the following code, which is written in C# using our Visual Studio .NET Toolkit.  You will also need to add a project reference to System.Xml.dll and the using System.XML; directive to your form code.


public void OnSubmitRequest(DocReturnEvent e)



{


if (thisApplication.MachineOnlineState == XdMachineOnlineState.Online)

{

// submit to Sharepoint using DAVAdapter

(thisXDocument.DataAdapters["Submit to Sharepoint"] as DAVAdapter).Submit();

}

else

{

// We are offline or working offline.

XmlDocument oDOM = new XmlDocument();

Microsoft.Office.Interop.InfoPath.SemiTrust.IXMLDOMDocument oWrappedDOM = thisXDocument.DOM;


oDOM.PreserveWhitespace = true;

oDOM.LoadXml(oWrappedDOM.xml);

oDOM.Save("C:SubmitForm_"

+ DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss.ff") + ".xml");

}


e.ReturnStatus = true;

}


Then, if you've been offline for a while and a number of files have built up, you can run the following jscript to invoke InfoPath externally and force a submit looping through the files, as below:




var oFileSys = new ActiveXObject("Scripting.FileSystemObject");

var oSubmitDir = oFileSys.GetFolder("C:Submit");

var oFilesInSubmitDir = new Enumerator(oSubmitDir.Files);


var oApp = new ActiveXObject("InfoPath.Application");


var fso = new ActiveXObject("Scripting.FileSystemObject");


for (; !oFilesInSubmitDir.atEnd(); oFilesInSubmitDir.moveNext())

{

var strFileName = oFilesInSubmitDir.item().Name.toLowerCase();


if (strFileName.length >= 4

&& strFileName.lastIndexOf(".xml") == (strFileName.length - 4))

{

try

{

var oDoc = oApp.XDocuments.Open(oFilesInSubmitDir.item().Path);

oDoc.Submit();

oDoc.View.Window.Close();


var f = fso.GetFile(oFilesInSubmitDir.item().Path);

f.Delete();


}

catch (e)

{

WScript.echo("ERROR: " + e.description);

}

}

}

oApp.Quit();




The InfoPath 2003 SP1 Preview



Do you know about the InfoPath 2003 SP1 Preview release? There are actually two free downloads available:




  1. The InfoPath 2003 SP1 client: new features and improvements added to the InfoPath client.

  2. The InfoPath 2003 Visual Studio toolkit: this provides the ability to write .NET managed code business logic in your InfoPath form.


Anyone can download and install this version of InfoPath and use it until it expires.


When the Office System 2003 SP1 is released (mid-2004), InfoPath will be updated to have many new features, in addition to performance improvements and bug fixes (and if you just want the performance improvements and bug fixes, the new features can be turned off).  The SP1 is completely backwards compatible with InfoPath 2003.


This preview gives you a chance to try out an initial version of the SP1 bits now so that you can learn the new features and plan for the SP1 deployment within your company.


The SP1 release is very important in that we were able to address customer wishes.  Give it a try!  We're certainly excited about it and will be posting about InfoPath SP1 here often (and we'll make it clear when a post is SP1 specific).