Thursday, February 14, 2008

Serialize Export Webparts

I needed to add webparts to a provisioned site. When the feature for the site creation began, webparts (all custom) had to be added and configured.

Easy enough, but how do you get the custom web parts out?

I found this on a http://sharepointex.blogspot.com/2007/09/managing-web-parts-programmatically.html

Was not exactly what I needed. So I used the gettype(), not that thier are two kinds of webparts, one from sharepoint and the other from asp.net


Note that this does not run, it will throw exceptions when trying to cast the web parts in the foreach, but I ran it in debug and dragged the execution point and changed the type string to get the files.

It was never meant to run more than once.


private void SerialzeWebparts(SPWeb curWeb)
{
SPLimitedWebPartManager sPLimitedWebPartManager = curWeb.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared);

//might not be this kind of webpart
foreach (Microsoft.SharePoint.WebPartPages.WebPart wp in sPLimitedWebPartManager.WebParts)
{
if (((object)wp).GetType().ToString() == "Microsoft.SharePoint.Portal.WebControls.BlogView")
{
WebPartExportMode tempMode = wp.ExportMode;
wp.ExportMode = WebPartExportMode.All;

string fileName = String.Format(@"C:\Temp\{0}_{1}.txt", wp.ID, wp.Title);
System.Xml.XmlTextWriter wrt = new System.Xml.XmlTextWriter(fileName, Encoding.UTF8);

sPLimitedWebPartManager.ExportWebPart(wp, wrt);
wrt.Close();

wp.ExportMode = tempMode;
}
}

//might not be this kind of webpart
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in sPLimitedWebPartManager.WebParts)
{
if (((object)wp).GetType().ToString() == "Microsoft.SharePoint.WebPartPages.ContentEditorWebPart")
{
WebPartExportMode tempMode = wp.ExportMode;
wp.ExportMode = WebPartExportMode.All;

string fileName = String.Format(@"C:\Temp\{0}_{1}.txt", wp.ID, wp.Title);
System.Xml.XmlTextWriter wrt = new System.Xml.XmlTextWriter(fileName, Encoding.UTF8);

sPLimitedWebPartManager.ExportWebPart(wp, wrt);
wrt.Close();

wp.ExportMode = tempMode;
}
}

}

No comments: