Tuesday, July 21, 2009

SPFeatureReceiver Guidance

CAUTION! This is starting to become a PET PEEVE of mine!

Features can be managed from stsadm.exe, Site collection features web ui, Site features web ui, console apps, powershell scripts, feature staplers and the list goes on and on.
To make sure your feature receivers work no matter where the feature is being activated from do yourself a favour and keep on reading.


SPFeatureReceiverProperties.Feature.Parent can be many things depending on the scope of your feature and where it's being activated from so please make sure you check before using it. So many times have I found great features in CodePlex that I would like to staple to site definitions or deploy/activate using powershell or other mediums and find I get this.

Value does not fall within the expected range. at ###.###.FeatureReceiver.FeatureActivated(SPFeatureReceiverProperties properties)

For Site Scoped Features

public override void FeatureActivated(SPFeatureReceiverProperties properties) {
SPSite site = properties.Feature.Parent as SPSite;
if (site == null)
{
SPWeb web = properties.Feature.Parent as SPWeb;
if (web != null)
site = web.Site;
}
if(site == null)
return new ArgumentNullException("Can't find a refrence to a site!");
//Or check for parent being a Web app or log it

// Do Stuff
}

For Web Scoped Features
public override void FeatureActivated(SPFeatureReceiverProperties properties) {
SPWeb web = properties.Feature.Parent as SPWeb;
if (web == null)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
web = site.OpenWeb();
}
if(web == null)
return new ArgumentNullException("Can't find a reference to a web!");
//Or check for parent being a Web app or log it

// Do Stuff
}


You get the idea! (I'll format the code as soon as I'm back on my normal PC)