SharePoint 2010 Event Receiver Interview Questions

1.         What is event receiver?
An event receiver is a piece of managed code that responds to SharePoint events when specific triggering actions occur on a SharePoint object. Triggering actions include activities such as adding, updating, deleting, moving, checking in, and checking out.

2.         What Are Event Hosts?
Event hosts are common SharePoint objects that expect to receive events—in other words, objects whose event receivers "listen" for SharePoint events. These SharePoint event host object types include instances of common objects such as SharePoint site collections, sites, and lists. Each event host type has a specific set of event receiver base types from which it can inherit.

3.         What are the types of event receivers?
There are two types of event receivers available in SharePoint.
1. Syncronous Events: This event is executed in the same thread in which the triggering action is occurring. For example, when the user adds an item from the SharePoint user interface, the event is fully executed before returning to the user and showing that the item was added. These are before events that occurs before the currently requested operation happens.  This provides an opportunity for an event receiver to perform tasks before data is committed to a database. A good example of the use of Before events is performing data validation, because Before events fire prior to commitment of data. You can also use Before (or synchronous) events to cancel user actions—for example, if data validation fails.
(e.g. ItemAdding, ItemUpdating,ItemDeleting)

2. Asynchronous Events: This event occurs at a later time than the action that triggered it, and it executes on a thread that is different from the one in which the triggering action is running. These are after events. After events trigger event receivers that execute after user actions are committed to the content database; they invoke code that runs after the content database has been modified. This allows you to execute logic that occurs after a user has completed a specific action.
(e.g. ItemAdded, ItemUpdated,ItemDeleted)

4.         What is the base class for List events and List Item events?
The Base class for SharePoint events is   Microsoft.SharePoint.SPEventReceiverBase. The List and List Item events inherited based on the scope of event host as below.
   List Item: 
Microsoft.SharePoint.SPItemEventReceiver
  SharePoint List:  Microsoft.SharePoint.SPListEventReceiver

5.         How to cancel the actions using event receiver?
SharePoint before events(synchronous) can be cancelled since it get trigged before completing the operation. Any validation can be applied as well as the event can be cancelled using event properties.
E.g
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
if(condition=true)
{
properties.Cancel=True;
}
}

6.         What is the best practice to get the context of SPSite when using event receiver?
The event properties should be used to get the current SPContext. If we get the current context of the site in different object  like SPContext then your connection may get lose when your dispose the site context.  Use SPItemEventProperties.Site/SiteID properties to get the current context or use SPItemEventProperties.Context property.

7.         Best coding practice of event receiver?
a.       Enable / disable firing other event in the same SharePoint object to avoid unnecessary loops.
b.      Do not use SPcontext to get the site/web properties, instead user event properties to get site/web properties
c.       Dispose if any heavy object process in event receiver in final block
d.      Do not use RunWithElevatedPrevillege if event receiver planned to be deployed as sandbox solution
e.      Use UserToken to impersonate your current access.

8.         What is Enabling and Disabling event receiver?
SharePoint Event is nothing but triggering action occurs on a SharePoint object. The trigger may come from manual action (updating item manually) or automatic action (SPItem.Update). Both actions will fire the events. Sometimes it makes unnecessary events in the same list. These events many go infinitely and impact the server performance majorly. To avoid this unnecessary event firing, we can purposely enable/disable the other event firing on the same object. 
You can achieve this by executing the DisableEventFiring method on the list item. After the changes are saved you can activate the event handler again by executing the EnableEventFiring method on the list item.
Best practice is to execute the DisableEventFiring method right before any of the update methods and to execute the EnableEventFiring method right after one of the update methods.

9.         What is before property?
Get the string/value pairs in a hash table before the event occurred on the SharePoint item.

10.     What is after property?
Get the string/value pairs in a hash table after the event occurred on the SharePoint item.

11.     What is the difference between event receiver and workflow?
Workflows:
·         SharePoint Workflow consist a set of task(s) which can be triggered both manually and automatically.
·         SharePoint Workflows are created in SharePoint Designer, Microsoft Visio and of course through Visual Studio.
·         The workflow is triggered once an action is completed.
·         Workflow can be exported and imported
·         Workflow can be paused
·         Workflow can send mails without attachment
·         Does not required coding knowledge to work on SPD workflows
·         Multiple forms(initiation, task edit..) can be associated as part of workflow
Event Receivers:
·         SharePoint event receiver contains custom coding/logic which can be triggered automatically based on the event host type.
·         SharePoint event receivers can be created only in Visual Studio.
·         The events can be triggered before action or after action.
·         Events cannot be exported and imported
·         Events can be cancelled(synchronous) but cannot be paused
·         Even receivers  can send mails with attachment
·         Required coding knowledge
·         No custom forms associated as part of event actions

12.     Can SharePoint events cancelled and redirected to differ page?
Yes, SharePoint Synchronous events can be cancelled since it occurs before action on SharePoint object. So the event can be cancelled and redirects to different page.
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 Obsolete: The event is cancelled, but a URL is provided that redirects
the user to a custom error message page, or to any desired URL.
e.g.
public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);

           properties.Cancel = true;
           properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
           properties.RedirectUrl = "/_layouts/DeletingEventReceiver/ErrorPage.aspx";
           this.EventFiringEnabled = false;
       }
13.     How to add an event receiver to the specific list programmatically/object model?
The below is a sample code how an event receiver is bound with a list.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = properties.Feature.Parent as SPWeb;
web.Lists["Video Library"].EventReceivers.Add(
SPEventReceiverType.ItemAdded,
“MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa”,
” MyProject.MyModule.Events.VideoAddedEventReceiver “);
}
In the above code, the custom class ‘VideoAddedEventReceiver’ of type ‘ItemAdded’ is bound with a list named ‘Video Library’.


14.     Why can’t we use SPContext in even receiver?
The event properties should be used to get the current SPContext. If we get the current context of the site in different object  like SPContext then your connection may get lose when your dispose the site context.  Use SPItemEventProperties.Site/SiteID properties to get the current context or use SPItemEventProperties.Context property.

15.     Can event receiver deployed as sandbox solution?
Yes, Event receivers can be deployed as sandbox solution. But make sure that your custom code is not using RunWithElevatedPrevillege method. Sandbox solution only can access the site collection object and it cannot access other than site collection object, network resources, database

16.     What is event binding OR how to register events on SharePoint Object?
For the event receivers to receive an event, they should be bound to the corresponding objects. This binding can be done in three ways.
Using a feature
Using a content type
Using WSS object model

17.     What is event unbinding and how to unbind?
• Event receiver bound with the help of content type cannot be unbound.
• If the event receiver was bound with the help of a feature, deactivating the feature would unbind the event receiver from its associated object.
• If the event receiver was bound using WSS object model,
1. Move to the object (site collection or website or list) to which the event receiver is bound.
2. Retrieve the event receiver definition of the intended event receiver.
3. EventReceiverDefinitionObject.Delete().
4. Call the update of that object (site collection or website or list).

18.     How to find event receiver is attached to an list/library?
Registered events can be fetched using server object model or PowerShell scripts

19.     What is best either event receiver or workflow?
Its based on requirement. If business need very simple operation to be done with any custom calculation then workflow is the best option. If business need some custom business logic OR some action on before event then event receivers is best choice.

20.     Can event receiver register using feature?
Yes

21.     Can more than one event receiver register on same list/library?
Yes, the event receiver sequence specifies the order in which an event receiver is executed in cases where an event triggers multiple event receivers. For example, if you have two ItemAdded event receivers bound to the same list (one from Assembly "1" and the other from Assembly "2"), the event receiver that is bound with a lower sequence number is executed first. A practical example is adding an event receiver to a system list that already has a system event receiver bound to it. In that case, you assign the new event receiver a higher sequence number.

22.     If more than one event receiver registered on single list/library then how it works?
The event receiver sequence specifies the order in which an event receiver is executed in cases where an event triggers multiple event receivers. For example, if you have two ItemAdded event receivers bound to the same list (one from Assembly "1" and the other from Assembly "2"), the event receiver that is bound with a lower sequence number is executed first. A practical example is adding an event receiver to a system list that already has a system event receiver bound to it. In that case, you assign the new event receiver a higher sequence number.

23.     Where event receiver is deployed?
Events can be deployed on both sandbox solution and farm solution. If we use sandbox solution then it will deployed on site collection solution gallery and required DLL will be  extracted on UCCache folder when needed. If event receiver deployed as farm solution then the DLL registered in GAC and solution will be available in farm solution gallery.

24.     How to add an event receiver to the specific content type?
In a content type, the elements.xml file should be as follows.

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
<ContentType ID=”id” Name=”name” Group=”GroupName” Description=”Description of content type” Version=”0″>
<FieldRefs>
<FieldRef ID=”FIELD ID” Name=”FIELD NAME” />
…………………………
…………………………
</FieldRefs>
<XmlDocuments>
<XmlDocument NamespaceURI=”http://schemas.microsoft.com/sharepoint/events“>
<spe:Receivers xmlns:spe=”http://schemas.microsoft.com/sharepoint/events“>
<Receiver>
<Name> VideoAddedEventReceiver </Name>
<Type> ItemAdded </Type>
<SequenceNumber>20000</SequenceNumber>
<Assembly> MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa </Assembly>
<Class> MyProject.MyModule.Events.VideoAddedEventReceiver</Class>
<Data></Data>
<Filter></Filter>
</Receiver>
</spe:Receivers>
</XmlDocument>
</XmlDocuments>
</ContentType>
</Elements>

The same limitation of ‘using feature’ applies to content type also because a content type cannot be associated with a site.
Sequence Number determines when the event receiver should get executed in case if more than one event receivers are about to be executed. An event receiver with greater sequence number gets executed after its counterpart with lesser sequence number.

25.     How to add an event receiver to the content type using feature.xml file?
In the feature, the elements.xml file should be as follows.

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
……………………
……………………
<Receivers ListTemplateId=”100″>
<Receiver>
<Name>VideoAddedEventReceiver</Name>
<Type>ItemAdded</Type>
<SequenceNumber>20000</SequenceNumber>
<Assembly>MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa</Assembly>
<Class>MyProject.MyModule.Events.VideoAddedEventReceiver</Class>
<Data></Data>
<Filter></Filter>
</Receiver>
………………………………
……………………………..
</Receivers>
</Elements>

Any number of receivers can be bound through one feature.
Limitation: Site level events cannot be registered/bound through the feature because we cannot associate a ListTemplateId with a site.

26.     What are the new event receivers added in SharePoint 2010?
Event Host Type
Existing Events
New Events
Events Base Class
SPSite
SPWeb
SiteDeleting
SiteDeleted
WebDeleting
WebDeleted
WebMoving
WebMoved
WebAdding
WebProvisioned

SPWebEventReceiver
SPSite
SPWeb

ListAdding
ListAdded
ListDeleting
ListDeleted
SPListEventReceiver

SPSite
SPWeb
SPList
SPContentType
FieldAdding
FieldAdded
FieldDeleting
FieldDeleted
FieldUpdating
FieldUpdated

SPListEventReceiver

SPSite
SPWeb
SPList


EmailReceived
SPEmailEventReceiver
SPSite
SPWeb
SPList
SPContentType

WorkflowStarting
WorkflowStarted
WorkflowCompleted
WorkflowPostponed
SPWorkflowEventReceiver
SPSite
SPWeb
SPList
SPContentType
ItemAdding
ItemAdded
ItemDeleting
ItemDeleted
ItemUpdating
ItemUpdated
ItemFileConverted
ItemFileMoving
ItemFileMoved
ItemCheckingIn
ItemCheckedIn
ItemCheckingOut
ItemCheckedOut
ItemAttachmentAdding
ItemAttachmentAdded
ItemAttachmentDeleting
ItemAttachmentDeleted

SPItemEventReceiver


12 comments: