Saturday, August 06, 2011

Handling exception in SharePoint Client Object Model

 

If you use normal try … catch … finally blocks to handle exceptions in Client Object model, you will need to invoke the server via ExecuteQuery three times(one for each situation). This could lead to performance degradation as well as to a huge stress on the server side. Luckily the Client Object Model provides a class named ExceptionHandlingScope that is specifically defined to support such situations and avoid executing multiple queries against the server.

Refer sample from http://msdn.microsoft.com/en-us/library/ee534976.aspx



ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection");            

ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);

using (scope.StartScope())
{
using (scope.StartTry())
{
List oList = clientContext.Web.Lists.GetByTitle("My List");
oList.Description = "In Try Block";
oList.Update();
}

using (scope.StartCatch())
{
// Assume that if there's an exception, it can only be
// because there is no list with the specified title, so
// create the list.
ListCreationInformation listCreateInfo = new ListCreationInformation();
listCreateInfo.Title = "My List";
listCreateInfo.Description = "In Catch Block";
listCreateInfo.TemplateType = (int)ListTemplateType.Announcements;
List oList = clientContext.Web.Lists.Add(listCreateInfo);
}

using (scope.StartFinally())
{
List oList = clientContext.Web.Lists.GetByTitle("My List");
oList.EnableFolderCreation = true;
oList.Update();
}
}

clientContext.ExecuteQuery();




Explanation:



Under the cover, the ExceptionHandlingScope instance collects activities (internally called ClientAction) to execute on the server side for all the three situations (try, catch, finally). The server will begin executing the code inside the StartTry block, and then in case of failure, it will execute the code in the StartCatch. Whether or not exceptions occurred in the StartTry

block, it will finally execute the code in the StartFinally block. However, the request sent to the server is just one, as well as the response.