Removing duplicated web parts after page layouts feature reactivation
using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.SharePoint;using Microsoft.SharePoint.WebPartPages;using System.Web.UI.WebControls.WebParts;using System.Xml;using System.Security.Cryptography;using System.IO;namespace RemoveDuplicatedLayoutsWebParts{ class Program { static void Main(string[] args) { using (SPSite site = new SPSite(args[0])) { SPList list = site.GetCatalog(SPListTemplateType.MasterPageCatalog); SPListItemCollection items = list.Items; // find the right Page Layout foreach (SPListItem item in items) { List<string> webParts = new List<string>(); if (item.File.ServerRelativeUrl.Contains("Cargotec.CMS.PageLayouts") && !item.File.ServerRelativeUrl.EndsWith("txt")) { try { Console.WriteLine("Proceed: " + item.File.ServerRelativeUrl); var previousWps = new List<String>(); SPFile file = item.File; if (file.CheckOutType == SPFile.SPCheckOutType.None) file.CheckOut(); // get the Web Part Manager for the Page Layout SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared); foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpm.WebParts.Cast<System.Web.UI.WebControls.WebParts.WebPart>().ToList()) { Console.WriteLine("Checking web part: " + wp.Title); wp.ExportMode = WebPartExportMode.All; var xml = GetXml(wp, wpm); //Console.WriteLine("-------------------------------------------"); //Console.WriteLine(xml); //Console.WriteLine("-------------------------------------------"); if (previousWps.Contains(xml)) { Console.WriteLine("Deleting web part: " + wp.Title); wpm.DeleteWebPart(wp); } else previousWps.Add(xml); } file.CheckIn("removed duplicates"); file.Publish("removed duplicates"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } Console.WriteLine("Finished"); Console.ReadKey(); } static bool Contains(List<System.Web.UI.WebControls.WebParts.WebPart> wps, System.Web.UI.WebControls.WebParts.WebPart wp, SPLimitedWebPartManager wpm) { foreach (var wpOld in wps) { if (GetXml(wp, wpm) == GetXml(wpOld, wpm)) return true; } return false; } static string dllLink = " <Assembly>Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>" + System.Environment.NewLine; static string dllLink2 = "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" + System.Environment.NewLine; static public string GetXml(System.Web.UI.WebControls.WebParts.WebPart wp, SPLimitedWebPartManager wpm) { using (var sw = new StringWriter()) { using (var xw = new XmlTextWriter(sw)) { // Build Xml with xw. wpm.ExportWebPart(wp, xw); xw.Flush(); } return sw.ToString().Replace(dllLink, "").Replace(dllLink2, ""); } } }}