Wednesday, May 9, 2012

SharePoint Registering Event Handlers to Content Type

Recently i have a requirement to registering the event handler to multiple lists having the same content type. Actually the event handler has ItemAdded/ItemUpdated events.

The complexity has been increased when new lists keep-on added at different places/sites. So i keep registering the same event handler with each newly created list which has same content type. I felt this is not a good approach to registering the event handler for each and every list.

When i investigated for the better solution, i found that event handlers can be registered for a specific content type. So as soon as the content type is added to the list, the same event handler is available on the list for a specific content type items. With this no need to register event handler for each list with same content type.

Binding Event Handlers to Content Type can be done by using SharePoint content type feature/elements xml.
Feature - XML
<?xml version="1.0" encoding="utf-8"?>
<Feature Scope="Web" 
  Title="Sample Event Handler Registration" 
  Id="A6B8687A-3200-4b01-AD76-09E8D163FB9A" 
  xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>
  </ElementManifests>
</Feature>
ConteType with Event Handler Binding - XML
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ContentType Name="ContentType Name"
   ID="ConteTypeGUID"
   Description="ContentType Description"
   Group="ContentType Group Name" >  
  <XmlDocuments>
    <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/events">
      <spe:Receivers xmlns:spe="http://schemas.microsoft.com/sharepoint/events">
        <Receiver>
          <Name>List Item Updated Event Receiver</Name>
          <Type>ItemUpdated</Type>
          <SequenceNumber>10001</SequenceNumber>
          <Assembly>Sample.Solution, Version=1.0.0.0, Culture=neutral, Public                    KeyToken=285bf69c25gca888</Assembly>
          <Class>Sample.Solution.ListItemUpdatedHandler</Class>
          <Data></Data>
          <Filter></Filter>
        </Receiver>          
      </spe:Receivers>
    </XmlDocument>
  </XmlDocuments>
 </ContentType> 
</Elements>
Hope this helps in reducing the development efforts and increases the efficiency.

No comments:

Post a Comment