Skip to content

Instantly share code, notes, and snippets.

@reallyseth
Created May 21, 2010 20:01
Show Gist options
  • Save reallyseth/409343 to your computer and use it in GitHub Desktop.
Save reallyseth/409343 to your computer and use it in GitHub Desktop.
try
{
// Get the limitedWebPartManager of the page layout file.
using (SPLimitedWebPartManager wpManager = page.File.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
// cycle through each web part and get the different attributes
foreach (XPathNavigator webPartConfiguration in pageLayoutConfiguration.Select("WebPart"))
{
string errorMsg = null;
string webPartFilename = webPartConfiguration.GetAttribute("FileName", "");
string webPartType = webPartConfiguration.GetAttribute("Type", "");
string webPartFilepath = properties.Definition.RootDirectory + "\\" + webPartConfiguration.GetAttribute("FileName", "");
string webPartUniqueID = webPartConfiguration.GetAttribute("Id", "").ToLower();
string webPartZoneID = webPartConfiguration.GetAttribute("ZoneId", "");
int webPartZoneIndex = Convert.ToInt32(webPartConfiguration.GetAttribute("Index", ""));
// if the web part comes from a definition, open the .webpart or .dwp definition file
if (webPartType == "Definition")
{
// Import the webpart into memory by loading the webpart definition file
FileStream wpFileStream = new FileStream(webPartFilepath, FileMode.Open,
FileAccess.Read);
XmlTextReader wpXmlReader = new XmlTextReader(wpFileStream);
System.Web.UI.WebControls.WebParts.WebPart webPart = wpManager.ImportWebPart(wpXmlReader, out errorMsg);
if (!string.IsNullOrEmpty(errorMsg))
{
throw new ApplicationException(
string.Format("Error importing webPart '{0}': {1}", webPartFilename,
errorMsg));
}
// set the web part ID
webPart.ID = webPartUniqueID;
// add the web part to the web part manager
wpManager.AddWebPart(webPart, webPartZoneID, webPartZoneIndex);
}
// if the web part is a list view part, add it
else if (webPartType == "ListView")
{
ListViewWebPart webPart = new ListViewWebPart();
string listName = webPartConfiguration.GetAttribute("ListName", "");
SPList list = web.Lists[listName];
webPart.ListName = list.ID.ToString("B").ToUpper();
webPart.ZoneID = webPartZoneID;
wpManager.AddWebPart(webPart, webPartZoneID, webPartZoneIndex);
}
else if (webPartType == "Members")
{
// TODO: add code to create a site members web part and add it to the page
}
}
}
// Update the list item.
page.Update();
// Check in and publish the page layout.
string fileOperationMessage = properties.Definition.GetTitle(System.Threading.Thread.CurrentThread.
CurrentCulture) + ": WebPart configuration.";
page.File.CheckIn(fileOperationMessage);
page.File.Publish(fileOperationMessage);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment