If you worked with Sharepoint on-prem you probably know what are event receivers: custom handlers which you may subscribe on different types of events. They are available for different levels (web, list, etc). In this article we will talk about list event receivers.
In Sharepoint Online we can't use old event receivers because they should be installed as farm solutions which are not available in SPO. Instead we have to use remote event receivers. The concept is very similar but instead of class and assembly names we should provide end point url where SPO will send HTTP POST request when event will happen.
Let's see how it works on practice. For event receiver end point I will use Azure function and will run it locally. For debugging it I will use ngrok tunneling (btw ngrok is great service which makes developers life much easier. If you are not familiar with it yet I hardly suggest you to do that :) ). But let's go step by step.
First of all we need to implement our Azure function:
[FunctionName("ItemUpdated")] public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]HttpRequestMessage req, TraceWriter log) { log.Info("Start ItemUpdated.Run"); var request = req.Content.ReadAsStringAsync().Result; return req.CreateResponse(HttpStatusCode.OK); }
It doesn't do anything except reading body payload as string - we will examine it later. Then we run it locally - by default it will use http://localhost:7071/api/ItemUpdated url.
Next step is to create ngrok tunnel so we will get public https end point which can be used by SPO. It is done by the following command:
ngrok http -host-header=localhost 7071
After this command you should see something like that:
Now everything is ready for attaching remote event receiver to our list. It can be done by using Add-PnPEventReceiver cmdlet from PnP.Powershell. Note however that beforehand is it important to connect to target site with Connect-PnPOnline with UseWebLogin parameter:
Connect-PnPOnline -Url https://{tenant}.sharepoint.com/sites/{url} -UseWebLogin
Without UseWebLogin remote event receiver won't be triggered. Here is the issue on github which explains why: RemoteEventReceivers are not fired when added via PnP.Powershell.
When ngrok is running we need to copy forwarding url: those which uses https and looks like https://{randomId}.ngrok.io (see image above). We will use this url when will attach event receiver to target list:
Connect-PnPOnline -Url https://mytenant.sharepoint.com/sites/Test -UseWebLogin $list = Get-PnPList TestList Add-PnPEventReceiver -List $list.Id -Name TestEventReceiver -Url https://{...}.ngrok.io/api/ItemUpdated -EventReceiverType ItemUpdated -Synchronization Synchronous
Here I attached remote event receiver to TestList on site Test and subscribed it to ItemUpdated event. For end point I specified url of our Azure function using ngrok host. Also I created it as synchronous event receiver so it will be triggered immediately when item got updated in the target list. If everything went Ok you should see your event receiver attached to the target list using Sharepoint Online Client Browser:
Note that ReceiverUrl property will contain ngrok end point url which we passed to Add-PnPEventReceiver.
Now all pieces are set and we may test our remote event receiver: go to Test list and try to edit list item there. After saving changes event receiver should be triggered immediately. If you will check body payload you will see that it contains information about properties which have been changed and id of list item which we just modified:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <ProcessEvent xmlns="http://schemas.microsoft.com/sharepoint/remoteapp/"> <properties xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <AppEventProperties i:nil="true"/> <ContextToken/> <CorrelationId>c462dd9f-604a-2000-ea96-f4bacc80aa84</CorrelationId> <CultureLCID>1033</CultureLCID> <EntityInstanceEventProperties i:nil="true"/> <ErrorCode/> <ErrorMessage/> <EventType>ItemUpdated</EventType> <ItemEventProperties> <AfterProperties xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> <a:KeyValueOfstringanyType> <a:Key>TimesInUTC</a:Key> <a:Value i:type="b:string" xmlns:b="http://www.w3.org/2001/XMLSchema">TRUE</a:Value> </a:KeyValueOfstringanyType> <a:KeyValueOfstringanyType> <a:Key>Title</a:Key> <a:Value i:type="b:string" xmlns:b="http://www.w3.org/2001/XMLSchema">item01</a:Value> </a:KeyValueOfstringanyType> <a:KeyValueOfstringanyType> <a:Key>ContentTypeId</a:Key> <a:Value i:type="b:string" xmlns:b="http://www.w3.org/2001/XMLSchema">...</a:Value> </a:KeyValueOfstringanyType> </AfterProperties> <AfterUrl i:nil="true"/> <BeforeProperties xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/> <BeforeUrl/> <CurrentUserId>6</CurrentUserId> <ExternalNotificationMessage i:nil="true"/> <IsBackgroundSave>false</IsBackgroundSave> <ListId>96c8d1c1-de22-47bf-9f70-aeeefa349856</ListId> <ListItemId>1</ListItemId> <ListTitle>TestList</ListTitle> <UserDisplayName>...</UserDisplayName> <UserLoginName>...</UserLoginName> <Versionless>false</Versionless> <WebUrl>https://mytenant.sharepoint.com/sites/Test</WebUrl> </ItemEventProperties> <ListEventProperties i:nil="true"/> <SecurityEventProperties i:nil="true"/> <UICultureLCID>1033</UICultureLCID> <WebEventProperties i:nil="true"/> </properties> </ProcessEvent> </s:Body> </s:Envelope>
This technique allows to use Azure function as remote event receiver and debug it locally. Hope it will help someone.
Update 2021-11-22: see also one strange problem about using of remote event receivers in SPO sites: Strange problem with remote event receivers not firing in Sharepoint Online sites which urls/titles ends with digits.