in SharePoint 2007

Feature Receivers and SPContext.Current and SPFeatureReceiverProperties

Another day, another discovery! – MOSS Rocks! 🙂

I had to create a List using a Feature. So, I added my code in the FeatureActivated method. The first thing I did was to get the current web (site)

public override void
FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb CurWeb = SPContext.Current.Web;
// Rest of the code follows....
}

 

I went ahead and installed the feature using stsadm command. It worked fine. I then activated the feature and ended up getting this error!

Object reference not set to an instance of the object

If I remove the code inside the FeatureActivated method, it works! And, If I activate the feature from the web browser, it works!

Googling, I found that you cannot use SPContext.Current inside FeatureActivated when using stsadm (via command prompt) to activate the feature

Why? – Very simple, cmd.exe process does not understand or know how to get your current context! If you are running via browser, you have the w3wp.exe process from which you can get the context!

 

So, is there a way I could get the Web or Site to which the feature is getting deployed? Of course, YES!

Below is an extension method for you! (from here – Matt Smith’s blog, who is now enjoying his vacation!):

public static class Extensions
{
/// <summary>
/// Gets the web.
/// </summary>
/// <param name="properties">The properties.</param>
/// <returns></returns>
public static SPWeb
GetWeb(this SPFeatureReceiverProperties properties)
{
SPWeb site;
if (properties.Feature.Parent is SPWeb)
{
site = (SPWeb)properties.Feature.Parent;
}
else if (properties.Feature.Parent is SPSite)
{
site = ((SPSite)properties.Feature.Parent).RootWeb;
}
else
{
throw new Exception("Unable to retrieve SPWeb -
this feature is not Site or Web-scoped.");
}
return site;
}
}

Depending on the scope of your feature, you cast the Parent.

And you use it like this:

public override void
FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb CurWeb = properties.GetWeb();
Guid listId = CurWeb
.Lists
.Add(ListTitle, ListDescription, SPListTemplateType.GenericList);
CurWeb.Update();
}

Write a Comment

Comment

Time limit is exhausted. Please reload the CAPTCHA.