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.