sharepoint web parts

An effective way of maintaining your Web Part Gallery is essential to ensure smooth operations. In this article, we will explore an alternative approach to a previously suggested method by Greg Galipeau for cleaning up the Web Part Gallery.

The Previous Method: Greg Galipeau’s Feature Receiver

In his blog post, Greg Galipeau introduced a Feature Receiver that he used as a generic Feature Receiver for all his WebPart Features. This approach removes the WebPart with the same name as the Feature’s DisplayName when the Feature is deactivated.

However, there are a couple of issues with this method:

  1. It assumes that the WebPart has the same name as the Feature.
  2. It limits the Feature to deploying just a single WebPart.

To overcome these limitations, we can use an alternative approach that inspects the Feature’s element definitions and extracts the exact WebPart names that were deployed.

Alternative Approach: Enhanced Feature Receiver

The alternative Feature Receiver, which extends the BaseFeatureReceiver, resolves the issues listed above.

Here is the modified WebPartFeatureReceiver class:

“`csharp
public class WebPartFeatureReceiver : BaseFeatureReceiver
{
public override void FeatureDeactivating(SPSite site, SPFeatureReceiverProperties properties)
{
base.FeatureDeactivating(site, properties);

    var elements = properties.Definition.GetElementDefinitions(CultureInfo.CurrentCulture);
    var webparts = elements.Cast<SPElementDefinition>()
        .SelectMany(e => e.XmlDefinition.ChildNodes.Cast<XmlElement>()
            .Where(n => n.Name.Equals("File"))
            .Select(n => n.Attributes["Url"].Value)
        )
        .ToList();

    var rootWeb = site.RootWeb;
    var wpGallery = rootWeb.Lists["Web Part Gallery"];

    var galleryItems = wpGallery.Items.Cast<SPListItem>()
        .Where(li => webparts.Contains(li.File.Name))
        .ToList();

    for (int i = galleryItems.Count - 1; i >= 0; i--)
    {
        var item = galleryItems[i];
        item.Delete();
    }
}

}
“`

This alternative WebPartFeatureReceiver inspects the Feature’s element definitions and extracts the exact WebPart names that were deployed, thereby resolving the two issues mentioned earlier.

Conclusion

By employing this alternative approach, you can efficiently clean up your Web Part Gallery and avoid the limitations imposed by the previous method. This will ensure that your WebPart management is more accurate and flexible, leading to smoother operations within your SharePoint environment.