Monday, March 22, 2010

Adding Rich Text from SharePoint to an Infopath Form

Problem Scenario:
You are trying to add the value from a Rich Text field from SharePoint to an Infopath form. This is a common scenario when trying to create custom Workflows in Visual Studio with Infopath Form support.

Symptoms:
Your Rich Text does not appear in the infopath form. Any text which is not marked up does not appear. Text outside of tags does appear.

Solution:
After some digging I figured that InfoPath requires the xhtml Namespace to be present for any data within a Rich Text field. After a lot of digging into XmlParsers, XMLNameSpaceManagers, XmlNameTables and the likes I found a very simple solution.
When passing the value over to the ExentedProperty in your Workflow, wrap the string with a div tag that has the xmlns='http://www.w3.org/1999/xhtml' attribute on it.

string htmlText = "<div xmlns='http://www.w3.org/1999/xhtml'>"
+ workflowProperties.Item.Title
+ "<br/>"
+ workflowProperties.Item["Body"]
+ "</div>";

TaskProperties.ExtendedProperties["Instructions"] = htmlText ;

Just one thing missing now. Infopath translates your valid xhtml and shows the actual tags. To solve this problem you will need to add some parsing to the load method of the form. Yes, that means that you will need to deploy some code with the form. But it's no biggie. Promise.
A fellow blogger has a great post on how to stop Infopath escaping the html
http://www.chrisbuchanan.ca/Blog/Lists/Posts/Post.aspx?ID=1


UPDATE!
So I thought I nailed it! Well, as long as you do not attempt to open that infopath form using infopath! As that will throw a security exception due to the underlying code. But hey! It's on the server you might say. Being hosted by Infopath Forms Server. Nobody would wanna open it in infopath anyway. Ha. Outlook 2007 does! So when your Outlook 2007 users hit the Edit this Task button, instead of getting a nice RichtText experience, they get a security error complaining about a missing digital signature.

Sorry folks. Back to the basics on this one. I'll just strip out all HTML before passing it to Infopath using Regular expressions. A nice one to achieve this is
string stripped = Regex.Replace(textBox1.Text,@"<(.|\n)*?>",string.Empty);

(found via weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx

2 comments:

moss said...

Tx! You saved me a lot of future headaches!.

I guess sometimes brute force is fine :)

Chris Buchanan said...

Hey thanks for linking to my blog, do you mind updating the link:

http://www.chrisbuchanan.ca/Blog/Lists/Posts/Post.aspx?ID=1