I'm a big fan of using WebServices to take the code and logic away from InfoPath.
Although you can use managed code inside an InfoPath Project, for me it makes sense to use simple button / control rules (that can be defined in the InfoPath designer) and use a WebService to do the hard work.
As an example, we needed recently to be able to check for Sharepoint document libraries and optionally create them from within InfoPath.
We created a WebService to do this. The service could run on the Sharepoint server, and hene use the Sharepoint Object Model. This gave us a relatively simple service...
(note the following code has been simplified for the blog purpose)
[code:c#]
public string CheckWSSFolder(string WebName, string ParentFolder, string FolderName, bool CreateFolder)
{
string returnMessage = string.Empty;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://serverurl"))
{
site.AllowUnsafeUpdates = true;
using (SPWeb targetWeb = site.AllWebs[WebName])
{
targetWeb.AllowUnsafeUpdates = true;
if (! CreateFolder)
{
try
{
SPFolder rootFolder = targetWeb.GetFolder(ParentFolder);
SPFolder targetFolder = rootFolder.SubFolders[FolderName];
returnMessage = "Folder Exists";
}
catch (System.Exception err)
{
returnMessage = "Folder Not Found " + err.ToString();
}
}
else
{
try
{
SPFolder rootFolder = targetWeb.GetFolder(ParentFolder);
rootFolder.SubFolders.Add(FolderName);
returnMessage = "Folder Created";
}
catch (System.Exception err)
{
returnMessage = "Folder Not Created: " + err.ToString();
}
}
targetWeb.AllowUnsafeUpdates = false;
}
site.AllowUnsafeUpdates = false;
}
}
);
return returnMessage;
}
[/code]
Using this example, we could then create InfoPath data connections to consume this service. The connection type can be a simple 'read' service and the button / control rules can set the service input parameters...
Button Rules (xpath removed for simplicity)
Rule1
Set a Fields Value, Field = WebName, value = "the SPWeb Name"
Set a Fields Value, Field = FolderURL, value = "Folder URL or SubFolder URL (e.g. folder/subfoler)
Set a Fields Value, Field = CreateFolder, value = false
Rule2
Query using a Data Connection, connection = "Web service connection"
Rule3
Set a Fields Value, Field = my:Fields/my:FeedbackNode, value = message returned from webservice
Within the example above, two things to note:
a) We are using RunWithElevatedPrivileges to let the service run with full privilages
b) The AllowSafeUpdates = true had to be set to allow folder creation, then revoked at the end of the service.
Of course, the service can be used now by any InfoPath or other project.