Friday, April 10, 2009

Using browser enable Infopath form as a class [C#]

I was facing a problem when I had needed a dot net utility to get data from browser enable InfoPath form and save this to another custom list. These steps and code will help to use an browser enable InfoPath form as a Dot Net class.
For using browser enable InfoPath as a class first you need to follow these steps,
 Create a browser enable InfoPath Form.
 Save it’s source file by selecting ‘Save As Source Files…’.




After click ‘Save As Source Files…’, you need to provide path to save this form schema on your location. You can check that ‘MySchema.xsd’ will also one of all files saved on your provided path.
Now Go to Start Menu -> All Programs ->Microsoft Visual Studio 2005 -> Visual Studio Tools ->Visual Studio 2005 Command Prompt



It will display Visual Studio Command prompt. Now navigate to your folder where you have save you InfoPath form schema (MySchema.xsd).

Now you need to run command

Xsd.exe /c /l:CS myschema.xsd

Remember that source infopath form will be closed before executing this command.It will create “myschema.cs” in same folder. This class will look like this…

---------------------------------------------------------------------------------
using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.50727.42.
//


///
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-04-09T04:39:44")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-04-09T04:39:44", IsNullable=false)]
public partial class myFields {

---------------------------------------------------------------------------------

you can use all properties of class ‘myFields’.

Now as per requirement, Suppose there is a document library (Suppose _doclib) where all infopath forms has saved.Let take a item (Suppose ID = 1) of that library.


C# Code:


SPListItem item = _doclib.Items.GetItemById(1);
SPFile InfoPathFile = item.File;
if (InfoPathFile != null)
{
Stream inStream = InfoPathFile.OpenBinaryStream(SPOpenBinaryOptions.None);
XmlTextReader reader = new XmlTextReader(inStream);
myFields objForm = (myFields)DeserializeFile(InfoPathFile, typeof(myFields));
}
protected static object DeserializeFile(SPFile myFile, Type myType)
{
MemoryStream fileStream = new MemoryStream(myFile.OpenBinary());
XmlReader reader = XmlReader.Create(fileStream);
XmlSerializer serializer = new XmlSerializer(myType);
return serializer.Deserialize(reader);
}

Now ‘objForm’ will have all values of that perticular infopath form.just use this objForm and enjoy…