Getting SPContext inside event receiver
Asked Answered
C

3

7

I created an Event Receiver, but the problem is that I can't get a reference to the SPContext: SPContext.Current returns null. I need it to add some lists to the site. Does anyone have an idea of how I could get it?

Also I tried putting break points inside the event receiver, but FeatureActivates never triggers for some reason. What is the correct event to use when a list is activated right after de deployment?

Capitate answered 27/2, 2012 at 16:9 Comment(0)
T
15

You can't get SPContext inside handlers - this is by design. You should use event properties passed as argument to the handler to get reference to current web, list item etc. For example in feature activated handler you can do it like this:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb web = properties.Feature.Parent as SPWeb;  
    //Some code with web
}

If Feature Scope is Site then

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
        SPSite site = properties.Feature.Parent as SPSite;  
        //Some code with web
}
Tymon answered 27/2, 2012 at 19:30 Comment(0)
F
5

I figured that the scope of the feature matters. If you deployed the feature in the site scope then you can get the web using this line of code:

SPWeb web = (properties.Feature.Parent as SPSite).OpenWeb();
Finial answered 6/8, 2012 at 18:13 Comment(0)
B
2

I know this thread is kind of old, but really you should use:

SPWeb web = properties.OpenWeb() 

as per SP best practices: http://msdn.microsoft.com/en-us/library/ee724407.ASPX It ensures you have no objects to dispose and keeps you from hitting a casting error.

Bey answered 6/12, 2013 at 22:49 Comment(1)
This isn't for feature receivers.Franke

© 2022 - 2024 — McMap. All rights reserved.