My blog has moved!

Visit http://blog.adamroderick.com/ and update your bookmarks.

Monday, February 1, 2010

Utility to Get Feature Scope in SPFeatureReceiver

During development, I might change my feature’s scope in the feature.xml definition.  To make sure this never bites me, I always check in my SPFeatureReceiver methods to make sure I am casting the feature’s parent to the right object.  If not, I throw an SPException so the error gets displayed to the browser window.  I find myself repeating this for every feature I write, so here is a snippet I use to keep it DRY.

    internal static class FeatureReceiverUtil
{
/// <summary>
/// Returns an object representing the scope of the feature, and throws an SPException
/// if the scope is unexpected
/// </summary>
/// <typeparam name="T">should be SPWeb, SPSite, SPWebApplication, or SPFarm</typeparam>
/// <param name="properties">the properties from the feature receiver event</param>
/// <returns></returns>
internal static T GetScope<T>(SPFeatureReceiverProperties properties) where T : class
{
var scope
= properties.Feature.Parent as T;
if (null == scope) throw new SPException(
string.Format(
"Feature {0} ({1}) expected to be at the {2} scope but was not",
properties.Definition.DisplayName,
properties.Definition.Id,
typeof(T).Name
));
return scope;
}
}

Usage is:



SPWeb web = FeatureReceiverUtil.GetScope<SPWeb>(properties);

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home