Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
CS-Script: Utilities
//css_host /version:v3.5 /platform:x64;
//css_ref System.Core;
//css_ref System.Xml;
//css_ref System.Xml.Linq;
//css_dir C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI;
//css_reference System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
namespace CSScript4SP
{
public static class WebPartManagerExtensions
{
/// <summary>
/// Generic wrapper for iterating web parts on page
/// </summary>
/// <typeparam name="T">Web part type</typeparam>
/// <param name="web">Web Url</param>
/// <param name="pageUrl">Relative page Url on Web</param>
/// <param name="webPartCode">Code for web part</param>
public static void ForEachWebPartOnPage<T>(this SPWeb web, string pageUrl, Action<SPWeb, T, SPLimitedWebPartManager> webPartCode) where T : Microsoft.SharePoint.WebPartPages.WebPart
{
var page = web.GetFile(pageUrl);
using (var wpm = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
try
{
var allWebParts = wpm.WebParts.OfType<T>();
foreach (var wp in allWebParts)
{
webPartCode(web, wp, wpm);
}
}
finally
{
wpm.Web.Dispose();
}
}
}
/// <summary>
/// Generic wrapper for saving changes in web part on page
/// </summary>
/// <typeparam name="T">Web part type</typeparam>
/// <param name="web">Web Url</param>
/// <param name="pageUrl">Relative page Url on Web</param>
/// <param name="updateMethod">Update method for web part</param>
public static void UpdateWebPartOnPage<T>(this SPWeb web, string pageUrl, Action<SPWeb, T> updateMethod) where T : Microsoft.SharePoint.WebPartPages.WebPart
{
var page = web.GetFile(pageUrl);
using (var wpm = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
try
{
var allWebParts = wpm.WebParts.OfType<T>();
foreach (var wp in allWebParts)
{
updateMethod(web, wp);
wpm.SaveChanges(wp);
}
}
finally
{
wpm.Web.Dispose();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment