SharePoint 2013/Online: JavaScript Injection using Embed JavaScript Pattern

Based on the latest recommendations from Microsoft, User Interface SharePoint 2013 & SharePoint Online should be customized using Client Side Frameworks and not using Traditional Master Page Customization based on Branding Solutions.

Moving on the same recommendations we will discuss JavaScript Injection or Embed JavaScript Pattern which is one of the newly recommended techniques from Microsoft that enables the developers to write applications to push the client scripts into the page from outside SharePoint Environment.

This sounds similar to the implementation of the Delegate Controls in an on premise SharePoint Installation but in this case we push the scripts from outside of the SharePoint Environment.

Using Client Side Frameworks such as JQuery along with this technique we can perform DOM Manipulation (adding, removing, modifying HTML Elements) as and when needed in whichever ways.

We must make use of Custom Actions with SharePoint App Model in order to implement Embed JavaScript Pattern by utilizing location identifier ScriptLink that can be accessed through UserCustomActions collection of SPWeb Object.

In this in this article we will see how to implement Embed JavaScript Pattern in real time business applications as below-

Lets’ start with a SharePoint App Project by selecting App for SharePoint Project Template

1

Specify the Site URL

Choose Provider-Hosted as hosting model in order to develop High Trust Apps

2

Choose ASP.Net Web Forms Application to create Web Application Project for the Provider Hosted App

3

Provide Certificate details for the High Trust Apps

4

Now once the project is ready we can start with the coding part of Solution as follows-

Steps 1 – In the default.aspx add HTML code to provide UI for the solution

5

In the App.js file add the following code-

Steps 2 – Refer the JQuery File from the CDN

Steps 3 – Calling InjectJavaScript Function

6

Steps 4 – Inside InjectJavaScript Function, check if MDS is enabled and if it is Register Custom JavaScript code using RegisterModuleInit function.

The first parameter to the RegisterModuleInit function is the path to the JavaScript file relative to the _layouts folder.  Since this solution deploys the JavaScript file into a folder under the _layouts virtual directory, you have provided that relative path.  The second parameter is the entry point function which is LoadJSInsideHostWeb.

This approach will ensure that this JavaScript will work both with MDS enabled & disabled sites.

7

Steps 5 – Inside LoadJSInsideHostWeb function, we are calling LoadJQuery function to include JQuery file from the CDN and once loaded successfully it is calling ModifyHostWeb which will do the actual job of Injecting JavaScript Code to the Host Web

8

Steps 6 – Inside ModifyHostWeb function

  • We are manipulating the Site Title of the Host Web by using JQuery Element Identifier
  • We are replacing the Site Icon of the Host Web by using JQuery Element Identifier

9

Steps 7 – Inside LoadJQuery function we are loading JQuery File from the CDN

10

Steps 8 – Here we are hooking up the button click event for InjectJs & RemoveJS HTML buttons

Inside each event handler we are calling InjectJavaScript & RemoveJavaScript functions by passing Client Context to the Host Web & Web Object referring the Host Web and setting the notification message on the SharePoint App Page (default.aspx) to show the status of the operation

11

Steps 9 – Inside InjectJavaScript function we are making use of Custom Actions Framework for SharePoint to inject JavaScript based customization inside the Host Web in the following steps-

12.1

Preparing path of the Script file that we are going to inject into the Host Web and embedding it by creating the dynamic script block with src attribute set to the script file path.

Then we are retrieving the UserCustomActions collection in context of the Host Web and adding the new User Custom Action with Location as Script Link and Script Block as dynamic script block created earlier

 

13

Steps 10 – Inside RemoveJavaScript Function we are removing the User Custom Action from the UserCustomActions collection in context of the Host Web based on the Description & Location property of the User Custom Action.

14

With this we are done with the code.

Now lets’ run the App and see it in action by pressing F5 in Visual Studio

Once the App launched we can see the UI with a Result Panel & two HTML Buttons

  • Inject JavaScript to Host Web – This button will Inject JavaScript to the Host Web using User Custom Action
  • Remove JavaScript to Host Web – This button will Remove JavaScript from the Host Web by removing User Custom Action

15

If we look the Host Web before embedding the script to it, it would look like as follows. Notice we have default Site Icon and Title which was provided at the time of site creation

16

Now on App Page click on Inject JavaScript to Host Web button to push custom JavaScript into the Host Web

On clicking the button we can see the success message in the Result Panel confirming that the JavaScript has been applied to the Host Web

17

If we revisit the Host Web we can see the Site Icon and Title has been changed as per the code we had added to the custom JavaScript File that we have injected into Host Web

And since this change takes place at the Master Page Level, we can see the effect of the change all across the site on every screen as shown below:

18

19

20

 

Now in order to unplug the JavaScript based customizations out of the Host Web we can click on Remove JavaScript to Host Web

Once the Remove operation has been completed successfully we can see the result panel confirming the success of the operation.

21

And we can go back to Host Web to ensure that the Site Icon and Original Title are restored back as usual.

22

So we can clearly see the “Embed JavaScript Pattern” is very effective as it gives you handle on customizing Host Web Elements from outside the SharePoint itself.

Point of Caution

It is the responsibility of the App Developer to handler the smooth removal of the injected code as soon as the App gets uninstalled. There are a couple of issues that I would like to point out around this fact as follows:

If code is injected using SharePoint Hosted App, then it is not possible to get it removed the injected code automatically by any mean. In this case it is required to provide a User Interface or any other mean to execute the code for removal of injected Javascript followed by User Training for the Administrators to run the code first before uninstalling the App.

If code is injected using Provider Hosted App, then it is possible to get it removed automatically by handling App Uninstalling Event using Remote Event Receivers. You can refer to following of my earlier blogs on Remote Event Receivers to get better understanding on usage

That’s all for this demo.

Hope you find it helpful.

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.

 

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 : Working with Chrome Control and Cross Domain Execution in Provider Hosted App

In the new SharePoint 2013 App model, the Apps can be hosted in one of the following hosting model: SharePoint Hosted (with in SharePoint Domain), Provided Hosted and Auto Hosted (Outside SharePoint Domain).

One of the biggest issue that we can see with Apps running outside SharePoint Domain is Branding, since these Apps has got separate Home or Landing Pages than SharePoint and does not follow Visual Paradigms like Navigation Menus, Back Link to Home Page and so on similar to SharePoint.

Intranet Users can feel disconnected with the App due to this huge gap in UI Experience.

In order to overcome this obvious issue SharePoint allows to import a very basic version of SharePoint 2013 Chrome into their Apps without apply the Custom CSS Styles manually by means of a Client Side Rendering Control called “Chrome Control”.

The functional implementation details of this control reside in “SP.UI.Controls.js” file located in the new “/_layouts/15” virtual directory or “Layouts” Folder in 15 Hive.

Hope up to this point you grasp a fair understanding in Chrome Control and now it is time to move on to see it in action.

In order to demonstrate this implementation of Chrome Control we will start with a Provider Hosted App as show in below steps:

Create a new SharePoint App Project by selecting “App for SharePoint” project template

1

Choose Hosting Model as “Provider-Hosted”

2

Choose “ASP.Net Web Forms Application” as template for provisioning the Remote Site

3

Specify the Certificate location, decrypting password and Issuer ID (This ID was generated while we configure the S2S Trust for Provider Hosted Apps)

4

Once the Project has been added to the solution it would look like as below:

5

I have added a dummy feature to force SharePoint to create an App Web for this App, though this is purely optional.

6

We can review the App Web using any SharePoint Object Browser, here I am using SharePoint Manager to lookout the same

7

Also notice that we have changed the Start Page for App to “ChromeCrossDomain.aspx” as highlighted below-

8

Allowing Read permission for the App in Site Collection Hosting it in AppManifest.xml

9

Also in the Remote Web Project we have Pages Folder which is containing pages for our App.

10

We have “ChromeCrossDomain.aspx” page residing inside this folder which will serve as Start Page for this App

11

Similarly we have Scripts folder which is holding all JavaScript Files in use by this App as shown below

Apart from standard JavaScript Files supporting JQuery, we also have two App specific custom JavaScript Files “ChromeLoader.js” & “CrossDomainExecutor.js” which is implementing the core of Chrome Control for this App

12

In the Start Page HTML –

Firstly we have to add the “Script” Tags to include custom Javascript Files

Then we need to add a “Div” Tag with id = “chrome_ctrl_container” (you can use any unique value as ID) at the top level as shown highlighted

13

Now if we explore the code in one of the Custom JS file “ChromeLoader.js”, we can see it as

Step 1 – “getParameterByName” is a helper function that can be utilized to read Query String Parameters from the incoming request

Step 2- Read the “SPHostUrl” Query String Parameter to get the handle on Host Web

Step 3- Load “SP.UI.Controls.js” file in context of Host Web and once loaded call “renderChrome” method

Step 4- Inside “renderChrome” method, we are preparing Object holding the Chrome Configuration Options

appIconUrl                –      Icon URL that we need to show at the top header of the App

appTitle                     –      Header Title for the App

appHelpPageUrl       –      Help Page Url for the App

settingsLinks            –      Links to be shown under settings menu

Step 5- “SP.UI.Controls.Navigation” method is used to load the Chrome Control inside the div with Id = “chrome_ctrl_container” along with settings applied based on the “options” object we created in Step 4

Step 6- Visible the Chrome Control and let the SharePoint UX rendering takes precedence over the App defaults

14

This is it for loading the Chrome Control in our custom App.

Now let see how we can enable Cross Domain Execution for this App.

If we investigate the other custom JS File “CrossDomainExecutor.js” we can notice the execution as follows-

Step 1- Getting “SPHostUrl” and “SPAppWebUrl” Query String Parameters using “getParameterByName” method as before. “SPHostUrl” provides the Url of Host Web where the App has been installed while “SPAppWebUrl” provided the Url of App Web which we got created during the App Installation (by means of Dummy Feature).

Step 2- Getting the reference of “SP.RequestExecutor.js” JS file in context of Host Web as earlier. “SP.RequestExecutor.js” is used to execute Cross Domain Calls to SharePoint i.e. the Call from SharePoint App (Domain 1) to SharePoint (Domain 2).

Step 3, 4, 5- Instantiating the context of App Web and instantiating the object of AppContextSite to get the handle on Host Web object. Once it is done rest of the things are simply applying JSOM operations

Step 6- Query Announcements List in Host Web and interface its records in the App Start Page

15

Before moving forward let’s have a look into the Announcements List to see what all items we have for query on App Start Page

16

We can see there are two items available to be displayed with in the App Start Page.

Build the Solution and deploy it

Trust the Security Certificate and move on

17

Trust the App when asked to and move on

18

Provide Credentials for Authentication

19

And we are all set with final outcome which can we analyzed as below:

Step 1- Showing the App URL ensuring we are looking at the Start Page of the App

Step 2- Showing App Site Header Image and Title fetched by Chrome Control from within the Host Web Context

Step 3- Showing Settings Links added during configuring options for the Chrome Control

Step 4- Showing Announcement List Items queried from the Host Web executed by Cross Domain Request to SharePoint

20

So it is evident that by making use of Chrome Control we could save significant efforts in maintaining Synch between SharePoint and App UI Designs.

Hope you find it helpful.

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… 🙂

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. 🙂