Saturday, May 22, 2010

Updating Date and Integer type fileds in InfoPath programmatically

From the title of the topic seems that this task should be easy! But to my own surprise I find it very difficult and time consuming activity.

The Task:
We are having a InfoPath form Template, that is already published in a SharePoint Form Library. Now, We have to create the InfoPath form dynamically and submit the form in the SharePoint library. This process was described earlier in this post.



Now, the problem is the InfoPath form contains certain Date and Integer data types. And I have a C# application to do the task.

First Problem:
If I have to do this task inside InfoPath managed codes using VSTA (Visual Studio Tools for Application), the following piece of can be used:

XPathNavigator root = MainDataSource.CreateNavigator();
XPathNavigator nameNode = root.SelectSingleNode("/my:myFields/my:Name", NameSpaceManager);
nameNode.SetValue("newvalue");

But, I am not using VSTA and have to navigate the XML node programmatically. The "NameSpaceManager" only available inside InfoPath managed codes only. Therefore the "NameSpaceManager should create first in the code:

public XmlNamespaceManager InitNamespaceManager(XmlDocument xmlDOMDoc)
{

XmlNamespaceManager xnmMan;
xnmMan = new XmlNamespaceManager(xmlDOMDoc.NameTable);

foreach (XmlAttribute nsAttr in xmlDOMDoc.DocumentElement.Attributes)
{
     if (nsAttr.Prefix=="xmlns")
         xnmMan.AddNamespace(nsAttr.LocalName,nsAttr.Value);
}
return xnmMan;
}

XmlNamespaceManager NamespaceManager = InitNamespaceManager(XMLDoc);


This NameSpaceManager is required to resolve any NameSpace related issues at the time of creating XPathNavigation.


Second Problem:

This problem raised when I updated the Date and Integer fields of the InfoPath file in my code. After submission of the file, when I try to open, the following error message displayed:


After googled some time, I learnt that, XML only understand a single date format. That is "yyyy-MM-dd". You have to pass the dates in this format only. So, I used:

newNode.SetValue(XmlConvert.ToString(DateTime.Now, "yyyy-MM-dd"));

Third Problem:

After putting that dates in the correct format, I was a bit confident that the problem has been resolved. But the previous error message was again shown me, i.e. "Schema validation error".

Fortunately, I got this and this on the Internet, and fixed the entire problem finally.

XmlNamespaceManager NameSpaceManager = InitNamespaceManager(XMLDoc);

XPathNavigator nav = xd.CreateNavigator();

//For a text field value
nav.SelectSingleNode("/my:myFields/my:Requestor", NameSpaceManager).SetValue("SampleData");

//For a date Field
XPathNavigator navTRDDate = nav.SelectSingleNode("/my:myFields/my:TRDDate", NameSpaceManager);

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

navTRDDate.SetValue(DateTime.Now.ToString("yyyy-MM-dd"));

No comments: