Thursday, May 8, 2008

HttpContext in eventhandler

First off all, i would like to thank Adil Baig to show Developers (specifically in MOSS) like us that thing like this can be done in first place.

I often heard that HttpContext is null in event handler and we cannot use session and Request.QueryString.
Here is the solution.
public class MyEventHandler: SPItemEventReceiver
{
HttpContext current;
public MyEventHandler()
{
current = HttpContext.Current;
}

public override void ItemAdding(SPItemEventProperties properties)
{
/// some thing went wrong so you need to cancel the event and redirect
}

With this Context you can find all the properties you want.
In SharePoint there is not any functionality for displaying our customized error page.
Like if for data validation in event/item handler we use
properties.ErrorMessage = “Opps... Not allowed”;
properties.Cancel = true;

And validation message displayed in SharePoint error Page which looks error in application.
But with this Context you can use to redirect to any of your custom or any out of the box Page.
SPUtility.Redirect(Url, SPRedirectFlags.Default, current);

HttpContext is available only in synchronous event like ItemAdding and ItemUpdating.

More Info Click Here

18 comments:

Anonymous said...

this sounds familiar from an older post by this guy, does it???
http://baigadil.blogspot.com/2008/01/getting-application-context-in.html

Parth Patel said...

You are absolutely right.
We had taken idea from that site only and we have already given a link (More info) at the bottom of the post.

That was our mistake that we had not mentioned name of "Mr. Adil Baig" in the post, that we edited now.
Check the post again.
Thanks.

chris said...

Hi,

I am writting an event handler for a list and here is my code:
SPSite newSite = new SPSite(SPContext.Current.Site.url);

SPWeb newWeb = newSite.OpenWeb();

SPWebCollection subSites = newWeb.Webs;

SPWeb newSubWeb = subSites.Add(SiteTitle,SiteTitle,Description....)

The above code for some reason is not working. However when I harcode the url rather than trying to get the current url using SPContext it works!!!

Can you please tell me what I might eb doing wrong!

Thanks alot

Chris Sammut

Jayesh Prajapati said...

Hi chris,
This code works for you,and kindly metion your mail id so that we can provide you better service.

public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
this.DisableEventFiring();
using (SPSite site = new SPSite(properties.SiteId))
{
SPWeb subsite = site.OpenWeb();
SPWebCollection subSites = subsite.Webs;
SPWeb newSubWeb = subSites.Add("SPKINGS");
newSubWeb.Update();
}
this.EnableEventFiring();
}

Regards,
SharePointKings Team.

chris said...

Thanks lot for your help....
It worked!

Cool said...

Hi,

I have a scenario where I need to get the HttpContext on the OnActivated() method which is part of the Custom Site Definition provisioning. I'm trying to do a redirect using the SPUtility.Redirect to a custom application page which will set the permissions similar to permsetup.aspx. Always I get the HttpContext as null when the code hits SPUtility.Redirect.

SPUtility.Redirect("new_permsetup.aspx", SPRedirectFlags.RelativeToLayoutsPage,HttpContext.Current);

The above redirect is used on the siteprovisioning.cs page which basically has a partial class inheriting from SPFeatureReceiver and hence I'm not able to get the context as you mentioned in your earlier posts using SPItemEventReceiver. Any thoughts will be much appreciated.

VJ

Cool said...

Hi,

I have a scenario where I need to get the HttpContext on the OnActivated() method which is part of the Custom Site Definition provisioning. I'm trying to do a redirect using the SPUtility.Redirect to a custom application page which will set the permissions similar to permsetup.aspx. Always I get the HttpContext as null when the code hits SPUtility.Redirect.

SPUtility.Redirect("new_permsetup.aspx", SPRedirectFlags.RelativeToLayoutsPage,HttpContext.Current);

The above redirect is used on the siteprovisioning.cs page which basically has a partial class inheriting from SPFeatureReceiver and hence I'm not able to get the context as you mentioned in your earlier posts using SPItemEventReceiver. Any thoughts will be much appreciated.

AnilChitatil said...

Hai Chris,

I had an SPList in my main site and another one SPList in my subsite. These two SPList has same fields. In my main site i have a temporary SPList, when i add any item in the main site SPList or subsite SPList i need to trigger my event handler and which add corresponding item to my temporary SPList also (which is in main site)

Note: I have a subsite, in it i have an SPList, when i add an new item to the subsite SPList also i need to trigger my event handler.

Can you tell me how can i do it,

Thanx in advance.

AnilChitatil
anilchitatil@gmail.com

Mondo said...

Cool: re null httpcontext

you have to declare and set the value of your httpcontext variable in the top level of your eventhandler. Right after the namespace and before your eventhandler class. Else it is null but does compile below that level.
ray

Mohammed Barakat said...

The HttpContext.Current Is Always Null When uploading multiple docs at the same time .

I faced the same issue when I was tring to update some custom fields of my document library when uploading new documents, the field was ( ProjectID ) which I put it inside a session in my webpart ( the step before uploading the document).

What I did is : I put the projectID into the cache ( per user ) inside the custom webpart which acts as a session as follows :

if (Request.QueryString["ProjectID"] != null)
{
HttpRuntime.Cache.Remove(SPContext.Current.Web.CurrentUser.LoginName);
HttpRuntime.Cache.Add(SPContext.Current.Web.CurrentUser.LoginName, ProjectID, null, DateTime.UtcNow.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
}

then I implemented the ItemAdded event and I get the value of the cached projectId through :



public override void ItemAdded(SPItemEventProperties properties)
{
try
{

string ProjID = "";

string CreatedBy = null;
if (properties.ListItem["Created By"] != null)
CreatedBy = properties.ListItem["Created By"].ToString().Split(';')[1].Replace("#","");

if (HttpRuntime.Cache[CreatedBy] != null)
{
//SPContext.Current.Web.CurrentUser.LoginName;
ProjID = HttpRuntime.Cache[CreatedBy].ToString();

if (properties.ListItem["Project"] == null)
{
properties.ListItem["Project"] = new SPFieldLookupValue(ProjID);
properties.ListItem.SystemUpdate();
}


base.ItemAdded(properties);

}

}
catch (Exception ex)
{ }


}

SharePoint Kings said...

Mohammed,

HTTPContext.Current will not be available in ItemAdded directly. because its asynchronous event.

you will get HttpContext in only in ItemAdding only

can you try cookie if you are using your custom webpart?

and lastly check comments by "Manoj Kumar Sriram" in this post
http://www.sharepointkings.com/2008/06/redirection-from-event-handler.html

he successfully used HttpContext.Current in ItemAdded using static context but you check how its behaving in your case

PN said...

I have a similar requirement as that of Anil's requirement.

I have a Survey List in English site and a similar list is on the Japanese and Russion Language sites.

The requirement is to push the questions created in Survey list on English site to the other two survey lists on Japanese and Russian sites.

Let me know if you have dealt with a similar requirement earlier.

Thanks

Pradeep Narsimhula

SharePoint Kings said...

Pradeep,

we had not done anything like that but what the problem you are facing? you can use event handler and push same question in other site's discussion. (changing the language is your call)

are our understanding correct?

Suresh said...

Hi,
i developed a doucment Library system. there i created some groups like Contrubute Users group without delete, Readonly users group,Admin group.
he is my question: how to check login user group to validate Itemdeleteing and itemadding events. based on that i will send a message to other user groups.

SharePoint Kings said...

Suresh,
in item adding or deleting event find user's groups and do the things no need to redirect for this use error message property with show error true

parastoo said...

Hi,

1-how can i start workflow with my data within event handler?(i must send username persone that he/she active eventhandler to workflow,how i do this?)

please give me information about manager.startworkflow.(i dont know that datas will pass in manager.startworkflow how is create)

2-how i recieve this data in workflow?(or how i call this data of the event handler in workflow)
Please Help Me

thanks

SharePoint Kings said...

@Parastoo,

please check this link
http://www.sharepointkings.com/2008/09/how-to-start-workflow-programmatically.html

also check other workflow related article which will help you.

santhosh said...

thanks a lot :)




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com