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.