Tag Archive for 'generics'

(SPWeb)properties.Feature.Parent no more … a handy Feature Receiver Base Class

If you are writing SharePoint feature receivers often, you will find there are several lines of code common to just about every feature receiver:

  1. A cast of properties.Feature.Parent to the appropriate scope (either SPWeb, SPSite, SPWebApplication, or SPFarm)
  2. Empty implementations of FeatureInstalled and FeatureUninstalling

Provided below is an abstract generic class that now serves as the base class for every feature receiver I write. It eliminates the redundant code by performing the cast for you based on the classes generic type parameter and also goes ahead and implements all the abstract methods, making it so that you to only need to override the actual methods you plan to handle. Your extending feature receiver now will look like the following:

    public class MyFeatureReceiver : BaseFeatureReceiver<SPWeb>
    {
        public override void FeatureDeactivating(SPWeb scope, SPFeatureReceiverProperties properties)
        {
            // Pointless, but what the heck
            base.FeatureDeactivating(scope, properties);
 
            // Now do something with your scope object, in this case an SPWeb
            ...
        }
    }

And now, the code for the BaseFeatureReceiver:

    /// <summary>
    /// Base class that makes the feature scope available as an argument to the
    /// FeatureActivated and FeatureDeactivating methods
    /// </summary>
    /// <typeparam name="T">
    /// T is the class type of the scope of the feature (SPFarm, SPWebApplication, SPSite, or SPWeb)
    /// </typeparam>
    public abstract class BaseFeatureReceiver<T> : SPFeatureReceiver
    {
        public sealed override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            FeatureActivated((T)properties.Feature.Parent, properties);
        }
 
        public virtual void FeatureActivated(T scope, SPFeatureReceiverProperties properties) { }
 
        public sealed override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            FeatureDeactivating((T)properties.Feature.Parent, properties);
        }
 
        public virtual void FeatureDeactivating(T scope, SPFeatureReceiverProperties properties) { }
 
        public override void FeatureInstalled(SPFeatureReceiverProperties properties) { }
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties) { }
    }

Hope you find this helpful.