Search This Blog

Sunday, December 11, 2016

Attach Event Receiver to SharePoint List using CSOM (Client Side Object Model)

using Microsoft.SharePoint.Client;
using System;
using System.Net;
 
private static void AttachEventReceiver()
{
            var userName = "<<UserNameWithoutDomainName>>";
            var password = "<<Password>>";
            string domain = "<<DomainName>>";
            string webUrl = "<<WebUrl>>";
 
            using (var context = new ClientContext(webUrl))
            {
                context.Credentials = new NetworkCredential(userName, password, domain);
                var list = context.Web.Lists.GetByTitle("<<ListName>>");
                var eventReceivers = list.EventReceivers;
                context.Load(eventReceivers);
                context.ExecuteQuery();
 
                EventReceiverType eventType = EventReceiverType.ItemUpdated;    //event type (ItemAdded / ItemUpdated)
                string receiverAssembly = "<<FullyQualifiedAssemblyName>>";     //Example: <<AssemblyName>>, Version=<<AssemblyVersion>>, Culture=neutral, PublicKeyToken=<<PublicKeyToken>>
                string receiverClass = "<<ReceiverClassNameStartingWithNamespaceName>>";    //Example: <<NamespaceName>>.<<ClassName>>
                string receiverName = "<<ReceiverName>>";       //you can give any name
 
                bool isEventReceiverAlreadyAssociated = false;
                foreach (var eventReceiver in eventReceivers)
                {
                    if (eventReceiver.EventType == eventType
                            && string.Compare(eventReceiver.ReceiverAssembly, receiverAssembly, StringComparison.OrdinalIgnoreCase) == 0
                            && string.Compare(eventReceiver.ReceiverClass, receiverClass, StringComparison.OrdinalIgnoreCase) == 0
                            && string.Compare(eventReceiver.ReceiverName, receiverName, StringComparison.OrdinalIgnoreCase) == 0
                        )
                    {
                        isEventReceiverAlreadyAssociated = true;
                    }
                }
 
                if (!isEventReceiverAlreadyAssociated)
                {
                    EventReceiverDefinitionCreationInformation eventReceiver
                                       = new EventReceiverDefinitionCreationInformation
                                         {
                                               EventType = eventType,
                                               ReceiverAssembly = receiverAssembly,
                                               ReceiverClass = receiverClass,
                                               ReceiverName = receiverName,
                                          };
 
                    list.EventReceivers.Add(eventReceiver);
                    context.ExecuteQuery();
                }
            }
 }  

No comments:

Post a Comment