I have a troublesome webpart which I would like to remove from all the places it is being used. (A large number of personalized site pages).
How can I do this in SharePoint 2007?
First of all, I recommend that you fix the web part! Modifying lots of pages programmatically can take a long time and needs to be tested.
Here's some code to begin with. Apologies for nestings etc...
using(var site = new SPSite("http://moss.domain.com/sites/sales"))
using(var web = site.OpenWeb())
{
var user = web.SiteUsers[@"domain\dave"]; //User with a personalised page
//Open site with user token
using(var userSite = new SPSite("http://moss.domain.com/sites/sales", user.UserToken))
using(var userWeb = userSite.OpenWeb())
{
var page = userweb.GetFile("http://moss.domain.com/sites/sales/default.aspx");
using(var webpartManager = page.GetLimitedWebPartManager(PersonalizationScope.User))
{
var webpartsToDelete = new List<WebPart>();
foreach(var webpart in webpartManager.WebParts)
{
if(webpart is My.Dodgy.WebPart) //Replace with your web part type
{
webpartsToDelete.Add(webpart);
}
}
foreach(var webpart in webpartsToDelete)
{
webpartManager.Delete(webpart);
}
}
}
}
You'll have to iterate over each web application, site, web, user and page... not a trivial amount of time.
To reduce this effort, you could make a "Self Service Fix" page for users to paste in the URLs of broken pages. (I would imagine that the majority of pages on your server won't be personalized or have the web part on it).
And test it first!!