SharePoint 2016/2013/Online: How to Optimize SharePoint Custom Pages Using HTML5 IndexedDB API

In this article we will discuss another obvious performance issues with SharePoint Solutions involving large volume of data transactions surfacing SharePoint Custom Pages.

This could become more prominent if we have strict governance in place and we are not allowed to make use of advanced server side options (Custom Web Service End Point, MTA Enabled Modules etc.).

In one of the recent assignment I came across a similar scenario where I need to crawl data from an external Web Service end Point and surface data on SharePoint Pages. Since the anticipated data volume was huge and traditional caching approaches like Cookies wont’ work due to size limitations.

In pursuit of the solution I have gone through the “HTML5 Web Storage APIs” that allows you to setup an In-Browser Transactional Database System called “IndexedDB”.

Here is a quick introduction of IndexedDB for details I must recommend you to visit IndexedDB

“IndexedDB is a transactional database system, like an SQL-based RDBMS. However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a JavaScript-based object-oriented database. IndexedDB lets you store and retrieve objects that are indexed with a key; any objects supported by the structured clone algorithm can be stored. Operations performed using IndexedDB are done asynchronously, so as not to block applications.”

I also want to thanks to “Raymond Camden” for his detailed research on Storage Limits for IndexedDB and believe you must refer this link to understand the limits carefully before getting into concrete implementations.

Now let’s try to understand the implementation details by using following diagram:

Solution Architecture Diagram & Explanation

1

In this solution the SharePoint Page will try to look for the required data in Local Indexed DB created to support this page. If data is not found in local database, page will issue the request for data from SharePoint List.

Since we are dealing with “100,000” Items present in SharePoint List, I made use of “REST API + OData Continuation” data access strategy to overcome SharePoint List Threshold Limits. This mechanism will access only 100 List Items at a time and it is safe to extend this limit up to 2000 items per fetch.

Each fetch will a JSON Object that will be persisted into Indexed DB as individual record. I opt this strategy to reduce the page load time. If the number of items are not much you can add each item as separate record.

Every subsequent data call will be automatically diverted to the local database as primary source.

Additionally we can add “Auto Refresh Modules” to keep the local database fresh with SharePoint List Changes and sync the changes with Indexed DB “Asynchronously”.

Ideally speaking for a complete solution “Auto Refresh Modules” are must to have.

So this all about execution summary for this solution.

Now let’s have look at implementation details as follows-

I have created a SharePoint List with two columns and “100,000” Items added to it as shown below.

Demo

This list will be acting as data source for the page. In actual scenarios this source could be a Web Service End Point which can provide voluminous data on demand.

2

3

Before getting into code let’s see how this Page will behave on execution. Demonstrating the page in action will be helpful later when we get a deep dive in code.

If we run the page we will see this page took about “3 minutes” to get execution completed.

The first execution cycle will include the following actions:

  1. Initialize IndexedDB Database
  2. Query SharePoint List
  3. Add REST API Response to IndexedDB
  4. Load page with data from IndexedDB

Since we are adding data to the store asynchronously, overall application will remain functional even it is taking 3 minutes to complete.

4

Following screen shot showing data adding to IndexedDB asynchronously

5

We can also review the Indexed DB initialized as the part of this request using “Developer Tools or F12 Key” with in the browser as shown below-

6

We can explore each item in the each of the JSON Object as shown below-

7

Now refresh the page to see the execution again and we can see roughly “1 second” to complete the page request.

The subsequent execution cycle will include the following actions:

  1. Query IndexedDB for data
  2. Load page with data from IndexedDB

So we can see how we can trim the execution path by using a well-defined strategy.

8

Code Analysis

Let’s do the code analysis to understand the concrete implementation.

In Step 1 we are enclosing some of the literals as variables and will refer theses variables later in the code

9

In Step 2 we are checking if respective Indexed Database is initialized already or not and if not Initialize the Database. In this demos let’s call this database as “Products”

10

In Step 3 “onsuccess” event handler will get executed and database object will get stored in a global variable “SharePointOptimization.sharePointStore”. This variable will be acting as start point for all the operations on the database in future.

In Step 4 default error handling module is assigned as callback function to “onerror”, “onblocked”, “onabort” event handler

11

In Step 5 we are querying SharePoint List using REST API

12

In Step 6 we are making use of OData Continuation Techniques to overcome SharePoint List Threshold restrictions.

In this step we also call “AddDataToStore” function that will add SharePoint List Items coming as JSON Object to the Local Indexed Database.  It is important to recall that in this demo I am storing 1 JSON Object as 1 record in database and each object contains information for 100 List Items.

13

In Step 7 we are adding JSON Objects to IndexedDB. In order to do that we need to perform following operations-

  • Initialize Transaction with Read Write Operation Permissions
  • Get Handle on “Products” Database inside IndexedDB Data Stores
  • Call asynchronous “add” method to add JSON Object to “Products” Store

In Step 8 we are calling “QuerySharePoint” function to query data from SharePoint List in case data is not available in Local Database.

14

Steps 9, 10, 11 explains about “ReadSPStore” function where we will read the data from Local Data Store (IndexedDB)

In Step 9 following operations are performed-

  • Initialize Transaction with Read Operation Permissions
  • Get Handle on “Products” Database inside IndexedDB Data Stores
  • Call asynchronous “count” method to get total number of JSON Object available in “Products” Store

In Step 10 following operations are performed-

  • Check for get count request status
  • If success Initialize Indexed DB Cursor by calling asynchronous “openCursor” function

In Step 11 following operations are performed-

  • Check for get cursor request status
  • If success read the record from IndexedDB and add to the local array variable
  • Call “continue” function as long as there are items left in local store
  • Once all data is read and save to the local array pass this array to “RenderUI” function to render this data on the interface as required

15

In Step 12 we can plug any UI engine to produce more intuitive UI as applicable, for the sake of this demo I am writing out the Count of Store records * 100 (since each record contains 100 Items) to show the total number of items stored in the local store.

16

Steps 13, 14, 15 show you a helper function to check if local store contains required data or not. It helps to decide if we need to read data from Local Store or SharePoint List

“GetProductCount” function is quite similar to the “ReadSPStore” function except it perform a lesser number of operations

17

In Step 16 we will initialize Local SharePoint Store by calling “InitializeSharePointStore” function

18

In Step 17 we can see some of the UI elements to build a basic UI for this demo

19

Point of caution

Before implementing this mechanism make sure you have identified all the compatibility issues around this corner.

I would recommend you to refer the following site every now and then to make sure you are using features supported by the targeted browsers.

http://caniuse.com/#search=IndexedDb

20

Since I have made use of artifacts which are compatible with SharePoint Online Development Guidelines so we can use this approach with pages hosted in SharePoint Online as well.

That is all for this demo.

Hope you find it helpful.

 

SharePoint 2016/2013/Online- How to Apply Password Encryption for Component as Service using PowerShell

Recently I have developed a couple of PowerShell based components that will serve as data crawlers for federated data sources like External Web Services, SQL Server Databases, and Excel Workbooks & SharePoint Lists.

In order to authenticate the Service Accounts against all of these sources I had no choice but to embed the User Name and Passwords with in the PowerShell Code in plain text. It gets even worst when few of the Web Services could support only “Basic Authentication”.

Saving passwords in plain text to code files could lead us to the Compliance Issues and could get the solutions rejected eventually.

In order to fix this issue I have implemented a couple of mechanism to deal with each type of Authentication requirements.

In this article I will discuss the mechanism to authenticate the requests to SharePoint Lists.

In order to simplify this demo let’s consider a simple scenario where I am having a list “MyLocations” as shown below and I need to export its metadata using a PowerShell based component.

1

To keep the content crisp I will walk you through the specific section from code and skipping all the CSOM specific code which you can refer in my earlier articles if you like.

I have intentionally divided this implementation into two separate code files in order to keep the passwords safe from the developers. Intent is to get the Encryption File generated by the SharePoint Admins and provided these files to developers for so that they can use it in code directly as shown below.

In the following code snippet you can see the commands to encrypt password “12345678” and export it to a text file “BANSALP.txt”

2

This file would look like as shown below:

34

This way you can store passwords for all required service accounts in different text files without violating Security Compliance.

Now in order to pass this encrypted password to SharePoint for authentication we can make use of “System.Management.Automation.PSCredential” Class as shown below.

Here “Get-Content” Command let is used to read the content from “BANSALP.txt” file and “ConvertTo-SecureString” Command let to get the encrypted password as secure string

5

Once credential Object has been created we can assign this credential object to SharePoint Client Context “Credentials” Property

6

With this Client Context SharePoint Authenticates the incoming request based on the ACL of the requestor

Following is the outcome of the call that we have send to SharePoint:

7

I have exported the metadata to a “csv” file as well that would look like this.

8

Hope you find it helpful.

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: Send Email Using REST API

Sending Email is one of the most common functionalities that need to be developed in almost every project irrespective of the nature of the project.

Based on the new development paradigms introduced by Microsoft, recommended development approach prefers to make use of Client Side Object Model and REST API for developing functionalities for SharePoint 2013.

In this article by moving on the same lines we will discuss how to develop a Mail Client for SharePoint Online/2013 using REST API End Point exposed by SharePoint 2013.

In this demo I will make use of OOB Content Editor WebPart for executing the Javascript Code and a virtual mail Utility “smtp4dev” which is available on CodePlex for free download. “smtp4dev” allow you to test mail functionality by intercepting incoming mails using a thin mail client by configuring a local SMTP Server in your development VM.

I have mentioned quite a number of such useful tools in one of my earlier blog post SharePoint Developer Tools – Get Your Gears, and recommend you to visit it for details on the tools that can be very helpful in enhancing developer productivity while working in SharePoint Environment.

Let’s start by writing JavaScript code and since we are making use of Content Editor WebPart we need to perform some additional tasks:

  • Open SharePoint Designer
  • Visit Site Assets Library
  • Add a new Text file and give it a proper name of your choice

1

In the text file add the code as shown in the following steps

Step 1: CSS of your choice to build the UI as desired. In my case I put some CSS classes for the UI of mail client

2

Step 2: Add some HTML elements that design the UI for the Mail Client and apply CSS classes appropriately

3

Step 3: Add reference to “jquery.js”, “sp.runtime.js” and “sp.js” files

4

Step 4: Add “document.ready” function to bind the click even of the button with the appropriate event handler

5

Inside Event Handler function “SendMail ()” we will proceed with the code as follows:

Step 5: Reading values from UI control to prepare the Email Contents to be sent

Step 6: Preparing the Request Header object to be sent along with REST API call to SharePoint, this object is necessary to provide execution details to be authenticated by SharePoint

Step 7: Preparing REST API URL to pass into the subsequent call by making use of page context variable

Step 8: Preparing API Call by configuring metadata object of type “SP.Utilities.EmailProperties”. It is worth to spend time to review this object for a while to notice what all properties are exposed by this object. We can specify From Email, To Email, CC Email, Subject & Body of the mail with in this object

Step 9: In the success call back we can perform the desired action, in this demo we are just writing down a success message to the Result Panel

6

With this we are all done with coding and now it is time to create a new page and add Content Editor WebPart to the page

  • Go to Site Page Library
  • Add a new WebPart Page
  • On the WebPart Page, Click Add WebPart Link

7

  • From the WebPart Picker choose “Content Editor” WebPart that falls under “Media and Content” category
  • Click Add to add the WebPart to the Page

8

Next thing is to add the reference to the JavaScript Code file that we have created in the steps above.

  • To refer the Code file Edit the WebPart
  • Specify the relative URL of the Code file in the Content Link placeholder in WebPart Properties as shown below

9

10

  • Once done with the changes choose “Stop Editing” from the Ribbon to save the changes to the WebPart

11

If the code executes successfully we will see the UI for Mail Client rendered as shown below

12

Before we execute the code to send the mail we need to first have a look to the “smtp4dev” tool. This tool will receives the mail messages and get them displayed to “Messages” Tab

13

Now enter the Name, Email Address and Message on the UI and click “Send Email” button

14

Once the Email functionality gets executed successfully, we will see the Success message print in the Result Panel and also an Email Received Notification from “smtp4dev” tool.

15

We can analyze the received further by looking it into the “smtp4dev” tool “Message” Tab.

In the “Message” Tab select received mail and click on the “Inspect” button

16

On the “Message Details” screen under the “Body” Tab we can see the body of the mail received

17

Since this the REST call we can analyze the corresponding Request-Response cycle using any Web Proxy tool, here I am using Fiddler to inspect it.

We will get a null response Object in case of successful execution of the Email functionality.

18

Known Limitations

Issue with Attachments

Adding attachments with in the Email is not supported using this approach and this limitation is due to limited exposure of the properties by “SP.Utilities.EmailProperties” Object.

Only following properties has been exposed by this object to be used with in REST Call

19

Here we can see that there is no property exposed for adding attachments along with the mail.

Issue with External Mails

External Mail are not supported using this approach which means we can only send mails to valid Site Users only if you try to send the mail to any external User or Email ID you will probably get the following error:

20.png

That is all for the 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 Online: How to Install SharePoint Online Management Shell

SharePoint Management Shell is a Windows PowerShell Module that allows managing SharePoint Users, Sites & Content in an efficient manner.

In this article we will see the steps to setup the development machines with “SharePoint Online Management Shell”.

First let’s look for the System Requirements to avoid any frustrating compatibility issues that might arise later on:

System Requirement

Supported Operating System
  • Windows 7 Service Pack 1
  • Windows 8
  • Windows Server 2008 R2 SP1
  • Windows Server 2008 Service Pack 2
  • Windows Server 2012
PowerShell
  • PowerShell 3.0

Steps to Install SharePoint Online Management Shell

Step 1: Visit the Url: https://www.microsoft.com/en-in/download/details.aspx?id=35588

Step 2: Click download button

1

Step 3: Select “sharepointonlinemanagementshell_4727-1200_x64_en-us.msi” file and click Next

2

Step 4: Run the “sharepointonlinemanagementshell_4727-1200_x64_en-us.msi” file

Step 5: Accept License Terms & Click Install Button

3

4

5

Step 6: Once the installation is complete, search for “SharePoint Online Management Shell” and launch it

6

This completes the installation of SharePoint Online Management Shell on our machine.

Now let’s try a few of the operations to verify the installation of SharePoint Online PowerShell Module

How to connect to SharePoint Online Services

Get current user credentials to connect to the SharePoint Online Services (assuming the user is having a valid SharePoint Online Account Credentials)

$userCredentials = Get-Credential

7

8

Import “Microsoft.Online.SharePoint.PowerShell” Powershell module to the Management Shell Console

Import-Module Microsoft.Online.SharePoint.PowerShell

9Connect to SharePoint Online Service by supplying Tenant Url and User Credential to the Connect-SPOService command

Connect-SPOService  -Url  https://prashantmbansal-admin.sharepoint.com -Credential $userCredentials

If you notice carefully the URL I have supplied to the Url Parameter in the above command, you will find “-admin” is added in the URL.

Actual URL of the Tenant is https://prashantmbansal.sharepoint.com but it is by convention that we much have to use “-admin” in the Host Header of URL in order to connect to the SharePoint Online Services.

That is why we have to specify the “https://prashantmbansal-admin.sharepoint.com” as Tenant URL.

10

If we forgot to follow this convention we might encounter the following error:

11

How to get the list of all the SharePoint Sites lies under current Tenancy

Once we are successfully able to Connect to SharePoint Online Services we can perform different operations on the site such as getting a list of all the SharePoint Sites available with in current tenancy by using the following command.

Get-SPOSite

12

This is just the first step to Start with PowerShell Development for the SharePoint Online Sites, but the possibilities are limitless, especially when we can combine the SharePoint Client Object Model with PowerShell Scripting Environment.

We will explore the details on CSOM based Solutions driven by PowerShell Scripts in future articles.

Hope you find it helpful.