SharePoint 2013/Online: Implement Client Caching for SharePoint Objects

Before started reading this article I would recommend that you should read my previous article SharePoint 2013/Online: Implement Client Caching for SharePoint Properties on Client Caching to get better understanding on topics like Caching Concepts, HTML5 Local Storage API and Modernizr.js.

In this demo we will discuss the caching mechanism for SharePoint Objects which are more complex in nature than the primitive data types.

I have selected “SharePoint List Items Collection” object for this demo since while working with SharePoint it is often that we need to query the SharePoint Lists using CSOM or REST API, which either ways returns a SharePoint List Items Collection Object that we can hold in the local cache and can boost Read/Write Operations in a more efficient manner.

So let’s starts with a new SharePoint App Project

  • Choose “App for SharePoint” Project Template

1

  • Specify SharePoint Site URL (On Premise or Online)
  • Select hosting model as “SharePoint-Hosted”

2Here I am using SharePoint Online Site to go with this demonstration

  • Enter SharePoint Online Account Credentials

3

  • Let Visual Studio configure the project for you

4

5

For the sake of this demo I have created a list called Products which has got few items added as shown below:

6

I have added HTML code to default.aspx page that will display following elements to the UI

  • Result Panel: This is a div that will display the output of the operations performed
  • Get List Button: This will retrieve the data from SharePoint and add it to the Cache
  • Clear Cache: This will clear the local cache whenever needed

7

  • Added little CSS to App.css to make UI elements more intuitive

8

With this our UI is a go.

Now let’s explore the code that that we have added to App.js

Step 1: Hooking up the event handlers to the click event for “Get List” & “Clear Cache” button

Step2: Verifying if the current browser supports the HTML5 Local Storage API

Step 3: Verifying if the current browser supports the HTML5 Local Storage API by utilizing Feature Detection capabilities of Modernizr.js Framework. For more details on Modernizr.js you can visit https://modernizr.com/

Step 4: This function first checks if Local Storage API is supported in the current browser and if it is supported then clear the specific key by specify the key name or all the keys from local cache by calling Clear() methods that you can see as commented in this function.

Step 5: This is the helper method that checks if current browser supports the HTML5 Local Storage API traditionally by querying JavaScript “window” object

9

Step 6: Same as Step 2 & 3

Step 7: Instantiate the local storage object

Step 8: Try to reading SharePoint Items Collection from Local Cache by specify Cache Key after converting it into string array

Step 9: If Items Collection is not present in Local Cache then we are calling getProductListItemsCollection(). This function will fetch the items from Products List and save it to the local cache for further use. We will see the implementation details of this function in Steps 12,13,14 & 15 down the line

Step 10: If the items collection is available in the local cache then it will be fetched from local cache based on the cache key

Step 11: Calling explodeJSONObject() which is a helper function that reads the item values out of the JSON Object that is passed as input parameter. We will see the implementation details of this function in Step 16.

10

Step 12: Getting Products List and query items using CAML Query

Step 13: Converting Lists Items Collection into a valid JSON Object by calling getJSONObject() method. We will see the implementation details of getJSONObject() method in Step 17 down below

Step 14: Once we received the valid JSON Object we can save it to Local Storage Cache by converting it back to String Array.

Step 15: Calling explodeJSONObject() which is a helper function that reads the item values out of the JSON Object that is passed as input parameter. We will see the implementation details in Step 16.

x

Step 16: explodeJSONObject() method takes JSON form of SharePoint List Items Collection and display it to the Result Panel by treating each row in the List Item Collection as Object with each column as its properties. Since we are fetching Item ID and Product Title Columns in the SharePoint List Items Collection so we can use it as [“RowObject”.ID] and [“RowObject”.Title] to display it in the result panel.

Step 17: getJSONObject() method takes SharePoint List Items Collection as input and transform it into JSON Object by reading values from List Items Collection

Step 18: getQueryStringParameter () is a helper method that helps you to extract Query String values based on the parameter name

12

With this we are done with the code.

Before we start execution we need to allow Read Permission to the App on Site Collection

  • Launch AppManifest.xml
  • Go to “Permissions” Tab
  • Select “Site Collection” from Scope Dropdown
  • Select “Read” from Permission Dropdown

13

Run the App

Enter the SharePoint Online Credential when prompted

14

Trust the App when prompted

15

When App lunches we can see the UI based on the HTML that we have added earlier to the default.aspx page

We can see Result Panel where we will see the results of the operations and “Get List”, “Clear Cache” buttons as well

16

First time when the “Get List” button clicked following tasks are being performed in a row:

  • Verify Products Items are not present in local cache
  • Products Items are then queried from SharePoint
  • List Items Collection is then saved to the local cache to serve any upcoming request for the same data
  • Display List Items in the Result Panel

17

Using Fiddler we can verify the request that is issued by App to SharePoint for getting Products List Items as shown below

18

Whenever “Get List” button clicked for the second time following tasks are being performed in a row:

  • Verify Products Items are present in local cache
  • Products Items are then fetched from local cache directly instead of sending request to SharePoint
  • Display List Items in the Result Panel

19

Using Fiddler we can verify that there is no request issued by App to SharePoint for getting Products List Items as shown below

20

This is it for this demo.

Hope you find it helpful.

 

Advertisements

SharePoint 2013/Online: Implement Client Caching for SharePoint Properties

SharePoint Pages are intended to act as data presentation layer to the end Users for the data stored in SharePoint List. In the rich interactive Client Centric Applications it is expected to have quick response to different User Actions like Read Data from or Save Data to SharePoint List.

Any delays due to read/write operations to SharePoint can negatively impact the User experience and could lead to denial of acceptance on developed features.

Using HTML5 Local Storage API, Web Applications can store data locally in user’s browser. Local Storage is more secure and large data can be stored without impacting overall Web Application Performance.

This new API allows large amount of data (approx. 5 MB) to be cached locally which is far larger than cookies which were commonly used for caching data.

Local Storage is maintained per domain & protocol (Origin of Request) and all Web Pages of same origin can use the same Cache.

In this article we will see HTML5 Local Storage API in action and utilize it to cache SharePoint Properties of primitive data type like String, Integer, Boolean and in one of the upcoming articles in the same series I will explain the caching of some of the complex SharePoint Objects.

Let’s kick start this demo with a new SharePoint App Project in Visual Studio 2013

  • Choose “App for SharePoint” Project Template

1

  • Specify SharePoint Site URL (On Premise or Online). Here I am using SharePoint Online Site to go with this demonstration
  • Select hosting model as “SharePoint-Hosted”

2

  • Enter SharePoint Online Account Credentials

3

  • Wait till Visual Studio configure the project for you

4

5

I have added HTML code to default.aspx page that will display following elements to the UI

  • Result Panel: This is a div that will display the output of the operations performed
  • Get Web Title: This HTML Button will retrieve the Title of the Host Web and add it to the Cache on click event
  • Clear Cache: This HTML Button will clear the local cache whenever needed on click event

6

  • Add little CSS to App.css to make UI elements more intuitive

7

With this our UI is a go.

Now let’s explore the code that that we have added to App.js

  • Step 1: Hooking up the event handlers to the click event for “Get Web Title” & “Clear Cache” button
  • Step2: This function first checks if Local Storage API is supported in the current browser and if it is supported then clear the specific key by specify the key name or all the keys from local cache by calling Clear() methods that you can see as commented in this function.
  • Step 3: This is the helper method that checks if current browser supports the HTML5 Local Storage API traditionally by querying JavaScript “window” object

8

  • Step 4: This method is a helper function that helps to retrieve Query String Parameters out of the requested URL

9

  • Step 5: Verifying if the current browser supports the HTML5 Local Storage API
  • Step 6: Verifying if the current browser supports the HTML5 Local Storage API by utilizing Feature Detection capabilities of Modernizr.js Framework. For more details on Modernizr.js you can visit https://modernizr.com/
  • Step 7: Instantiate the local storage object
  • Step 8: Reading Web Title value out of Local Storage Cache by specifying the key
  • Step 9: If the Web Title exists in the Local Cache then the value is retrieve out of it without any need of issuing call to SharePoint else we call another helper method “getWebTitle()” that will issue the request to SharePoint and get the Web Title, display it to result Panel and add the value to the Local Cache and make it available to server any subsequent request.

10

  • Step 10: In this method we are making CSOM call to SharePoint in usual way, once the call gets succeed the Web Title will get displayed in the Result Panel and also adding the value to local storage by calling setItem() method. This value will be available to serve from Cache in response to any future request for Web Title.

11

With this we are done with the code.

Before we start execution we need to allow Read Permission to the App on Site Collection

  • Launch AppManifest.xml
  • Go to “Permissions” Tab
  • Select “Site Collection” from Scope Dropdown
  • Select “Read” from Permission Dropdown

12

  • Run the App
  • Enter the SharePoint Online Credential when prompted

20.png

  •  Trust the App when prompted

14When App lunches we can see the UI based on the HTML we have added earlier to the default.aspx page

We can see Result Panel where we will see the results of the operations and “Get Web Title”, “Clear Cache” buttons as well

15Now when we click on “Get Web Title” button we can see two actions performed & logged in the Result Panel as follows-

  • Since the Web Title is not available in the Local Cache, it is retrieved from SharePoint and saved back to the local cache
  • Displaying Web Title in the Result Panel

16

If we investigate the Client – Server Request cycle using Fiddler we can see that there is actually a request issued to SharePoint and the response received from the server in form of requested data.

17

When we click “Get Web Title” button again we will see following two actions performed & logged in the Result Panel

  • Since the Web Title is available in the Local Cache this time , so no call has been issued to SharePoint for data and Web Title has been retrieved from the Local Cache
  • Displaying Web Title in the Result Panel retrieved out of Local Cache.

18

If we look into Fiddler again we can see that no request has been issued to SharePoint since we got the requested data available in Local Cache.

19

That’s it for this article.

In the upcoming article on Client Caching I will explain the caching scenarios related to bit more complex SharePoint Object like “SPListItemCollection” which is quite common return type when we query data from SharePoint Lists and deserve special attention as long as the caching is concerned.

Hope you find it helpful.

SharePoint 2013 : How to overcome List Threshold Limits using OData Continuation

While working with SharePoint Large List we all must have encountered the issues with restricted access to the list due to List Threshold Limits.

In this article we see the solution to this problem that can be implemented using OData Continuation in conjunction with REST API.

In order to demonstrate this solution I am making use of SharePoint Hosted App as in shown in below steps-

  • Create SharePoint App Project by choosing “App for SharePoint 2013” Project Template

1

  • Specify Host Web URL
  • Select SharePoint -Hosted as hosting model

2

Wait while Visual Studio configure the Project for you

3

In order to showcase the data access from a Large SharePoint List, I have added a list with 1 Lakh items in it and default Threshold limits are still intact

4

Now add some HTML for the UI in the Start Page of the App (default.aspx)

Step 1: Adding container for the HTML Button

Step 2: Adding HTML Button that will execute the code in action

5

So the final UI would look like as below-

6.1

Now add some JavaScript code in App.js File

Step 3: Bind the event handler with the HTML Button in “document.ready()” function

Step 4: Adding a helper function “getQueryStringParameter()” that will help us to extract the Query String Parameters

6

In the Callback function “oDataContinuations” we have following steps executing-

Step 5: Getting value of “SPHostUrl” by using “getQueryStringParameter()” helper function

Step 6: Getting value of “SPAppWebUrl” by using “getQueryStringParameter()” helper function

Step 7: Loading “SP.RequestExecutor.js ” JavaScript file as we need to issue a Cross Domain Call from SharePoint App to Host Web

Step 8: Prepare the URL to execute the Cross Domain Call to the Large List present in the Host Web

Step 9: Instantiate the object of Request Executor based on the App URL

Step 10: Calling “executeAsync” method of Request Executor Object

This function needs a JSON object with configuration values like

url: Specify the Url to execute Cross Domain Call

method: Specify the Request access method (GET or POST)

datatype: Specify the expected return type of the response (JSON)

headers: Specify the Request Headers

Step 11: On successful execution of this request, response object would return back with a property “__next” which contains the direct URL to the next set of records which can be queried from the list, check for this property and make sure it exists before proceed further

7.1

Step 12: Get the Url to the next result set

Step 13: Call the “getItems()” method recursively with the new Url returned by response object “__next” property

7

With this we are all done with the code.

But before we move any further we need to allow the permission for the App on Host Web since we need to query the data from the list which is hanging inside the Host Web.

Step 1: Go to App Manifest File => Permission Tab

Step 2: Specify Read permission

8

Build the Solution and Deploy it

9

Trust the App when asked for

10

Provide the credentials when asked for

11

Click on “Manage Threshold Limits”

12

See to the Result Panel and sure enough you will find records adding continuously based on the Paginated REST Calls driven by Odata Continuation

13

This is a simple demonstration to showcase how we can effectively make use of Paginated REST Calls driven by Odata Continuation to overcome issues related to List Threshold Limits.

Hope you find it helpful.

SharePoint 2013 : Batch Exception Handling

Batch Exception Handling in JSOM is a new concept in SharePoint 2013 that enables us to execute Try Catch and Finally code blocks in the same way as we do in Server Side Code i.e. executing with in the same Server Call.

For instance, while working with Server Side code if we need to create a new list then we need to first check its existence and if the list does not exists only then code will create it.

Point to notice here is this whole logic will gets executed in the same Server Call.

On the other hands if we try to perform the same action while working with JavaScript Client Object Model (JSOM) we need to issue two separate calls to the server, one is to check for the existence and other is to load or create the list.

Using new Batch Exception Handling constructs “startScope, startTry, startCatch, and startFinally we can achieve this in single JSOM Call to the Server.

In this article we will see the implementation details for Batch Exception Handling using SharePoint Hosted App.

  • Create a new project using “App for SharePoint 2013” Project Template

1

  • Specify the Host Web URL
  • Specify “SharePoint Hosted” as Hosting Model

2

  • Wait while Visual Studio configure Project for you

3

  • Prepare UI using HTML Elements decorated the desired CSS using Default.aspx (App Start Page)

Step 1: Specify the Page Title

Step 2: Add HTML to present the UI Elements for “Result Panel” and decorate the element with the required CSS of your choice

Step 3: Adding container to hold the button to execute Batch Exception Handling Process

Step 4: Add a HTML Button, specify its Label and decorate it with the required CSS

4

  • Write code to implement the logic for Batch Exception Handling by modifying App.js JavaScript File

Step 5: Bind the event handler with the Button using dynamic binding in “document. Ready” function

5

Inside the Event Handler function “batchExceptionHandling”

Step 6: Instantiate SharePoint Context and get the instance of the current web (all old school thing)

Step 7: Instantiate the Exception Handling Scope

Step 8: Start a Scope block by calling startScope() method

Step 9: Start a Try block by calling startTry() method

Step 10: Inside the Try Block, try to load the instance of the list in our case list is “My-Custom-List”

Step 11: Dispose the Try Block by calling dispose() method

Step 12: Start the Catch Block by calling startCatch() method

Note: This catch block will be executed only when action in try block gets failed, like in this case if we try to load “My-Custom-List” and it is not available in the SharePoint Site the operation will get failed and catch block gets executed.

Step 13: Since we get an exception while loading the list that means list is not available, so adding the new list with the same name

Step 14: Dispose the Catch Block by calling dispose() method

Step 15: Start the Finally Block by calling startFinally() method

Step 16: Load the list now, since by this time we will be having list available anyways (Created if not exists or loaded if exists)

Step 17: Dispose the Finally Block by calling dispose() method

Step 18: Dispose Scope Block by calling dispose() method

6

Step 19: In the success callback function check for the exception occurred during the function call by calling “get_hasException()” method, if the method returns True that means we had created the list else we already had a list that we have loaded.

7

With this step we are all done with the coding part and now the next step is to launch the app and see some action.

  • Build and deploy the solution

8

  • Enter the Credentials when asked for Authentication

9

After successfully authenticating the User, we can see the Start Page for the App

10

Open the SharePoint Manager and browse the App Web -> Lists and see if we got the list “My-Custom-List” created or not, in our case we do not have any such list created

11

Now click the Button “Batch Exception Handling” and see the Result Panel

First time when we click the button, JSOM code executes within the Exception Handling Scope, and see if the list is already available in the Site or not, if not it will be added by the code present in catch block as shown below

12

We can confirm the same in SharePoint Manager as well-

13

When we click the button afterwards the code in Try Block gets executed and successfully loads the list due to which in the Success Callback function “get_hasException()” function returns False and we get an alternative message in the Result Block as shown below –

14

I found this technique really effective when we have a scenario for implementing Fall Back mechanisms without involving multiple Server Calls for the same request.

Hope this simple implementation could help you to understand the concept of Batch Exception Handling.

SharePoint 2013 : How to enable Remote Event Receivers with existing List & Libraries

While working with Remote Event Receivers I came across a scenario where we need to hook up the Event Handlers to any of the existing lists in a site.

For example we got a list called “Products” in which we need to stop the users to delete any list item.

This requirement can be achieved simply by deploying a Farm Solution containing the Event Receiver SPI hooked up with the Products List Item Deleting Event.

But what if we are not allowed to deploy any code solution in SharePoint Environment?

The simple answer to this complex question is involve Remote Event Receivers and hooked them up to the existing list which is a bit of tricky task.

In this article we will see to the steps to register Remote Event Receivers with the existing Lists & Libraries while utilizing our knowledge based on earlier articles in this series which can be reached at:

  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
  4. SharePoint 2013 : Remote Event Receivers on List Item Event – Real Business Scenarios

Let start with a Provider Hosted App that will register the Remote Event Receivers with the existing SharePoint Lists

Create “New Project”

1

Select “App for SharePoint” as SharePoint Project Template

2

3

Specify the URL of the Debugging Site, which is called as Host Web in case of an App

Select “Provider-Hosted” as App Hosting Model

4

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

5

Enter Certificate Details as we did in earlier demos

6

7

On successful creation of the Solution two projects should be added as shown below.

“PH-Bind-Event-Receivers-With-Existing-List” – Represents the Code Base for the Provider Hosted App

“PH-Bind-Event-Receivers-With-Existing-ListWeb” – Represents the Code Base for the Remote Web

8

Select App Project and Press F4 to see the properties

Under “App for SharePoint Events” Set the Events that the App is required to respond to.

Here we would need only “App Installed” and “App Uninstalling” Event to work on so we would enable only these two events by changing the value to “True”

9

As soon as we enable the App Events a new service class gets added to the Solution by the name “AppEventReceiver.svc” under the Services Folder

10

Detailed walkthrough of the highlighted steps is as follows-

Step 1- Check for the Event Raised and make sure that we are handling only “AppInstalled” Event

Step 2- This step is tricky of all. It is important to notice how we are getting the full path of the Service Class that will be listening to the lists events.

Since this is the Service that will be hosted somewhere outside SharePoint due to this usual SharePoint Tokens will not work here which means “~remoteAppUrl” Url Token will not work in this case.

So in order to get the complete path to the Service Class we need to make use of “OperationContext” class.

The “OperationContext” class provides you methods (as highlighted below) to extract Absolute Uri to the Service Class irrespective of where it is hosted.

Step 3- Retrieve the Remote Web URL to get the fully qualified path of Service Class

Step 4- Instantiate the App Context by calling “CreateAppEventClientContext” method shipped with TokenHelper.cs Class to facilitates App Authentication Tokens

Step 5- Load the Products List using traditional CSOM way

Step 6- Instantiate new Event Receiver Object using “EventReceiverDefinitionCreationInformation” class. It is important to set following properties to get this Event Receiver added to the collection of Event Receivers of Product List.

Important Properties to set are-

EventType                          –             Specifies the type of Event that can trigger receiver like here we are assigning it to “Item Deleting” Even

ReceiverName                  –             Specifies the unique name of this Event Receiver that can be used to identify it in Event Receivers Collection of Products List

ReceiverUrl                        –             Specifies the full path to Receiver. Assign the value of the Full Path that we have retrieved in Step 2

SequenceNumber           –             Specifies the Sequence Number for the Event Receiver to add to the Event Receivers Collection of the Product List

Step 7 – Add the Event Receiver Object to Products List Event Receivers Collection

11

Step 8 – The other Event that we consider is “AppUninstalling”. Since this Event is quite useful to perform cleanup activities like removing the Event Receiver registration with the respective as soon as the App gets uninstalled.

Step 9 – Same as Step 4 above

Step 10 – Same as Step 5 above

Step 11- Loop through all the Event Receivers registered with Products List and find a specific Event Receiver by Name value (recall Step – 6 where we have specified value to “ReceiverName” Property of Event Receiver)

Step 12- Once we identified the specific Event Receiver we can remove it from Event Receivers Collection of Products List

12

Step 13- This involves Handling of ItemDeleting Event of Products List. We can check the incoming Event Type by using “EventType” property of Event Object (properties)

Step 14- Validates the name of the list that generates the Event, this step is necessary to ensure that we are responding to right Event generated from an intended list

Step 15- Set “ErrorMessage” that needs to be displayed to the User in case User actions try to delete List Items

Step 16- Set “Status” to “CancelWithError” since we want to cancel the User action along with showing him proper error message

13

That’s it. We are all set to see the efforts in action.

Build and Deploy Solution to SharePoint

Trust the App when asked to and move on

14

15

Once deployed successfully we can test the Remote Event Receiver as follows-

Navigate to the Products List

Try to Delete any Item in the list and see if you are able to see the Error Message you set with in Event Receiver’s Properties

16

17

Sure enough you will get the Error Message displayed on to Error Page to which SharePoint Navigates you to.

18

This implementation is really amazing and I can see lot of potential in terms of handling discrete Business Rule and Validation on the existing SharePoint Lists and Libraries without deploying and Server Code in SharePoint Domain.

Hope you find it helpful.

SharePoint 2013 References

SharePoint 2013 Installation

  1. SharePoint 2013 Developer’s Installation Guide – LinkTech
  2. SharePoint 2013 Deployment Guide

SharePoint 2013 Architecture & Governance

  1. Microsoft SharePoint 2013: Designing and Architecting Solutions
  2. Microsoft SharePoint 2013: Planning for Adoption and Governance

SharePoint 2013 Development

  1. Beginning SharePoint 2013 Development
  2. Professional SharePoint 2013 Development
  3. SharePoint 2013 For Dummies
  4. Exploring Microsoft SharePoint 2013
  5. Microsoft SharePoint 2013 Developer Reference
  6. Microsoft SharePoint 2013 Inside Out
  7. Inside Microsoft SharePoint 2013
  8. Exam Ref 70-332: Advanced Solutions of Microsoft SharePoint Server 2013
  9. Exam Ref 70-331: Core Solutions of Microsoft SharePoint Server 2013
  10. QuickBooks 2013: The Missing Manual
  11. Custom SharePoint Solutions with HTML and JavaScript
  12. Microsoft SQL Server 2014 Business Intelligence Development
  13. Professional Visual Studio 2013
  14. QuickBooks 2013: The Missing Manual

SharePoint 2013 App Development

  1. Pro SharePoint 2013 App Development
  2. Microsoft SharePoint 2013 App Development

SharePoint 2013 PowerShell

  1. Beginning PowerShell for SharePoint 2013

SharePoint 2013 Business Intelligence

  1. Business Intelligence in Microsoft SharePoint 2013
  2. Pro SharePoint 2013 Business Intelligence Solutions

SharePoint 2013 Branding

  1. Pro SharePoint 2013 Branding and Responsive Web Development
  2. SharePoint 2013 Branding and User Interface Design

SharePoint 2013 Administration

  1. Professional SharePoint 2013 Administration
  2. Pro SharePoint 2013 Administration, 2nd Edition
  3. Microsoft SharePoint 2013 Disaster Recovery Guide
  4. Microsoft SharePoint 2013 Administration Inside Out

SharePoint 2013 Enterprise Content Management

  1. SharePoint 2013 WCM Advanced Cookbook
  2. Practical SharePoint 2013 Enterprise Content Management

SharePoint 2013 User Guides

  1. SharePoint 2013 User’s Guide, 4th Edition

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.