0

I want to access SPWeb object in feature under its FeatureActivated method. There are two ways to do this:

Public Override void FeatureActivated(SPFeatureReceiverProperties properties) {

//Method 1 

 SPWeb web = properties.Feature.Parent as SPWeb;

//Method 2

SPSite site = new SPSite("http://merdev-moss:5050");
SPWeb web = site.OpenWeb();

}

Whats the differencce between two methods ? Which one is best under which scenario ?

3 Answers 3

0

You don't need to put SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb in the using statement, because it's obtained from SPContext.Current.Site and will be automatically disposed.

2
  • yup your right, i only quickly copied it from msdn ;), but yes the spcontext handles it for us :P
    – Ali Jafer
    Dec 6, 2012 at 17:00
  • But what you Think, if i put; SPSite site = properties.Feature.Parent as SPSite. Its scope will be SPSite ? I don't need to change the method if i change the scope now. is it right ?
    – SPBeginer
    Dec 7, 2012 at 10:49
1

AFAIK,

properties.Feature.Parent will give you SPWeb in the context the FeatureActivated Event is being called... That means you should not dispose this object, since it is the current context which is activating the feature!

However, if you use:
SPSite site = new SPSite("http://merdev-moss:5050"); SPWeb web = site.OpenWeb();

this means you are creating a New Context and you need to dispose this connection which will be automatically done if you use it inside using

using (SPSite site = new SPSite("http://merdev-moss:5050"))
{
    using (SPWeb web = site.OpenWeb())
    {
       //do stuff
    }
}
1

The first option means that the feature needs to be scooped as web to use that method and if you change the scope you need to change the method as it will throw an exception. Use that method only if you need the feature as web and nothing else! same goes for any scope that you choose.

The second I prefer as it is not dependant on the scope of the feature,

for me I would use this:

SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb

more detail on what you can use to achive what you want can be found here:

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.aspx

The first one is using the current web, the second is creating a new instance that you need to dispose of ;)

hope it helps :)

1
  • If you activate your feature from Powershell, your feature activation will fail, because there you don't have an SPContext. That's why it's always better to use the properties.Feature.Parent property.
    – Norbert
    Dec 6, 2012 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.