Pages

Monday, May 21, 2012

SharePoint 2010 Web Part Feature Clean Up

Reading through "Inside Microsoft SharePoint 2010" I came across a section on page 192 titled, "Deleting Web Part Template Files at Feature Deactivation". I thought the suggestion to remove the .webpart template file from the Web Part gallery was worth writing about. In case you never tried this use case, attaching a SharePoint Web Part to a feature in SharePoint only supports adding a .webpart template file to the Web Part gallery upon feature activation. Deactivating the feature doesn't remove the .webpart template file which is why I recommend adding a feature event handler that removes this file from the gallery when deactivating your Web Part feature.  Here is the sample code segment taken from the book referenced above to remove the template file:


public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {

      SPSite siteCollection = (SPSite)properties.Feature.Parent;
      SPWeb site = siteCollection.RootWeb;

      List<SPFile> FilesToDelete = new List<SPFile>();
      // figure out which Web Part template files need to be deleted
      SPList WebPartGallery = site.Lists["Web Part Gallery"];
      foreach (SPListItem WebPartTemplateFile in WebPartGallery.Items) {
        if (WebPartTemplateFile.File.Name.Contains("put your .webpart file title here")) {
          FilesToDelete.Add(WebPartTemplateFile.File);
        }
      }

      // delete Web Part template files
      foreach (SPFile file in FilesToDelete) {
        file.Delete();
      }

    }
As a developer in training I welcome any constructive feedback. Please feel free to comment below. Thanks.

3 comments :

  1. I would remove the brackets from "({put your .webpart file title here})" and I would make sure the spfile in "List FilesToDelete = new List();" is changed to "SPFile". When I copied and pasted those were the changes I had to make. Other than that it worked awesome. Thanks for the code.

    ReplyDelete
  2. An interesting discussion is worth comment. I thinks you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

    ReplyDelete
  3. I am very pleased to find this blog. I want to thank for your time for this wonderful read!!! Keep Sharing, I'll surely be looking for more.

    ReplyDelete

I always welcome constructive feedback. Thanks.