Skip to content

Instantly share code, notes, and snippets.

@reallyseth
Created May 21, 2010 20:56
Show Gist options
  • Save reallyseth/409421 to your computer and use it in GitHub Desktop.
Save reallyseth/409421 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Xml.XPath;
using System.Web.UI.WebControls.WebParts;
namespace MySharePoint.Features
{
public class AddWebPartsToPage : SPFeatureReceiver
{
private const string LogSource = "AddWebPartsToPage SharePoint Feature";
private const string Log = "Application";
/// <summary>
/// Constructor
/// </summary>
public AddWebPartsToPage() { }
/// <summary>
/// Applies web parts to publishing page layouts based on configuration and webpart definition files.
/// </summary>
/// <param name="properties">SPFeatureReceiverProperties</param>
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
// open the current web
SPWeb web = (SPWeb)properties.Feature.Parent;
// get the path to the config xml file
string configFilePath = properties.Definition.RootDirectory + "\\configuration.xml";
// pull data from the config xml file
foreach (XPathNavigator pageLayoutConfiguration in LoadConfigurationFile(configFilePath).CreateNavigator()
.Select("Configuration/Page"))
{
string pageLayoutFileName = pageLayoutConfiguration.GetAttribute("FileName", "");
// Load the SPListItem that represents the page layout.
SPListItem page = web.GetListItem(web.Url + "/" + pageLayoutFileName);
// Check out the page Layout
page.File.CheckOut();
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);
}
catch (Exception ex)
{
// Make sure that the file is not checked out anymore.
page.File.UndoCheckOut();
throw;
}
}
}
catch (Exception ex)
{
// set the event log message
string logMessage = "Feature activation error: " + ex.Message;
// if the source doesn't exist, create it
if(!EventLog.SourceExists(LogSource))
EventLog.CreateEventSource(LogSource, Log);
// write to the event log
EventLog.WriteEntry(LogSource, logMessage, EventLogEntryType.Error);
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
}
public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
}
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
}
private XPathDocument LoadConfigurationFile(string configFilePath)
{
XmlTextReader configReader;
XPathDocument configDoc;
try
{
configReader = new XmlTextReader(new FileStream(configFilePath, FileMode.Open, FileAccess.Read));
configDoc = new XPathDocument(configReader);
}
catch (Exception ex)
{
throw new ApplicationException("Could not load configuration file 'configuration.xml' or invalid XML-Syntax.", ex);
}
return configDoc;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment