Wednesday, 20 June 2012

Feature activation depending on some logic

Some time we need to get our feature de-activated mode if it fails on some logic. For instance you have written a feature that provisions some lookup list that depends on an existent list or some timer job. The name of the existent list or timer job is supplied through properties.

The easiest way to tell SharePoint not to activate this feature is to throw SPException with your message.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
   string someListName = properties.Definition.Properties["ParentListName"].Value;
   if (string.IsNullOrEmpty(someListName))
     throw new SPException("Please supply value of 'ParentListName' property.");          
   SPSite site = (SPSite)properties.Feature.Parent;
   SPList someList = site.RootWeb.Lists[someListName];

   if (someList == null)
     throw new SPException(string.Format("List:'{0}' does not exist. Please create it first before activating this feature.", someListName));

   //do your stuff

That's it.