Using an Extension Method to remove a Web Part from the Gallery

Posted Tuesday, April 15, 2008 10:00 AM by CoreyRoth

When you deactivate a feature that deployed a web part, it is a good idea to remove that web part from the gallery.  This makes things much more likely to work when you upgrade said web part later.  Like everything in SharePoint, this task is more complicated than it needs to be.  You would think you could just call myWeb.WebParts.Delete("mywebpart.dwp"), but of course that is not the case.  That would be too easy.

To work with the web parts in the gallery, you first have to know where they are.  The Web Part Gallery is just a list, so it can be manipulated just like any other list.  To get the list, we use the GetCatalog method on the SPWeb object.  It takes an enum parameter of SPListTemplateType.WebPartGallery.

SPList webPartGallery = currentSite.GetCatalog(SPListTemplateType.WebPartCatalog);

Now we need to delete the web part from the gallery.   Unfortunately, there is neither an indexer that uses the web part's name, nor a find method.  This means we get to loop through the collection until we find the item we are looking for.  This provides for another great place to use an Extension Method.  I have found these to be highly useful to make up for the shortcomings in the SharePoint API.

public static class ExtensionMethods

{

    public static void Remove(this SPList myList, string key)

    {

        for (int i = 0; i < myList.Items.Count; i++)

        {

            if (string.Compare(myList.Items[i].Name, key, true) == 0)

            {

                myList.Items[i].Delete();

                return;

            }

        }

    }

}

The code is simple.  Just loop through the collection and compare the name property to a key parameter on the method.  The key parameter will contain the name of the web part's filename (i.e.: mywebpart.dwp).  To use the extension method, it would be called as in the sample below.

using (SPWeb currentSite = SPContext.Current.Web)

{

    SPList webPartGallery = currentSite.GetCatalog(SPListTemplateType.WebPartCatalog);

    webPartGallery.Remove("mywebpart.dwp");

}

This seems like a lot of code to be able to do something that should only take one line of code, but that is what is required.  My collection of SharePoint Extension Methods is getting huge. 

Filed under: ,

Comments

# re: Using an Extension Method to remove a Web Part from the Gallery

Wednesday, April 16, 2008 8:37 AM by KyleKelin

Very very useful. If you remove it from the gallery does it remove it from all the pages you have added it to?

# re: Using an Extension Method to remove a Web Part from the Gallery

Wednesday, April 23, 2008 9:26 AM by CoreyRoth

I do not believe so.  You should know by now that nothing in SharePoint is automatic. :)

Leave a Comment

(required) 
(required) 
(optional)
(required)