Using a Feature Receiver to Remove a Configuration Setting

Typical Goals

If you regularly use the Application Setting Manager to add and update configuration settings for your SharePoint applications, you will also want to remove configuration settings that are no longer required. For example, if you uninstall a Web Part, you should remove any configuration settings that are unique to that Web Part to prevent your property bags from becoming unwieldy and to reduce the risk of duplicating key names for different settings.

Solution

The IConfigManager interface defines a method named RemoveKeyFromPropertyBag that enables you to remove configuration settings. This method takes two arguments: the key as a string and the IPropertyBag instance from which you want to remove the setting. If you used a feature receiver class to add the configuration setting when your feature was activated, good practice suggests that you should you use the same feature receiver class to remove the configuration setting when it is no longer required.

Using the IConfigManager Interface to Remove Configuration Settings

The following code shows how to use the IConfigManager interface to remove a configuration setting from within a feature receiver class.

This example assumes that you have added a reference to the Microsoft.Practices.SharePoint.Common.dll assembly, the Microsoft.Practices.ServiceLocation.dll assembly, and the Microsoft.SharePoint.dll assembly.

using Microsoft.SharePoint;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;
using Microsoft.Practices.SharePoint.Common.Configuration;

[Guid("8b0f085e-72a0-4d9f-ac74-0038dc0f6dd5")]
public class MyFeatureReceiver : SPFeatureReceiver
{ 
    public override void FeatureDeactivating(SPFeatureReceiverProperties 
 properties)
    {
        IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
        IConfigManager configManager = 
 serviceLocator.GetInstance<IConfigManager>();

        SPSite mySite = properties.Feature.Parent as SPSite; 
  if(mySite != null)
  {
             configManager.SetWeb(mySite.RootWeb);
             IPropertyBag bag = configManager.GetPropertyBag(
                                  ConfigLevel.CurrentSPSite);

        configManager.RemoveKeyFromPropertyBag(
            "Contoso.Sales.Applications.CustomerLocationsListUrl", bag);
  }
    }   
}

Note

The Parent property of a feature depends on the scope of the feature that is being activated. In this example, the feature is scoped at the site collection level.

For more information about using the IConfigManager interface to remove configuration settings, see Removing Configuration Settings.