17 Sep 2011

Event Receivers SharePoint 2010

 

All event receivers provides two events Before and After.

Before events ( Synchronous) are those that happen just after the event occurred, but before SharePoint writes any data to the SharePoint content database
Such events are useful for custom validation, rules checking, and cancelation of users’ actions.
Before events run in the same process and thread as the current action
Example: ItemAdding Occurs before an item is going to be added to a list.

After events ( Asynchronous) are those that happen after SharePoint commits the data to the SharePoint content database
After events by default run in a background thread; however, you can force them to run synchronously
Example: ItemAdded Occurs after an item has been added to a list.

Event Receiver Base Classes:

SPItemEventReceiver
SPListEventReceiver
SPWebEventReceiver
SPWorkflowEventReceiver
SPEmailEventReceiver
SPFeatureReceiver

All of these receiver base classes (except for SPEmailEventReceiver and SPFeatureReceiver)
inherit from a common base class named SPEventReceiverBase,

 

SPItemEventReceiver

Example: An event receiver that traps ItemUpdating Before and ItemAdded After events

public class ContactItemEventReceiver : SPItemEventReceiver {
public override void ItemUpdating(SPItemEventProperties properties) {
String newEmail = (String)properties.AfterProperties[“Email”];
// Validate the email
      if (!regex.IsMatch(newEmail)) {
          // If it is not valid, cancel the current operation
         properties.Cancel = true;
         properties.ErrorMessage = “Invalid email value!”;
        }
  }
}
public override void ItemAdded(SPItemEventProperties properties) {

// Action after save
String newEmail = (String)properties.AfterProperties[“Email”];
// send mail

}

 

You can create a new Visual Studio 2010 project, selecting the “SharePoint 2010 – Event Receiver” project template

image

 

SPListEventReceiver

List event receivers are useful to enforce validation rules and policies and help avoid chaos to a website’s structure, you can enforce common naming conventions or common sets of validation rules
to each and every list created from a web browser.

SPListEventReceiver with which you can trap changes to the fields of an existing list as well as
actions related to adding or deleting lists instances.

 

The Events Provided by the SPListEventReceiver Base Class
FieldAdded Occurs after a field has been added to a list definition.
FieldAdding Occurs before a field is going to be added to a list definition.
FieldDeleted Occurs after a field has been removed from a list definition.
FieldDeleting Occurs before a field is going to be removed from a list definition.
FieldUpdated Occurs after a field has been updated to a list definition.
FieldUpdating Occurs before a field is going to be updated to a list definition.
ListAdded Occurs after a new list has been added to a SPWeb instance.
ListAdding Occurs before a new list is added to a SPWeb instance.
ListDeleted Occurs after a list has been deleted from a SPWeb instance.
ListDeleting Occurs before a list is deleted from a SPWeb instance.

 

Example : A list-level event receiver that traps field events

public class ContactsListEventReceiver : SPListEventReceiver {
public override void FieldAdding(SPListEventProperties properties) {
// Check if the list template is our custom list template
if (properties.TemplateId == 10001) {
properties.Cancel = true;
properties.ErrorMessage =
“You cannot change this list definition through the web browser”;
}
base.FieldAdding(properties);
}
public override void FieldDeleting(SPListEventProperties properties) {
// Almost the same code as FieldAdding event
}
public override void FieldUpdating(SPListEventProperties properties) {
// Almost the same code as FieldAdding event
}

 

SPWebEventReceiver

You can catch some events related to Site Collection deletion, both before and after the action, and for website creation, deletion, moving, and provisioning

Web-level event receivers are usually most useful for enforcing custom policies, custom, layout templates, or checking naming conventions, and restrict the deletion.

The Events Provided by the SPWebEventReceiver Base Class

SiteDeleted Occurs after a Site Collection has been deleted.
SiteDeleting
WebAdding Occurs before an SPWeb is being added to a list collection.
WebDeleted
WebDeleting
WebMoved
WebMoving
WebProvisioned Occurs after an SPWeb has been provisioned into a Site Collection.

 

SPWorkflowEventReceiver

You can intercept events related to running workflows.

Events Provided by the SPWorkflowEventReceiver Base Class

WorkflowCompleted Occurs after a workflow instance is completed.
WorkflowPostponed Occurs after a workflow instance has been postponed.
WorkflowStarted Occurs after a workflow instance has been started.
WorkflowStarting

 

SPWorkflowEventProperties.CompletionType
Whenever the workflow completes, you can read the CompletionType property from within the WorkflowCompleted event. The property might have any of the following values:
Completed
Errored
ExternallyTerminated
FailedOnStart
InternallyTerminated
NotApplicable

 

SPEmailEventReceiver

Allow you to intercept events when the list receives e-mail messages.

public class EmailEventReceiver : SPEmailEventReceiver
{
      public override void EmailReceived(SPList list,  SPEmailMessage emailMessage,  String receiverData)
  {
             if (!validSenders.Contains(emailMessage.Sender))
                  throw new Exception(“Invalid sender email”);
         base.EmailReceived(list, emailMessage, receiverData);
  }
}

Avoiding Event Loops

If you simply change an item inside an event receiver, such as ItemUpdated event, the event will fire again.

To disable event firing, all the event receivers inherit a Boolean property named EventFiringEnabled from the SPEventPropertiesBase base class.

It’s good practice to always set this flag to false at the beginning of your event receiver code, and then set it back to true at the end of code execution.

Event Deployment and Binding

Technique#1: A feature element file for provisioning a custom event receiver

Technique#2: using custom code

 

SharePoint 2010 has the ability to deploy an event receiver not only at the web level, but also at the Site Collection level.  except the SPEmailEventReceiver.

Another deployment feature introduced with SharePoint 2010 is the ability to bind an event receiver to a list template, using its ListTemplateId property,

No comments:

Post a Comment