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
//http://blog.mattsmith.co.nz/Lists/Posts/Post.aspx?List=c7bdac80-1d4e-4732-9e67-cefde9c03d31&ID=51
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?

 

 

Author

Admin

comments powered by Disqus

Categories

Recent Tweets

19 Types of Developers Explained dev.to/lpasqualis/19-…
Can't Afford Photoshop? Here Is The Best Free Drawing Software | Digital Trends digitaltrends.com/computing/best…
Retweeted by @dyardy Fun day christening Amazon’s latest wind farm. #RenewableEnergy https://t.co/cTxeXdsFop
Retweeted by @dyardy Hey C# peeps, we’re trying C# in browser with reference content. Try it here: docs.microsoft.com/dotnet/csharp/… reply with feedback /cc @LadyNaggaga
23 Amazing Vintage Photographs Taken Inside WWII Tank Factories ~ vintage everyday vintag.es/2017/10/23-ama…