Thursday, 15 November 2012

How to create InfoPath Forms Programmatically:

How to create InfoPath Forms Programmatically:
Following code will explain the way to create to create InfoPath forms programmatically.
Basic logic behind InfoPath form creation is just creating XML file to the form library. If we can add xml file to the form library then it will open in the form of InfoPath.

Syntax to create XML (InfoPath form):
StringBuilder SubFileTemplate = new StringBuilder();

SubFileTemplate.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?><?mso-infoPathSolution name=\"urn:schemas-microsoft-com:office:infopath:TemplateName:-myXSD-2012-06-26T06-06-08\" solutionVersion=\"1.0.0.871\" productVersion=\"14.0.0.0\" PIVersion=\"1.0.0.0\" href=\"" + SPContext.Current.Site.Url + "/LibraryName/Forms/template.xsn\"?><?mso-application progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.3\"?><?mso-infoPath-file-attachment-present?><my:myFields xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-06-26T06:06:08\" xmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\" xml:lang=\"en-US\">");
SubFileTemplate.Append("<my:AccountNumber>" + valueforAcntNumber + "</my:AccountNumber>");
SubFileTemplate.Append("<my:Description>" + valueforDescription + "</my:Description>");
SubFileTemplate.Append("</my:myFields>");

string XmlPath = web.Url + "/FormLibraryName/" + “TestForm.xml”;
MemoryStream stream = new MemoryStream();
System.Text.UTF8Encoding myEncoding = new System.Text.UTF8Encoding();
byte[] myBuffer = myEncoding.GetBytes(SubFileTemplate.ToString());
stream.Write(myBuffer, 0, myBuffer.Length);
if (myBuffer != null && myBuffer.Length != 0)
 {
 web.Files.Add(XmlPath, myBuffer);//Adding XML file to library
}


Here create one stringbuilder object and add xml tags to the variable and then save content to the library in the format of xml file.
You can get correct XML format tags by using following way:
Publish your InfoPath form into the SharePoint site and create one dummy InfoPath form manually. Then you can download the same form and then open with Notepad. Then you will be able to see the correct xml tags for your form.
Screen shot for the same.

Once you create xml file to library programmatically then you will be able to open in InfoPath.

No comments:

Post a Comment