Dynamic Data Source Controls for Your Data Form Web Parts 

Tags: Microsoft .NET, SharePoint

In this very, very, *very* old (but still interesting) ASP.net article on MSDN Magazine, I found the following clever code snippit that uses a temporary file to create a user control dynamically from a string:
 
TemplateColumn bc = new TemplateColumn();
String tmp = Session.SessionID + ".ascx";
StreamWriter sw;
sw = new StreamWriter(Server.MapPath(tmp));
sw.Write(strLayoutCode);
sw.Close();
bc.ItemTemplate = Page.LoadTemplate(tmp);
grid.Columns.Add(bc);
File.Delete(Server.MapPath(tmp));

 
This is indeed pretty neat, but it turns out it's not necessary. You can do the same with the following:
 
Page.TemplateControl.ParseControl(strLayoutCode);
 
I discovered this interesting fact after realizing that SharePoint's DataFormWebPart is doing some intriguingly useful (but obfuscated) stuff with DataSourceControls and the SQL database. Basically, in the SharePoint Designer, whatever controls you put inside the DataSources tag - using the design pane, I would assume - get serialized into a BLOB in the WebParts table of your WSS Content database. At run time, they get loaded from the database on the first call to get the DataSources collection, which typically happens during CreateChildControls.
 
I tried forcing a load by explicitly setting DataSourcesString within code, but it blew up because the parser did not understand the tag prefixes in the code that I inserted. It was then that I realized that SharePoint is leveraging ParseControl(string), and after digging in the database, I was able to see that SPD must be programmatically determining what namespaces to register when it saves the data to SQL by way of the DataSourcesString property.
 
This is useful to me because for a long time I have been thinking that SharePoint, and in a greater sense ASP.net needed a way to allow data source controls to be defined more flexibly and in a centralized location. Sure, you can do it programmatically. But, the control parser gives you a fairly efficient way of doing it using a repeatable and flexible process, and you won't be limited to keeping the controls on the filesystem.
 
If you want to leverage this functionality without giving up the other benefits of the Data Form, check out SPARK project over at CodePlex. It includes Flex Data Form, a version of the DFWP that inherits all the same features as the original, but allows you to set the DataSources string and some other properties from within the Web UI. (It also has some other nifty features as well.)
 
Update: Looks like I am not the only one thinking along these lines. Too bad his comments are closed, because his ideas are good ones and he deserves the Whuffie. :-)
 
More Data Form goodness, especially a decent explaination of the OOTB method for overcoming the list GUID issues that plague migration of the DFWP.
 

Links to this post

Comments

Make a Comment

Name *:
URL:
Email:
Comments:

`