Tuesday, November 20, 2007

Support multiple scopes in SPEventReceiver class

Quite often when I create a feature SPEventReceiver I am not certain what would be the best scope to use it. In other situations I am copying existing code from a feature scoped differently than the newly created one. After couple of these you get tired of trying to find out what is the actual meaning of the properties parameter, as it changes with the scope change.

So here is a little snippet that I started using to save some time and effort. In this particular case I am fetching the current web application from the feature properties:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWebApplication app = null;

if (properties.Feature.Parent is SPSite)

{

SPSite siteCollection = properties.Feature.Parent as SPSite;

app = siteCollection.WebApplication;

}

else if (properties.Feature.Parent is SPWeb)

{

SPWeb web = properties.Feature.Parent as SPWeb;

app = web.Site.WebApplication;

}

else if (properties.Feature.Parent is SPWebApplication)

{

app = properties.Feature.Parent as SPWebApplication;

}

else if (properties.Feature.Parent is SPFarm)

{

throw new Exception("Not supported as farm feature.");

}

}

This code can be used in some of my previous posts:

SharePoint Resources, Types, Use and Deployment (Update)

SharePoint Resources, Types, Use and Deployment

Dovizhdane!