Last active
December 17, 2015 13:10
-
-
Save vgrem/5615421 to your computer and use it in GitHub Desktop.
CS-Script: Utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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