Pages

Search This Blog

Showing posts with label Client Context. Show all posts
Showing posts with label Client Context. Show all posts

Monday, December 19, 2011

Using exception handling scope to handle errors in client object model : SharePoint 2010

While using client object model in SharePoint 2010, many a times we come across situations where in we call the
ctx.ExecuteQuery() method and some error occurs on the server due to which we get a 'ServerException' which does not give us the opportunity to make corrections in the operation that we are trying to do.

The ExceptionHandlingScope class models a try/catch behaviour for such situations.When we add the code within this scope,it is processed as if its present in a try/catch and gives the opportunity to correct the error in the catch/finally block.

For eg. lets take an example where in we are trying to update the description of a list using managed client object model.If the list does not exist in the target site, it will throw an exception.Now, in the catch block of the exception handling scope , we can create the list in the site and then update its description.

The code below demonstrates this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;

namespace Sharepoint2010TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {

           using (ClientContext ctx = new ClientContext("http://br-pc-341:2222"))
            {
                //Set up error handling
                ExceptionHandlingScope xScope = new ExceptionHandlingScope(ctx);

                using (xScope.StartScope())
                 {
                    using (xScope.StartTry())
                    {
                        //Try to update the description of a list named "Test List"
                        List testList = ctx.Web.Lists.GetByTitle("Test List");
                        testList.Description = "Test List Description";
                        testList.Update();
                    }
                    using (xScope.StartCatch())
                    {
                        //Fails if the list "Test List" does not exist
                        //So, we'll create a new list
                        ListCreationInformation testListCI = new ListCreationInformation();
                        testListCI.Title = "Test List";
                        testListCI.TemplateType = (int)ListTemplateType.GenericList;
                        testListCI.QuickLaunchOption = Microsoft.SharePoint.Client.QuickLaunchOptions.On;
                        List list = ctx.Web.Lists.Add(testListCI);
                    }
                    using (xScope.StartFinally())
                    {
                        //Try to update the list now if it failed originally
                        List testList = ctx.Web.Lists.GetByTitle("Test List");
                        if (testList.Description.Length == 0)
                        {
                            testList.Description = "Test List Description";
                            testList.Update();
                        }
                    }
                }
                //Execute the entire try-catch as a batch!
                ctx.ExecuteQuery();

                Console.WriteLine("Description Updated !!");
            }

        }
    }
}


This console application updates the description of the list named 'Test List'. If the list does not exist , the list is
created in the catch block and then the description is updated.



The list with the updated description can be seen on the sharepoint site:



Saturday, December 10, 2011

Create Custom sharepoint list using ECMA scripts (Sharepoint 2010 Client Object Model)

Many a time we have a requirement that we need to create a Sharepoint list without writing any server side code.

This requirement can be achieved by using Sharepoint 2010 ECMA scripts (Sharepoint 2010 Client Object Model).

Please follow the below steps.

Step 0: Create a new site page.

Step 1: Add a content editor webpart.

Step 2: Open the HTML souce for this content editor webpart and add the below code as it is and save it.


// JScript source code

<script type="text/javascript">

//ExecuteOrDelayUntilScriptLoaded(CreateList, "sp.js");
function CreateList()
{ 
    var site;
    var context;
    var ListName = document.getElementById('listName').value;
    var field1 = document.getElementById('field1').value;
    var field2 = document.getElementById('field2').value;


    var lstDesc = "List Description";
    context = SP.ClientContext.get_current();

    var site = context.get_web();

    var SetNewList = new SP.ListCreationInformation();
    SetNewList.set_templateType(SP.ListTemplateType.genericList);
    SetNewList.set_title(ListName);
    SetNewList.set_description(lstDesc);
    //Add the list name in QuickLaunch
    SetNewList.set_quickLaunchOption(SP.QuickLaunchOptions.on);

    var NewList = site.get_lists().add(SetNewList);
    // Add fields to the newly created list.
    var NewField1 = NewList.get_fields().addFieldAsXml(
    '<Field DisplayName=\''+ field1 +'\' Type=\'Text\' />', true,
    SP.AddFieldOptions.defaultValue);
    var NewField2 = NewList.get_fields().addFieldAsXml(
    '<Field DisplayName=\''+ field2 +'\' Type=\'Text\' />', true,
    SP.AddFieldOptions.defaultValue);

    context.load(NewField1);
    context.load(NewField2);

    context.executeQueryAsync(CreateListSucceeded, CreateListFailed);
}

function CreateListSucceeded() {
  alert('List has been created Succesfully.');
}

function CreateListFailed(sender, args) {
  alert('List Creation Failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


 </script>


 //HTML code
 <b>List Name</b>
 <input id="listName" width="150px"/>
 <br/>
 <b>Field0</b>
 <input id="field1" width="150px"/>
 <b>Field1</b>
 <input id="field2" width="150px"/>
 <br/>
 <img onclick="return CreateList();" alt="Create New List" src="/sites/Test/PublishingImages/Create.PNG"/>
After doing this you will see three textbox and one create button. Fill the list name and the field names to be added and click on Create button.
This will create the new list and add the link in the quick launch menu.

Hope it will be a help to you!
Ravish