Thursday, January 8, 2009

Programatically removing webpart from site collection

I have been working with my friend / colleague regarding the subject. He gave me the direction on how to get this done. Here is the initial blog he submitted.

Now, as some times it becomes a dying situation that you want to execute the same using Command Line tool, following are the points that you need to take into consideration.

1. Verify if the page has only SharePoint WebParts or any custom webparts that you have designed.
2. If you have only SharePoint WebParts then ignore point# 4
3. Check and Create HTTPContext as shown below (this may be required since you will be running outof sharepoint context)

if (HttpContext.Current == null)
{
isContextNull = true;
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
Console.WriteLine("Context Created.");
}

4. Declare all the Assemblies as SafeControls under the app.config incase you have custom controls or webparts that you designed are placed on the page
5. Use the below code...

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

foreach(WebPart wp in manager.WebParts)
{
if (wp != null && wp.Title == "")
{
manager.DeleteWebPart(wp);
web.Update();
web.AllowUnsafeUpdates = false;
}
}

6. Make SPWeb AllowUnsafeUpdates = true when you create the SPWeb instance.

Thats it.
Have fun.

No comments: