Showing posts with label Event Recievers. Show all posts
Showing posts with label Event Recievers. Show all posts

Tuesday, 2 December 2014

SharePoint Interview Questions and Answers: EventRecievers


Nice post by  sasikumarreddy valipireddy on Event Recievers in Sharepoint




  1. Event Receivers and types of event receivers?
  2. Best coding practice on event receivers?
  3. Use of DisableEventFiring() and EnableEventFiring()?
  4. BeforePropeties and AfterProperties?
  5. What all are Event receivers features introduced in SharePoint 2010?
  6. What are all new Event Receivers introduced in SharePoint 2010?
  7. Difference between event receivers and workflows?
  8. How to add an event receiver to the specific list programmatically?
  9. How to add an event receiver to the specific content type programmatically?
  10. How to add an event receiver to the content type using feature.xml file?
  11. The ItemUpdating event or the ItemUpdated event occurs two times when you enable the Require Check Out option for a document library in Windows SharePoint Services 3.0?
  12. Event Receivers with custom error page?
  13. I have one requirement, i.e. is there is one list name “Student Marks” and fields has English, Hindi, Telugu, Total, AVG. Total=English+Hindi+Telugu. The total field should be update automatically if I update any of the language marks. But here the actual problem is if you are updating two fields at a time the ItemUpdating event fires 2times. But I don’t want to fire twice. How?
  14. I have one document library and I want to allow only specific extension files (like .doc, .pdf etc.) into that document library? How can I prevent it?
  15. Why can't we use spcontext in event receivers? 
  16. Error occurred in deployment step 'Recycle IIS Application Pool': The vssphost4.exe process was unable to start due to an unknown error?  
  17.  How to delete the event receivers?
  18. How to check whether the event receiver attached or not? 
  19. I have one custom developed master page. I want to set this master page dynamically for newly created sites. what is the approach to do that?
  20. How can we handle not to allow duplicate documents in a document library?
Event Receivers:
Event Receivers has taken places either synchronously or asynchronously. If the action has taken before code execution.

All receivers that end with “ing” are synchronous and those which end with “ed” are asynchronous.

Synchronous Event Handlers will work before the event is completed while asynchronous event handlers will fire after the event is completed. 
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
Note:-Event Handlers should be placed in GAC only.
New Features in SharePoint 2010:
  1. Another great improvement to event handlers in SharePoint 2010 is with the improvements to Visual Studio 2010, and what it takes to create them. Notice, when you add a new item into a Visual Studio project, three is an Event Receiver template you can choose from:
  2. Now can register an event to the site level or web level. In the feature xml file we have to use the “Scope” attribute to either “Web” [Web site] or “Site” [Site collection]. The default value will be site level. This is one of main feature introduced in SharePoint 2010.
  3. Another important one is the ListUrl attribute, which allows you to scope your receiver to a particular list by passing in the relative URL.
  4. Note: ListUrl works only if feature has Scope=”Web”. In case the feature has Scope=”Site”, event receiver is fired for every list and library, ListUrl is ignored.
  5. In SharePoint 2007, error messages are not user friendly in event receivers. Now in SharePoint 2010, can provide user friendly error messages by redirecting to our own custom application pages.
  6. By using below properties, we can do it:
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "/_layouts/EventReceiverProject1/CustomErrorPage.aspx?Error=" + errorMessage;
New Event Receivers on SharePoint 2010:
On List:
    ListAdding(SPListEventProperties): This will be fired when a new list is getting created.
    ListAdded(SPListEventProperties): This will be fired after a list is created in database.
    ListDeleting(SPListEventProperties): This will be fired when a list is deleting.
    ListDeleted(SPListEventProperties): This will be fired after a list is deleted from database.
On Web:
    WebAdding(SPWebEventProperties): This will be fired before a new site is getting created.
    WebProvisioned(SPWebEventProperties): This will be fired after web site is successfully created and provision processed successfully. This will work either in synchronous mode or asynchronous mode.
Note: A site is being provisioned and A site was provisioned-->Notice that now you are no longer depending on "feature stapling" to execute code on a site after it is provisioned. You can now just attach this web event. This is new concept introduced in SharePoint 2010.
DisableEventFiring() and EnableEventFiring():
One reason to prevent events from being raised is to avoid recursion. For example, if you have an ItemAdded event on a list and you write code within it to add an item, you can put that code in a DisableEventReceivers() ... EnableEventReceivers() block to avoid recursion.
When you add a new item, only the ItemAdding() event is raised. However, in cases where Explorer View is used, both the ItemAdding() and ItemUpdating events are raised. In such cases the ItemUpdating event always occurs after the ItemAdding() event occurs.
Difference between event receivers and workflows?
  1. Unlike Workflows, Event Receivers cannot be triggered manually. SharePoint event handlers run for a short period of time (generally seconds), while SharePoint workflows may run for a much longer time period (days, months, or even years).
  2. Workflows run asynchronously means we can trigger the workflows only when an item is created and when an item is modified but event receivers can work either synchronously and asynchronously.
  3. Workflows can start manually but Event Receivers cannot.
  4. Can cancel the operation in Workflows but in SharePoint 2010 we can cancel the event receivers also.
  5. We can create workflows either by using SharePoint designer or visual studio but we should create an event receivers using visual studio only.
  6. SharePoint event handlers are automatically initiated, while SharePoint workflows can be initiated either automatically or manually.
  7. There is no User Interface(UI) for the event receivers.
Reference:
Add an event receiver to the specific list programmatically?
Add an event receiver to the content type programmatically?
Add an event receiver to the content type using feature.xml file?
Best coding practice on event receivers?
The ItemUpdating event or the ItemUpdated event occurs two times when you enable the Require Check Out option for a document library in Windows SharePoint Services 3.0
How to Event Receivers with custom error page?
I have one requirement, i.e. is there is one list name “Student Marks” and fields has English, Hindi, Telugu, Total, AVG. Total=English+Hindi+Telugu. The total field should be update automatically if I update any of the language marks. But here the actual problem is if you are updating two fields at a time the ItemUpdating event fires 2times. But I don’t want to fire twice. How?
By using DiableEventFiring and EnableEventFiring methods we can prevent from event being raised 2 times. [Please refer on the above to get clear idea on those 2methods].

Why can't we use spcontext in event receivers?
We cannot use the SPContext.Current property into the event receivers, because the current context in event receivers is always equal to null. 
Avoid duplicate files into the document library in SharePoint 2010?

Use event receiver and checks at the ItemAdding level
http://social.technet.microsoft.com/Forums/en-US/sharepointdevelopment/thread/301f3a11-498a-4cf7-93f1-774a032606d0


Error Type: Error occurred in deployment step 'Recycle IIS Application Pool': The vssphost4.exe process was unable to start due to an unknown error.

The reason for cause of that issue is: Might be your opened solution debugging location is same as others opened solution debugging location. So, please close all the opened solutions and try again by opening your sol. That issue will not come this time. 
I have one document library and I want to allow only specific extension files (like .doc, .pdf etc.) into that document library? How can I prevent it?
You need to prevent it before adding files into the document library for that we need write code in ItemAdding() event.
public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            //if the list is equals to the PDF routing then only go inside...
            if (properties.ListTitle.Equals(ConfigurationManager.AppSettings["PDF_Library_Name"], StringComparison.InvariantCultureIgnoreCase))
            {
                string fileUrl = properties.AfterUrl;
                if (!string.IsNullOrEmpty(fileUrl))
                {
                    fileUrl = fileUrl.ToLowerInvariant();
                    string fileExtension = Path.GetExtension(fileUrl);
                    if (!string.IsNullOrEmpty(fileExtension) && !fileExtension.Equals(".PDF", StringComparison.InvariantCultureIgnoreCase))
                    {
                        properties.Cancel = true;
                        properties.ErrorMessage = "Only PDF files are allowed for PDF signature routing. Please try again.";
                    }
                }
            }
        }
Event Receiver remembers points:

Below are my best consideration points on Event Receivers and also shared enhancements in SharePoint 2010.
  1. By default event receivers are asynchronous meaning that they run under the SharePoint timer service (OWSTIMER.exe). This means that the event receivers:
  2. Another important property you may want to set for each event you attach is the Sequence Number. The sequence number determines the order your event assemblies’ fire. This is especially important when you have created multiple assemblies that are all attached to the same Site, List or Content Type event. 
  3. When you enable the Require Check Out option for a document library in Microsoft Windows SharePoint Services 3.0, the ItemUpdated event or the ItemUpdating event occurs two times. This occurs when the document library is updated. The same problem happens when you upload a document into a document library with a required column if this column is not filled in the document.
  4.         Sol: DisableEventFiring() and EnableEventFiring() [Explained about these 2months below clearly.]
  5. My test is that itemadding and itemadded will fire after you click OK on the first window (the one you choose the document to upload) and before the second window appears;
  6. Itemupdating and itemupdated will fire after you click Save on the second window (the one you fill out Meta data).
  7. The default synchronization behavior is synchronous for before events and asynchronous for after events.
  8. You can tell SharePoint to just have the receiver work on the root site by using the RootWebOnly attribute on the <Receivers> node.
  9. Do not instantiate SPWeb, SPSite, SPList, or SPListItem objects within an event receiver. Event receivers that instantiate SPSite, SPWeb, SPList, or SPListItem objects instead of using the instances passed via the event properties can cause the problems: Check below on best practices on working Event Receivers.
  10. Debugging a SPEmailEventReceiver requires attaching the debugger to the OWSTIMER.EXE process. This is because the timer service fires the Incoming E-mail timer job, rather than the SharePoint web application.
Please add comments if its really helped you. Thanks for reading.




Reference:

http://sharepointquicksolutions.blogspot.in/2012/07/event-receivers-interview-questions-and.html

Monday, 1 December 2014

Event Receivers in SharePoint: A complete guide


1. Introduction

While developing any application we need to handle some events. For example, when a new item is added to a list, we may need to perform some action like say, notifying the person who created the list item, or modifying the dependent entries in some other location etc. Handling of such events is facilitated by event receivers. We have many SharePoint event receiver classes in order to handle variety of events.



2. SharePoint Event Receiver types

There are basically two types of event receivers: Synchronous and Asynchronous event receivers.Synchronous event receivers are also known as ‘Before’ event receivers. They are used to perform some custom action before an event occurs. In this case, there is a flexibility of cancelling the event on some conditions so that the event that gets initiated will not occur.
Asynchronous event receivers are also known as ‘After’ event receivers. They are used to perform some custom action after an event occurs. These events are asynchronous because they need not happen immediately after the event is performed. They can happen sometime later also, unlike synchronous event receivers which occur immediately before an event occurs.

3. Classes of Event Receivers

There are fundamentally five classes for Event Receivers for SharePoint 2007.
Microsoft.SharePoint.SPEmailEventReceiver : This provides event handling whenever a  user sends an email to a list on which e-mail feature is enabled
Microsoft.SharePoint.SPFeatureReceiver :  This provides event handling whenever is feature is acted upon
Microsoft.SharePoint.SPItemEventReceiver : This provides event handling whenever any action is performed on a list item
Microsoft.SharePoint.SPListEventReceiver : This provides event handling whenever a list definition is modified like adding or deleting columns and modifying existing columns.
Microsoft.SharePoint.SPWebEventReceiver : This provides event handling whenever a site or a site collection is deleted or moved
Each of the classes has some virtual methods which are to be over-ridden to perform our custom action. Those methods are as follows.



3.1 Site Level Events

Methods under the class SPWebEventReceiver handle site level events. A brief overview of those methods is as follows.
Site Deleted – This occurs after a site collection is deleted.
Site Deleting – This occurs before a site collection is being deleted.
Web Deleted – This occurs after a website has been deleted completely. This is an asynchronous after event.
Web Deleting – This occurs before a website is deleted. This is a synchronous before event.
Web Moved – This occurs after an existing website is moved. This is an asynchronous after event.
Web Moving – This occurs before a website is moved. This is a synchronous event.

3.2 List Level Events

Methods under the class SPListEventReceiver handle list level events. A brief overview of those methods is as follows.
Field Added – This occurs after a field link is added to a list.
Field Adding – This occurs when is field is being added to a content type.
Field Deleted – This occurs after a field is deleted from a list.
Field Deleting – This occurs when a field is being deleted from a list.
Field Updated – This occurs after a field is updated in a list.
Field Updating – This occurs when a field is being updated in a list.

3.3 Item Level Events

Methods under the class SPItemEventReceiver handle item level events. A brief overview of those methods is as follows.
ItemAdded – This occurs after a new item is added to a list. This is an asynchronous after event.
ItemAdding – This occurs before an item is added to a list. This is a synchronous before event.
ItemAttachmentAdded – This occurs after an attachment is added to a list. This is an asynchronous event.
ItemAttachmentAdding – This occurs while an attachment is being added to a list.
ItemAttachmentDeleted – This occurs after an attachment is removed from an item.
ItemAttachmentDeleting – This occurs while an attachment is being removed from an item.
ItemCheckedIn – This occurs after an item is checked in.
ItemCheckedOut – This occurs after an item is checked out.
ItemCheckingIn – This occurs while an item is being checked in.
ItemCheckingOut – This occurs while an item is being checked out.
ItemDeleted – This occurs after an item is deleted from its list.
ItemDeleting – This occurs while an item is being deleted from its list.
ItemFileConverted – This occurs when the type of file is being converted.
ItemFileMoved – This occurs after a file is moved.
ItemFileMoving – This occurs while a file is being moved.
ItemUncheckedOut – This occurs after un-checking an item in a list.
ItemUncheckingOut – This occurs while an item is being unchecked.
ItemUpdated – This occurs after an item is updated.
ItemUpdating – This occurs while an item is being updated.

3.4 Feature Events

Methods under the class SPFeatureReceiver handle events related to feature. A brief overview of those methods is as follows.
FeatureActivated – This occurs after a feature is activated.
FeatureDeactivating – This occurs when a feature is being deactivated.
FeatureInstalled – This occurs after a feature is installed.
FeatureUninstalling – This occurs when a feature is being uninstalled.

3.5 Email Events

Method under the class SPEmailEmailEventReceiver handles the event related to email. A brief overview of the method is as follows.
EmailReceived This occurs after an email message has arrived (to an email enabled list).

4. Binding the Event Receivers

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

4.1  Using Feature

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.

4.2 Using  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.

4.3 Using WSS 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’.

5. Unbinding SharePoint Event Receiver

• 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).



















Reference:

http://beginnersbook.com/2013/02/event-receivers-in-sharepoint/