To start with, let me differentiate between synchronous and asynchronous events.
The "...ing" events (synchronous) occurs before the action starts and the "...ed" (asynchronous) occurs after the actions ends.
Synchronous events:
· Occur before the event.
· Block the flow of code execution until your event handler completes.
· Provide you with the ability to cancel the events resulting in no after event (“...ed") being fired.
Asynchronous events:
· Occur after the event.
· Do not block the flow of code execution in SharePoint.
Custom event handler:
[code]
public class MyCustomEventHandler : SPItemEventReceiver
{
public MyCustomEventHandler() { }
public override void ItemAdding(SPItemEventProperties properties) { //your code goes here (synchronous event) }
public override void ItemAdded(SPItemEventProperties properties) { //your code goes here (asynchronous event)
}
}[/code]
Another business scenario maybe, one needs to redirect to a different page once custom code is executed. For redirection, fetching HttpContext is mandatory. Now, HttpContext is available in synchronous events but not in asynchronous events. Refer the code below, to see a workaround how to get HttpContext in Asynchronous events [this i found on SharePoint Kings Blog]:
[code]
public class MyCustomEventHandler:SPItemEventReceiver
{
HttpContext current;
static object obj;
public MyCustomEventHandler()
{
if (current == null)
{
current = HttpContext.Current;
}
}
public override void ItemAdded(SPItemEventProperties properties)
{
current = (HttpContext)obj;
//your code goes here (asynchronous event)
SPUtility.Redirect("http://server/page.", SPRedirectFlags.Trusted, current);
}
public override void ItemAdding(SPItemEventProperties properties)
{
obj = current;
//your code goes here (synchronous event)
}
[/code]
Cheers
4 comments:
There might be a problem in a multi user environment. Let’s say that a user fire ItemAdding, but before ItemAdded get the chance to execute, a second user fires ItemAdding. What will happen is that the ItemAdded event for the first user will get executed with the HttpContext of the second user (since you are using a static member to store the HttpContext between events).
yup! you are right
thanks a lot!
Post a Comment