SharePoint 2013 : Remote Event Receivers on List Item Event – Real Business Scenarios

In this fourth article in the series on Remote Event Receivers, we will look into some of the applicable business cases around the Remote Event Handlers.

You can reach the previous three articles in this series as follows:

  1. SharePoint 2013: Remote Event Receivers
  2. SharePoint 2013: How to develop Remote Event Receivers for App Events
  3. SharePoint 2013: How to develop Remote Event Receivers for List And List Item Events

We will investigate the working of the following scenarios which are quite obvious while working with SharePoint List & List Items.

Scenario 1 – How to restrict users to delete a certain item

In order to show case this scenario let’s consider an Item “Product-001-1” added to the List called “Products” as shown below:

Now let’s try to delete this item as highlighted below-

1

2

As soon as user try to delete the item SharePoint looks for any registered Event Receiver with the List and looking for its Receiver Definition to see what all event this Receiver is allowed to receive and executes it.

In our case we have registered the following Receiver Definition with the list-

3

Let’s investigate the code for register Remote Event Handler –

Since this a Before Event (as explained in one of the earlier post “SharePoint 2013: Remote Event Receivers”), we need to write the Code in “ProcessEvent” Method.

Step 1 is to check the type of Event that triggers this Event Receiver by making use of “SPRemoteEventType” Enum and “EventType” Property of the “SPRemoteEventProperties” object

Step 2 is to check the List Title by making use of “ItemEventProperties” collection of “SPRemoteEventProperties” object and ensure that we are handling Delete Events received only from a specific which in our case is “Products”

Step 3 is to check for the desired condition and if satisfied then set “ErrorMessage” and “Status” properties exposed by “SPRemoteEventResult” object.

In this case we have set a user friendly message and set status to “CancelWithError”. For all the valid status values we can look for “SPRemoteEventServiceStatus” Enum.

Step 4 is to return the SPRemoteEventResult object back to SharePoint

4

The setting we did in Step 3 will let SharePoint to terminate the event raised due user action and return the error message to SharePoint which would be rendered as Error Message for the user as highlighted below-

5

Scenario 2 – How to get Item Details after Item has been updated

In order to show case this scenario we can consider the same item as above and this time let’s let Edit the item as highlighted below

6

7

Now next thing is to investigate the code for registered Remote Event Handler –

Since this an After Event (as explained in one of the earlier post “SharePoint 2013: Remote Event Receivers”), we need to write the Code in “ProcessOneWayEvent” Method.

Step 1 & Step 2 are same as mentioned above

Step 3 is to fetch the Items Properties by making use of “ItemEventProperties” collection and preparing a variable to make it use later

It is worth noting that at this point, “ItemEventProperties” collection will contain the Properties of the List Item after the Update got succeed, which means that we can find all the updated values in the respective columns for the list item as highlighted and can consume as needed

Just to keep the story simple we are consuming these values in compiling a message to be written to Windows Event Log.

It is important to notice how we are accessing values of “Title” & “Price” Columns of that Item.

Step 4 is to write this message variable to Windows Event Log

8

Once execution is successful we can see the message logged in the Windows Event Log as shown below

9

Scenario 3 – How to validate User inputs using Remote Event Receivers

This scenario will talk on validating user inputs and terminate the execution as soon as the input value falls outside the valid value range.

For instance in this demo we are assuming a hypothetical business requirement demanding “Item Price should not exceed $300”

In order to showcase this validation scenario we can consider the same Item as mentioned above.

Let’s edit the item as shown below

10

Now specify the Item Price any greater than $300, here we are updating the Product Price as $350

As soon as we try to save the item, SharePoint handover the control to Remote Event Receiver which is registered with this list on Item Updating Event and Event Receiver validate the Item Price value against the specified business logic which on fail produces the error message “Price cannot exceed $300” as highlighted below-

11

If we look into the logic driving this business requirement we can see

Step 1 is to write the code in “ProcessEvent” handler as this action of updating the List Item is a Before Event [ItemUpdating]

Step 2 is to identify the Event Type and ensure that the business logic should be executed only in case of ItemUpdating event

Step 3 is to identify the Source of Event and ensure to handle the event only if the Source is “Product” List

Step 4 is to read the value of “Price” Field entered by the user

Step 5 is to validate the input Price value against the needed business logic

Step 6 is to set the “ErrorMessage” and “Status” Properties of the SPRemoteEventResult object. Set “Price cannot exceed $300” as Error Message and “CancelWithError” as Status. These properties let SharePoint to terminate the Event generated and no updates to the Item will get persisted.

Finally Step 7 is to capture information about the Item and Event and write it back to Windows Event Log.

12

These few simple scenarios might help you to understand the mechanics and objects exposed by Remote Event Receiver API that can be extended to achieve even more complex business scenarios at hand.

Hope you find it helpful… 🙂

Advertisements

SharePoint 2013: How to develop Remote Event Receivers for List And List Item Events

In this third post on Remote Event Receivers we are going to explore the mechanics revolving around Remote Event Receivers on List/List Item Events.

The previous two posts in this series can be reached out at:

  1. SharePoint 2013: Remote Event Receivers
  2. SharePoint 2013: How to develop Remote Event Receivers for App Events

In order to show case this scenario we need to start with a Provider Hosted App as highlighted in the following steps:

  • Select “App for SharePoint” Project Template

1

  • Specify the URL of Host Web and select “Provider-Hosted” as Hosting Model.

2

  • Select “ASP.Net Web Forms Application” as Project Template for Hosting the Remote Web

3

  • Specify the Security Certificate details based on SharePoint Provider Hosted App Development Environment configuration

4

Click Finish to complete the Visual Studio Solution Wizard.

Now next thing is to add the required items to the SharePoint App Project

  • Select App Project => New Item => Add

5

  • Select “List” as Project Item Template and the list as “Products”

This List will act as the Source of Events which will be delegated to the Remote Event Receiver

6

On List Settings Page –

  • Select a Display Name for the List
  • Choose Template for List Instance as “Custom List”

7

In List Designer –

  • On Columns Tab, specify the Columns/Fields you need to add to the list

I took ProductName & Price as two fields to be added for Products List

8

  • On the List Tab, verify the Site Relative Url of List

9

Once we got our list created and configured, it is time to add a new SharePoint Item to the project. Guess What??

The Remote Event Receiver. Yes!!!!

  • Select App Project => New Item => Add

10

  • Select “Remote Event Receiver” as Project Item Template

11

  • Select Type of Event Receiver as “List Item Events”

12

  • Select Event Source as “Products” List
  • Choose what all events you want to let handle by this Remote Event Receiver. For now I am choosing “Item Added”, “Item Updated” and “Item Deleted” events

13

As soon as the List is added to the Project a Feature scoped to the App Web gets also added

Once we are done with the configuration steps as shown above, we can see following artifacts added to the Project as highlighted below:

  • Products List
  • List Instance of the Products List
  • Remote Event Receiver

14

If we notice Remote Web Project which is nothing but an ASP.Net Application, we can see the following artifacts added already to it:

  • Service Class [Product-Remote-Event-Receiver]: That represent the Remote Event Handler Code Base
  • TokenHelper.cs & SharePointContext.cs : These helper classes are added to VS2013 to execute all the heavy lifting related to Authorization and Authentication algorithms easily between Remote Web Server(SPWeb Host) & SharePoint Server(Front-end Server).

15

We will revisit the Service Class Code in a short while to understand its internal plumbing.

But for now let’s build the Solution and Run it.

16

Trust the App with all needed permissions when prompted.

17

As soon as we Grant the App with all of the required permissions, the App Launcher redirects the User to the Start Page for the App, which is residing in the Remote Web for this case as highlighted below

18

We can see the App Launcher added to the Site Contents of the Host Web as shown below

19

We can ensure the presence of App Web by using SharePoint Manager and inspects Products List that has been provisioned to the App Web during the App Deployment

20

We can browse the App Web from Browser also as shown below

21

Now in order to test the Event Receiver, let’s create a test item in Products List as shown below

22

Specify Product Name & Price and Click Save button

23

As soon as Item gets added, it triggers “ItemAdded” event which is delegated to Remote Event Receiver by SharePoint.

In Remote Event Receiver we have two methods “ProcessEvent” & “ProcessOneWayEvent”.

For more details on these methods you can revisit my earlier post SharePoint 2013: Remote Event Receivers

On Item added we can see Breakpoint hit in “ProcessEvent” Method as shown below

24

Similarly we can see Break Point hit every time the Item gets updated as highlighted in below steps

25

26

27

Likewise we can see Break Point hit when Item gets deleted as highlighted in below steps

28

29

Since we registered the Event Receivers to handle “ItemAdded”, “ItemUpdated”, “ItemDeleted” only so none of the other Events would be delegated to Remote Event Receiver by SharePoint.

In case if any more Events need to be handled we need to add <Receiver> Elements in the Element.xml file associated with Remote Event Receiver as and when needed.

SPRemoteEventProperties Object is your real friend:

“ProcessEvent” method of Remote Event Receiver provides an object called as “properties” that exposes a lot of useful properties that can help us to perform any desired operation on the Web or List or List Item.

Following are the important properties that are exposed by “properties” object:

  • Event Type: Returns the type of Event Triggered by SharePoint Source Object
  • Item Event Properties: If the Event Type is of “List Item Type”, then “ItemEventProperties” collection is returned with data entered by user in each field of the List Item
  • List Properties: Returns the List specific properties like List Name, List ID and so on
  • Login User Properties: Return User specific properties like User ID, Login Name and so on
  • Source Web Properties: Return Web specific properties like Web Url

30

This post is more focused on the mechanics offered by SharePoint around Remote Event Receivers for List/List Item Events.

We will meet in another post where it will be more focused on to the implementation details on Event Receivers dancing around some valid Business Use Cases.

Hope you find this post helpful.

SharePoint 2013: How to develop Remote Event Receivers for App Events

In this second post on Remote Event Receivers we are going to explore the implementation details of “Remote Event Handlers for App Events”.

In case you need to recall the concepts related to “Remote Event Receivers”, you can refer to my First post in this series SharePoint 2013: Remote Event Receivers

In order to show case the implementation details of Remote Event Handler for App Events, let’s start with creating a Provider Hosted App by using following steps:

Create New Project in Visual Studio using “App for SharePoint” Project template

1

Specify Host Web URL and choose “Provider-hosted” as App Type

2

Choose “ASP.Net Web Forms Application” as Project Template to create Remote Web for our Provider Hosted App

3

Specify Certification Details based on the configuration of Provider-Hosted App Development Environment. Following details needs to be provided:

  • Certificate Location
  • Password
  • Issuer ID

4

Once all the above steps executed successfully we will get a new Solution created with two projects:

  • PH-AppEventLifeCycle which is a Provider Hosted App
  • PH-AppEventLifeCycleWeb which is a Remote Web for App

5

Select Provider Hosted App Project and press F4 to see the Project Properties. In the Project Properties look for “App for SharePoint Events” section and enable all events that you want to get handled by Remote Event Receiver.

Here I have set all the three events “Handle App Installed”, “Handle App Uninstalling, “Handle App Upgraded” to True, this setting will allow SharePoint to delegate respective events to the registered Event Receiver.

6

In case you need to create an App Web for your Provider Hosted Web (though it is not necessary) you must have atleast one Web Scoped Artifact added in the Project as this action will force SharePoint App Framework to provision App Web during the App Deployment.

In this case I have added a Dummy Module deploying some sample file just to force SharePoint to create an App Web for our Provider Hosted App.

7

It is noteworthy to look for AppManifest.xml file as most of the configuration settings for an App are derived from here only.

In General Tab, we have two noteworthy Properties:

  • Start Page: It allows you to set any Page as App Start Page. In this case we have set it point to the Default.aspx Page in Remote Web.
  • Query String : Allows adding additional information as Query String Parameters while redirecting to the Start Page

8

In Permission Tab, we can specify the set of Permissions that App will need to perform desired tasks.

At the time of App Installation, App will request this permission set to be granted and that we will see few steps down the line.

9

Now the very next thing is to investigate the constitution of Remote Web Project “PH-AppEventLifeCycleWeb

10

In this Project we have following important Files to look for:

  • Default.aspx: This is the start page for Provided Hosted App as we set it in earlier steps. In this page we can perform actions that are desired for a specific task. For example we can provide UI for end users to interact with the App.

In this demo the code sample is reading the title of the Hosting Web as follows:

           Steps 1: Getting URL of the Host Web by reading “SPHostUrl” Parameter

           Steps 2: Instantiating Client Context by Calling GetS2SClientContextWithWindowsIdentity method provided by SharePoint Infrastructure by means of TokenHelper.cs Class

           Step 3: Once Client Context is Instantiated, we can make use of Managed CSOM to load the Web and read its Title Property as shown below

11

  • Scripts: We can go with the default set of scripts added during creation of the project, else we can add any desired script file to it

12

  • AppEventReceiver.svc : This Service class has been added to the Project as soon as you add a “Remote Event Receiver” Project Item to the Project

13

Let’s walkthrough through the code file and see what we got.

Step 1: Add “Microsoft.SharePoint.Client.EventReceivers” Namespace which is needed for Remote Service to handle Remote Events and inherit the class from “IRemoteEventService”

Step 2: Override the method ProcessEvent

Step 3: Specify Remote Event Service Status if you want to continue or reject, so that execution succeed or revert back

Step 4: Perform actions as per the business requirement. Here I am adding logs to Windows Event Log

Step 5: Return the Event Result back to SharePoint

14

Step 1: Override the method ProcessOneWayEvent

Step 2: Perform actions as per the business requirement. Here I am adding logs to Windows Event Log

15

  • Web.config: In Web.config file, there are a couple of “AppSettings” that are important to take note of-

              ClientId: Generated Automatically by Visual Studio for development perspective. At the time of App registration this can be regenerated and used accordingly.

              ClientSigningCertificatePath: Specify the path of Client Certificate exported during environment configuration.

              ClientSigningCertificatePassword: Specify the path of Client Certificate Password specified to protect the Certificate during environment configuration.

               IssuerId: Specify the path of Issuer ID generated during environment configuration

16

With this we are done with inspection to all of the important files in our solution.

Now it is time to Build the Solution and Run it.

In the below screen shot we can see the Client ID is generated by Visual Studio Tools during Build Process.

17

Once the Solution Build & Run successfully, the App Framework looks for the AppManifest.xml and find a permission set to be granted by App User on the Host Web.

So we have to grant permissions as specified in Permissions Tab of AppManifest.xml file and in order to grant the permissions click “Trust It”.

18

As soon as we grant the permissions, App Launcher looks for the App Start Page as specified in General Tab of AppManifest.xml file and Redirect the user to that page.

If we notice the URL in below screen shot, we find the App Start Page is default.aspx of Remote Web as specified in AppManifest.xml file for the App.

19

If we investigate the Site Structure using any tool like SharePoint Manager (one of my favorites), we can see an App Web by the name “PH-AppEventLifeCycle” is also provisioned due to the presence of Dummy Module we added to the Project earlier.

20

After App is getting installed successfully, we can also see an event log is added to the Windows Application Log as shown below based on the message we placed in the “AppEventReceiver.svc” code file:

21

Likewise while the App is uninstalling, we can see an event log is added to the Windows Application Log as shown below based on the message we placed in the “AppEventReceiver.svc” code file:

22

This simple walkthrough can help you to understand on how to deal with the App Events.

We can utilize these semantics under different business cases liking registering Event Receivers for existing lists or notifying users and so on.

Hope you find it helpful.

See you all in the next post of this series. 🙂

SharePoint 2013: Remote Event Receivers

In this first article on “Remote Event Receivers”, we will understand the concept of “Remote Events” & “Remote Event Handlers” which is a newly introduced concept in SharePoint 2013.

What are Remote Events & Remote Event Receivers?

Remote Events are meant to be considered in context of SharePoint Apps only, since the newly introduced SharePoint Apps Model has got restrictions on how the code should be executed in SharePoint Environment.

SharePoint Apps Model restricts the Apps to execute any server side code within SharePoint execution boundaries. But there are scenarios where it becomes really necessary to handle certain Events during the App Life Cycle.

For instance this is an obvious scenario to perform any desired operation like “creating a Global Settings List in Host Web” during App Installation, similarly it is also a valid scenarios where an Email notification needs to send to the App Users with some of the relevant information regarding the app or taking backup of the App Data or Settings on to the Host Web before actually removing the App during App Uninstallation.

Due to such valid business cases, it is necessary to have a mechanism to handle such events from within the Apps and that’s where Remote Event Handler comes into play.

There are broadly two types of Remote Events most likely to be triggered out of an App:

  1. App Events
    • Handle App Installed
    • Handle App Uninstalling
    • Handle App Upgraded

1

  1. List Events : All list events are supported which are kept within SPRemoteEventType enumeration
    • ItemAdding
    • ItemUpdating
    • ItemDeleting
    • ItemCheckingIn
    • ItemCheckingOut
    • ItemUncheckingOut
    • ItemAttachmentAdding

2

The listed events are just a few out of the complete list of Events that are exposed as Remote Events.

For the complete list of Remote Events you can visit SPRemoteEventType Enumeration.

In order to handle all of the above listed Events SharePoint provides following two Handler functions via an Interface “IRemoteEventService”:

3

  1. ProcessEvent: This is “Before or Synchronous” Handler, which executes before any action (like List Item Added/Updated/Deleted) takes place. This is a Two-Way Event Receivers which means it takes instructions from SharePoint based on User Actions (List Items Added/Deleted), Process it and returns back the result to SharePoint. This function has a return type of type “SPRemoteEventResult”.

4

  1. ProcessOneWayEvent: This is “After or Asynchronous” Handler, which executes after any action (like List Item Added/Updated/Deleted) completed. This is not a Two-Way Handler so it will just accept the instructions from SharePoint based on User Actions (List Items Added/Deleted) and does not returns back any result or notification to SharePoint. This function should be mainly employed for operations like Logging, Sending Notifications to App Users and so on.

5

How do Remote Event Receiver Works:

Step1: User Performs Operations that generates an event in SharePoint [Be it App or List Events]

Step2: SharePoint then look for registered Web Service Endpoint designated to handle this event remotely

Step3: Web Service Endpoint process the instructions based on the Event generated from within SharePoint and returns the result back to SharePoint.

In order to perform any action directly from within the Web Service, Web Service Endpoint needs to call Access Control Service to obtain its own signed token.

6

SharePoint provides the TokenHelper.cs Class file which can be used to make request for necessary tokens.

7

That is all for this post on Remote Even Receivers.

Hope you will find it helpful.

In the upcoming articles on Remote Event Receivers we will explore the implementation details and see each of the types of Events Receivers in action.

So sit tight and stay tuned. 🙂