TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Attach Event Receiver to SharePoint List using CSOM (Client Side Object Model)
Amar Gaikwad
Aug 05
2016
Code
7
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
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();
}
}
}
SharePoint
SharePoint 2013
CSOM
SharePoint Client Side Object Model
SharePoint Event Receivers
Event Receivers