Event Receivers – Misc

Avoid Recursion

When your event receiver respond to a list/item update event, it may update another list (e.g., Log) which in turn generate another update event, so it keeps looping.

To avoid this recursion, this is the code:

ItemUpdated() {
this.DisableEventFiring(); ß First disable EventFiring, so this doesn’t fire an event
item[fieldname]=somevalye ß Do your business here.
objitem.SystemUpdate(false); ß Ensure version doesn’t change
this.EnableEventFiring(); ß Enable event firing again
}

DisableEventFiring, EnableEventFiring
—————————————————————-

Canncelling Event
http://www.zimmergren.net/archive/2010/01/05/sp-2010-how-to-event-receivers-and-custom-error-pages.aspx

When an event is being cancelled for whatever reason, you issue this command:

properties.Status=SPEventReceiverStatus.XXXXXX

This XXXXXX can be:

Continue – The event is allowed to continue.
CancelNoError – The event is cancelled but no error message is displayed.
CancelWithError – The event is cancelled and an error message is displayed.
CancelWithRedirectUrl – The event is cancelled, but a URL is provided that redirects the user to a custom error message page, or to any desired URL.

(in CancelWithRedirectURL, you would write: properties.RedirectUrl=”_layouts/xxxxxxxx/xxxx.aspx”

—————————————————————-
In SharePoint, we know, there are two types of event receivers, asynchronous and synchronous, for example, the ItemUpdating and ItemUpdated. The ItemUpdating is synchronous while the ItemUpdated is asynchronous. The obvious difference is, the synchronous event is raised before committing the changes so that we have the opportunity to cancel whatever the the operation but not in the asynchronous event as that is raised after successfully committing the changes requested.

SPEventReceiverSynchronization.Default
SPEventReceiverSynchronization.Synchronous (such as ItemUpdating)
SPEventReceiverSynchronization.Asynchronous (such as ItemUpdated)

With this command you can force the synchronization to be aync or sync.

eventReceiver.Synchronization = SPEventReceiverSynchronization.Synchronous;

Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: