PANVEGA’s Blog

DotNet Development, SharePoint Customizing, Silverlight, MS Infrastructure and other tips and tricks

How to manipulate InfoPath with CodeBehind

Posted by PANVEGA on February 16, 2009

I wonna show you how easy it is to manipulate the InfoPath Formular in C# Codebehind. The compiled DLL becomes part of the InfoPath form template (XSN) file.

1. First you have to install the VSTA tools for Visual Studio.

With the familiar Visual Studio development environment, VSTA enables Visual Basic and Visual C# developers to easily build managed customizations for both COM and .NET applications. The VSTA SDK includes integration tools, samples, and documentation to help you get started with VSTA.

Download Visual Studio Tools for Applications (VSTA)  here

2. Then create in InfoPath a new Formular with some for instance textboxes and Submit buttons. Under Tool–> Programming –>Microsoft Visual StudioTools… you will automatically redirected to the VS CodeBehind InfoPath Project.

3. In addition the Tool deploys a dll in your XSN file when building the project.

4. e.g. create a new Button. In the properties under general choose under ations “Rules and Custom Code” –> Edit Form Code

5. The Tool create you a new Event. How to create an Event Handler?

public void InternalStartup()
{
//EventManager.FormEvents.ContextChanged += new ContextChangedEventHandler(FormEvents_ContextChanged);
((ButtonEvent)EventManager.ControlEvents[“CTRL2_5″]).Clicked += new ClickedEventHandler(CTRL2_5_Clicked);
}

6. here is the method for this event. Create a Navigator and Namespace.

public void CTRL2_5_Clicked(object sender, ClickedEventArgs e)
{
// Create an XPathNavigator to walk the main data source
// of the form.
XPathNavigator xnMyForm = this.CreateNavigator();
XmlNamespaceManager ns = this.NamespaceManager;

// Set the fields in the form.
xnMyForm.SelectSingleNode(“/my:myFields/my:name“, ns)
.SetValue(“alex”);
xnMyForm.SelectSingleNode(“/my:myFields/my:check“, ns)
.SetValue(“true”);

// Clean up.
xnMyForm = null;

}

7. my:name is a textbox field with this given name and a simple checkbox

8. With SetValue() you can chane the current value. Here is the whole just edited formular in XML

<?xml version=”1.0″?><?mso-infoPathSolution solutionVersion=”1.0.0.23″ productVersion=”12.0.0″  PIVersion=”1.0.0.0″
href=”file:///C:\Documents%20and%20Settings\Administrator\Local%20Settings\Application%20Data
\Microsoft\InfoPath\Designer2\4b64fbe91f7d4cf4\manifest.xsf” ?><?mso-application
progid=”InfoPath.Document” versionProgid=”InfoPath.Document.2″?>
<my:myFields xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:my=”http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-02-16T17:31:03&#8243;
xmlns:xd=”http://schemas.microsoft.com/office/infopath/2003&#8243; xml:lang=”en-us”>
<my:name>alex</my:name>
<my:check>true</my:check>

</my:myFields>

this.Application

The Application object includes properties and methods that return references to the high-level objects of the InfoPath object model. For example, the XmlForms property returns a reference to a collection of XmlForm objects.

The Application object is the top-level object in the InfoPath object model, and it provides a number of properties and methods that can be used to access lower-level collections and objects in the object model, and to perform a variety of general purpose functions.

other Examples:

1. In the following example, the event handler for the Submit event is used to prevent the form from being submitted if the form has not been saved.

public void FormEvents_Submit(object sender, SubmitEventArgs e)
{
if(this.Dirty || this.New)
MessageBox.Show(“Please save this form before submitting it.”);
e.CancelableArgs.Cancel = true;
else
e.CancelableArgs.Message = “Submit succeeded.”;
}

2. Retrieve the rows of the repeating table:
XPathNavigator root = MainDataSource.CreateNavigator();
XPathNodeIterator rows = root.Select(
“/my:myFields/my:rows/my:row”, NamespaceManager);

// Loop through the rows of the repeating table
while (rows.MoveNext())
{

// Retrieve the SoftwareTitle

string Title= rows.Current.SelectSingleNode(“my:Title”, NamespaceManager).Value;

}

3. how to retreive and add a new Item to a custom SP List:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat(“<Method ID=\”{0}\” Cmd=\”New\”>”, id.ToString());
sb.AppendFormat(“<Field Name=\”Title\”>{0}</Field>”, title);
sb.AppendFormat(“</Method>”);

XmlDocument methodXML = new XmlDocument();
methodXML.LoadXml(sb.ToString());

XPathNavigator batch = DataSources[“CustomListName“].CreateNavigator();
XPathNavigator batchNav = batch.SelectSingleNode(“/Batch”, NamespaceManager);
batchNav.AppendChild(methodXML.DocumentElement.CreateNavigator());

one more good Example:

There’s quite a bit of C# coding in the form, to retrieve information from active directory and submit repeating rows to the sharepoint list.

using System.DirectoryServices;

public void FormEvents_Loading(object sender, LoadingEventArgs e)
{
try
{
// Get the user name of the current user.
string userName = this.Application.User.UserName;

// Create a DirectorySearcher object using the user name
// as the LDAP search filter. If using a directory other
// than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher(
“(mailNickname=” + userName + “)”);

// Search for the specified user.
SearchResult result = searcher.FindOne();

// Make sure the user was found.
if (result == null)
{
MessageBox.Show(“Error finding user: ” + userName);
}
else
{
// Create a DirectoryEntry object to retrieve the collection
// of attributes (properties) for the user.
DirectoryEntry employee = result.GetDirectoryEntry();

// Assign the specified properties to string variables.
string FullName = (employee.Properties[“displayName”].Value != null) ? employee.Properties[“displayName”].Value.ToString() : “”;
string Mail = (employee.Properties[“mail”].Value != null) ? employee.Properties[“mail”].Value.ToString() : “”;

// Create an XPathNavigator to walk the main data source of the form.
XPathNavigator xnMyForm = this.CreateNavigator();
XmlNamespaceManager ns = this.NamespaceManager;

// Set the fields in the form.
xnMyForm.SelectSingleNode(“/my:myFields/my:RequestorFullName”, ns)
.SetValue(FullName);
xnMyForm.SelectSingleNode(“/my:myFields/my:RequestorEmail”, ns)
.SetValue(Mail);

// Clean up.
xnMyForm = null;
searcher.Dispose();
employee.Close();
}

}
catch (Exception ex)
{
MessageBox.Show(“The following error occurred: ” +
ex.Message.ToString());
throw;
}

}

Note: When the form is deployed as a feature for a workflow. The managed code may not be executed. This issue occurs because a compiled DLL becomes part of the InfoPath form template (XSN) file when you create managed code behind an InfoPath form. Microsoft Office Forms Services does not extract a DLL by expanding the XSN file when the XSN file is installed by using the features functionality.

RESOLUTION

To resolve this issue, copy the compiled DLL to the same folder to which your feature XSN file was deployed.

More Informations:

http://www.infopathdev.com

http://blogs.msdn.com/vsta/

About these ads

2 Responses to “How to manipulate InfoPath with CodeBehind”

  1. Großartig Kollegen – da kann man weiterdenken

  2. I can imagine, that there’s more to say

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: