CKS:FBA - Fix for GenericWebPartReceiver

Topics: General/Misc.
Apr 22, 2009 at 7:42 PM

The FeatureDeactivating method in the GenericWebPartReceiver code is bad, bad, bad.  The Site and Web should not be disposed, and the repeated calls to SPList.Items instead of a cached SPListItemCollection object make the code highly inefficient.

It should be replaced with something like the following:

  public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
  {
   try
   {
    SPSite site = (SPSite)properties.Feature.Parent;
    SPListItemCollection webParts = site.RootWeb.Lists["Web Part Gallery"].Items;
    // go through the items in reverse
    for (int i = webParts.Count - 1; i >= 0; i--)
    {
     string webpartName = webParts[i].Name;
     webpartName = webpartName.Substring(0, webpartName.IndexOf('.')) + "WebPart";
     // delete web parts that have been added
     if (properties.Feature.Definition.DisplayName == webpartName)
     {
        webParts[i].Delete();
        break;
     }
    }
   }
   catch (Exception ex)
   {
    Utils.LogError(ex);
   }
  }