Feature.EventReceiver Get Web Context

In order to get the current SPWeb context that the feature was activated on I have used the following extension method.  Regardless if the feature is web or site scoped the following GetWeb extension will return the current web context.

Typically you would do something like the following.  This works fine if the feature is scoped for web.  If however it is scoped for Site then it will no longer work (.Parent becomes SPSite)

SPWeb site = (SPWeb)properties.Feature.Parent; 

Using the following extension you can now use something like the following.

SPWeb web = properties.GetWeb();  //much cleaner


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

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;

Cool eh?





comments powered by Disqus


Recent Tweets

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d… twitter.com/i/web/status/9…
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything huffingtonpost.com/entry/trump-te…
Retweeted by @dyardy Boston https://t.co/QmtMIF8P0F