Tuesday, January 6, 2009

Programatically removing webpart from all site collections

Scenario:
One of my colleague called me this morning and had a problem. Basically he has many 100 site collections all based on a sample template ( assume Team Site ) and he wanted to remove a particular web-part ( assume Announcemnts ) from the RootWeb default page.

Solution:
I love to write such fixes, so here's the code.

Code:

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebPartPages;

namespace DeleteWebPartsFromAllSite
{
class Program
{
static void Main(string[] args)
{
SPWebApplication webApplication = null;

using (SPSite site = new SPSite("http://localhost"))
{
webApplication = site.WebApplication;
}

foreach (SPSite site in webApplication.Sites)
{
using (SPWeb web = site.RootWeb)
{
site.AllowUnsafeUpdates = true;

SPLimitedWebPartManager WPMgr = web.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

foreach (WebPart wp in WPMgr.WebParts)
{
if (wp != null && wp.Title == "Announcements")
{
WPMgr.DeleteWebPart(wp);
break;
}
}
}
site.AllowUnsafeUpdates = false;
site.Dispose();
}
}
}
}
Notes:
Above code will only remove the webpart from the Shared view , so it might exist in user's personal view.

Follow-up:
If you dont have the rights, then you might get access denied errors. You can try RunWithElevatedPrivileges with elevated privileges.

You might be getting ErrorWebPart type while iterating the WebPartManager.WebPart loop. Here's the fix

1 comments:

Steven,  January 7, 2009 at 8:04 AM  

What a coincidence! you made my day :)

thx alot for sharing