Sunday 16 December 2012

Events in SharePoint firing more than once for an event receiver

There might be a requirement where we want to  strip permissions programmatically when uploading a document If we have kept versioning enabled then there will be multiple versions of the item created also if check in and check out are enabled a version of the document item will be created every time we strip permissions. Also note the ItemUpdated Event for a document library fires more than once 
The reason being a document version is created when it is uploaded and when editing the properties the document is by default checked out and then checked in 
So another version of the document is created  
Now when we want to strip the item permissions and there are multiple item permissions to be assigned then what we can do is that we will have to put the following line of code inside our method 

 this.EventFiringEnabled=false; 
this.EventFiringEnabled=true; 
At the end of your method just before you close the method 
So your code looks something like this 

public class SomeClass:SPItemEventReceiver 
{ 
public override void ItemAdded(SPItemEventProperties properties) 
{ 
this.EventFiringEnabled=false; 
SPListItem item=properties.ListItem; 
//Your code goes here 
item.Update(); 
this.EventFiringEnabled=true; 
} 
}