Introduction
Since SharePoint’s entry into the Content Management Field, developers had to interact with it using the server side object model. Though Out of the box web services were available it had its own limited development capability. With the introduction of client side object model things became much easier as developers could now interact with SharePoint remotely. Client side object model comes in 3 flavors,
- .Net managed client side object model(CSOM)
- JavaScript object model(JSOM)
- Silverlight client side object model
.Net client side object model is used to access SharePoint remotely from a console application and provides strongly-typed representation of SharePoint objects using the client library Microsoft.SharePoint.Client.dll . JavaScript object model on the other hand is used to access and interact with SharePoint from within the client browser in an asynchronous fashion. We can make use of Content Editor Web part or SharePoint apps to directly communicate with SharePoint by making use of JSOM.JSOM particularly makes use of the SP.js library to handshake with SharePoint server. Silver light has become deprecated and so is Silverlight Client Object Model.
JSOM Working
Just like any other API JSOM is dependent on 3 main client side libraries. These are referenced via SharePoint Master Pages. However if we are using a non-SharePoint custom master page ensure we have the references to the below libraries,
- MicrosoftAjax.js- Usually loaded by ScriptResource.axd
- SP.Runtime.js- Loaded from the LAYOUTS folder
- SP.JS- Loaded from the LAYOUTS folder
In order to perform an operation using JSOM, the request goes from the client browser to the REST service named client.svc residing in the SharePoint Server. This is an asynchronous call as after the request has been made, the code will continue to run. When the request returns one of the success/failure call back methods that are registered will be called to take care of the returned data.
Client.svc service is the WCF service that is responsible for performing all of the operations requested by JSOM. The service is located at /_vti_bin/client.svc on the SharePoint Server. The WCF service endpoint appends /_vti_bin/client.svc/ProcessQuery to process the request that is coming from the client browser and requires a formatted Xml Request as per the protocol specifications. So the request coming from the client browser will xml formatted and the return type will be a JSON response.
Script on Demand
JavaScript object model extensively makes use of script on demand framework (SP.SOD). It means that the script won’t be loaded until explicitly requested. Starting from SharePoint 2010 the scripts will be loaded on to the page only as required. Multiple methods are available in SP.SOD framework to implement On Demand scripting. We will look into two main commonly used functions which are utilized extensively in JSOM implementations.
SP.SOD.executeOrDelayUntilScriptLoaded
SP.SOD.executeOrDelayUntilScriptLoaded(functionName, scriptFileName) schedules an asynchronous callback function (functionName) which will be called when the script(scriptFileName) has finished loading to the page. This method ideally delays the execution of the JSOM code until the dependent scripts has been loaded. SP.js is the primary resource file required for JSOM. If the JSOM code executes prior to the loading of SP.jS library we will get object reference errors. So to make sure JSOM is executed after SP.js is loaded on to the page we make use of ‘SP.SOD.executeOrDelayUntilScriptLoaded’ as :
Usage
- SP.SOD.executeOrDelayUntilScriptLoaded(getWeb, 'SP.js');
-
- function getWeb() {
-
-
- var clientContext = new SP.ClientContext.get_current();
- var oWeb = clientContext.get_web();
- }
One of the limitations of SP.SOD.executeOrDelayUntilScriptLoaded is that if the script file is not loaded, the JSOM code block that is waiting to be executed will wait endlessly and may not even be executed at all. In order to circumvent this issue SP.SOD has another useful function SP.SOD.executeFunc.
SP.SOD.executeFunc
ExecuteFunc method call provides the flexibility to call an On Demand Script and then run another function once the script has finished loading. It resolves the drawback with ‘ExecuteorDelayUntillScriptLoaded(It cannot trigger an On Demand Script).
Usage
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
ExecuteFunc method takes three parameters,
- Sp.js- the script file that will be invoked and loaded to the page. It can be any file
- SP.ClientContext- The main object within the script file that will be used. It can be kept null.
- retrieveListItems- The function to run after the script files are loaded to the page.
JSOM Structure
- $(document).ready(function() {
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
- });
- var collListItem;
-
- function retrieveListItems() {
-
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
- var oList = oWeb.get_lists().getByTitle('Employees');
-
- collListItem = oList.getItems(SP.CamlQuery.createAllItemsQuery());
-
- clientContext.load(collListItem);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
-
- function QuerySuccess() {
-
- var listItemEnumerator = collListItem.getEnumerator();
- while (listItemEnumerator.moveNext()) {
- var oListItem = listItemEnumerator.get_current().get_item('Name');
- console.log("Name : " + oListItem);
- }
- }
-
- function QueryFailure() {
- console.log('Request failed' + args.get_message());
- }
- As a first step, get the current context by calling SP.ClientContext.get_Current method. Since JSOM is running in the context of the browser we cannot impersonate the user . Only way to change the user context is to run the client browser in the required user’s credential.
- Once the context object is created, make a call to get the current web
var oWeb = clientContext.get_web();
- The get_lists() method of the web object returns all the list collection present in the current web. Applying getByTitle () on the list collection fetches the specific Employees list.
var oList = oWeb.get_lists().getByTitle('Employees');
- Now, call getItems method on the list object to return all the items
collListItem = oList.getItems(SP.CamlQuery.createAllItemsQuery());
- The context object provides the load method which is responsible for loading objects and collections from the server. Whatever object is passed into the load method is populated and can be used in the subsequent call back function.
- If you want to work with the child properties of an object, it must be loaded by calling ‘clientcontext.load(object)’ followed by the executequeryasync call .Otherwise, you will generate an exception such as the following,
“The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.”
- JSOM provides the flexibility to execute the requests in batches. Thus each request to create a web object, create a list from the web object won’t be send as separate requests to the server. Instead all the requests will be batched together and send to client.svc upon calling the executequeryasync call. In the above example, we are making calls on the context, web, and list objects but cannot work with the objects’ child properties. Only when the call to ExecuteQueryAsync method is made, an XML request is generated and then sent to the server’s client.svc for processing. As part of ExecuteQueryAsync you have to provide two callback – a success and failure call back. These methods specify how to proceed when the request is processed.
- Depending on the Success/ Failure of the executeQueryAsync call, control will be passed to the appropriate call back function. From within the function we can then access properties of the loaded object. For instance in the above example, the loaded object is the list item collection which can be iterated by instantiating an enumerator object as shown below,
- var listItemEnumerator = collListItem.getEnumerator();
- while (listItemEnumerator.moveNext()) {
- var oListItem = listItemEnumerator.get_current().get_item('Name');
- console.log("Name : " + oListItem );
- }
JavaScript object model is an asynchronous programming model that enables communication with SharePoint in the client side. As with any programming constructs JavaScript object model also has exception handling techniques. JavaScript provides native try/catch to handle exceptions. Though JSOM is based on JavaScript using Try/Catch will not really do exception handling in JSOM. This is because of the asynchronous nature of JSOM. In JSOM all the operations are send as a batch to ‘client.svc’ WCF service in the server that would process the request.
Exception Handling
SharePoint however provides an exception handling mechanism similar to JavaScript try/catch of the format startTry() and startCatch() . Its implementation is similar to try/catch.
The main object that handles the exception in JSOM Is called ‘ExceptionHandlingScope’.It provides the below methods to perform exception handling.
- startScope
- startTry
- startCatch
- startFinally
Let’s see how it works,
Internal Implementation
As with any JSOM implementation we create the starting object which is client context. After that we create an exception handling scope object using the client context. Once the exception handling scope object is created we call its startScope method. This method indicates that the entire code within the block will be eligible for exception handling.
Once the exception handling scope starts we can initiate the try block using the startTry method. Any code written within the startTry method will be checked for exceptions and in the event of an exception the control will be passed to the exception handling block which is the catch block. The code block that began with startTry will be ended using the dispose method. The exception handling block that will be called in case of any error in the try block is the catch block which is instantiated using startCatch method. Within this block we can add the code that will resolve the issue that happened in the try block. Similar to try block catch block will also be ended using the dispose method.
The last code block of the exception handling paradigm is the finally block which is instantiated using the startFinally () method. This block will have all the code that needs to be run regardless of if an error occurs. The dispose method can be called to indicate the end of the finally block.
We can see how exception handling paradigm can be used in a real word scenario. Let’s say, we are trying to update a list which does not exist in SharePoint environment. This will ideally throw an exception as the object is not present. We will write the erroneous list update code in try block and handle the exception in the catch block by creating the list. In the finally block we will again try to update the list. This time the list will be updated without any exceptions.
Full Script
The full code for implementing exception handling is shown below,
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <script language="javascript" type="text/javascript">
- $(document).ready(function() {
- SP.SOD.executeOrDelayUntilScriptLoaded(CheckandCreateList, "sp.js");
- });
-
- function CheckandCreateList() {
-
- var clientContext = new SP.ClientContext.get_current();
- var oWeb = clientContext.get_web();
-
- var exceptionScope = new SP.ExceptionHandlingScope(clientContext);
- var startScope = exceptionScope.startScope();
-
- var tryScope = exceptionScope.startTry();
-
- var oList = clientContext.get_web().get_lists().getByTitle("ExceptionList");
- oList.set_description("Updated Description");
- oList.update();
-
- tryScope.dispose();
-
- var catchScope = exceptionScope.startCatch();
-
- var newListCreationInfo = new SP.ListCreationInformation();
- newListCreationInfo.set_title("ExceptionList");
- newListCreationInfo.set_description("Catch Updated Description");
- newListCreationInfo.set_templateType(SP.ListTemplateType.genericList);
- clientContext.get_web().get_lists().add(newListCreationInfo);
-
- catchScope.dispose();
-
- var finallyScope = exceptionScope.startFinally();
-
- var oList = clientContext.get_web().get_lists().getByTitle("ExceptionList");
- oList.set_description("Finally Updated Description");
- oList.update();
-
- finallyScope.dispose();
-
- startScope.dispose();
-
- clientContext.executeQueryAsync(Success, Failure);
- }
-
- function Success() {
- console.log("The list has been created successfully.");
- }
-
- function Failure(sender, args) {
- console.log('Request failed - ' + args.get_message());
- }
- </script>
Output
Console Output,
Summary
Thus we saw the basics of JavaScript Object Model implementation and exception handling in SharePoint.