Exploring Context in Client Object Model

The process of communicating with the SharePoint server from the client side starts through the ClientContext class, which inherits from ClientRuntimeContext. This class provides the capability to control the communication with the SharePoint server. You can specify the following while accessing the SharePoint server:

• URL

• Site

• Web

• Authentication Mode

• Credentials

This hour does not delve into the authentication mode and credentials now as this is outside the scope of this book. For now, just remember that you can use forms authentication as well to access the SharePoint site, and the client object model provides the means to pass the credentials as well.

Understanding the Role of the Load() Method

In this method you specify in which objects you are interested. Suppose if you want to load the List, you can just specify the name of the list you want. The main advantage of this is that specifying only the items you are interested in helps reduce network traffic. Generally the Load() method returns simple references to types, and not the whole object. If you try to access the child objects right now, you get a PropertyOrFieldNotInitializedException. If you need access to those, you have to mention those explicitly in your Load() method. Each time you call the Load() method, it adds one more query to the batch. Another interesting point is it’s not necessary for you to load the parent first to gain access to the child nodes. You take a look into this in the next example.

Now in the previous example comment the context.ExecuteQuery() and run the application. You get a PropertyOrFieldNotInitializedException. You might be thinking we had mentioned exactly what to load, but why is it throwing an exception? This is where ExecuteQuery comes into the picture.

Exploring the ExecuteQuery() Method

As mentioned earlier, even though you mentioned the items to load in the Load() method, it doesn’t load until you explicitly call the ExecuteQuery() method. This method is responsible for calling the Client.svc with the current batch mentioned earlier in the Load() method. This method can also be used to commit the changes back to the server once you have made changes to the client side as well.

Now that you understand the functionality of both Load() and ExecuteQuery(), let’s take a look into a slightly more complex example. This example uses a list named Books that is available under http://splearn. So before running this example, create a list named Books under splearn. This example tries to load fields in a list from SharePoint without actually loading the web object or the complete list object. This helps you understand how efficient the Load() method is.

using (ClientContext context = new ClientContext(@"http://splearn"))
{
    Web web = context.Web;
    List books = web.Lists.GetByTitle("Books");
    context.Load(books.Fields);
    context.ExecuteQuery();
    FieldCollection collection = books.Fields;
    Console.WriteLine(collection[0].InternalName);
    //Console.WriteLine(books.ItemCount);
    Console.Read();
}

Now as you saw in the previous example, you can access the fields of the list without actually loading the complete web object or the list object. This is achieved by mentioning specifically what to load in the Load() method. As we mentioned just the list to load in the Load() method, just the list and nothing related to the web object is loaded. To prove this, let’s uncomment the code in the preceding example and execute the application.

using (ClientContext context = new ClientContext(@"http://splearn"))
{
    Web web = context.Web;
    List books = web.Lists.GetByTitle("Books");
    context.Load(books.Fields);
    context.ExecuteQuery();
    FieldCollection collection = books.Fields;
    Console.WriteLine(collection[0].InternalName);
    Console.WriteLine(books.ItemCount);
    Console.Read();
}

We get the PropertyOrFieldNotInitializedException because we specifically mentioned the fields to be loaded.

Using Lambda Expressions

If you noticed the signature of the Load() method by now, it should not come as a surprise that you can specify a lambda expression as part of the Load() method. Take a quick look into the following sample application:

using (ClientContext context = new ClientContext(@"http://splearn"))
{
    Web web = context.Web;
    List books = web.Lists.GetByTitle("Books");
    context.Load(books, x => x.Title);
    context.ExecuteQuery();
    Console.WriteLine(books.Title);
    //Console.WriteLine(books.Description);
    Console.Read();
}

As you can see, the ExecuteQuery() method loads only the items mentioned in the lambda expression. If you uncomment the code and try to access the description of the list, you get a PropertyOrFieldNotInitializedException as you haven’t mentioned Description in the lambda expression.

Understanding the LoadQuery() Method

LoadQuery() is an alternative to the Load() method in the SharePoint 2010 client model. Sometimes it may not be easy to mention the items to load in the Load() method. In that case, you can create a query and pass it as a parameter to the LoadQuery() method.


By the Way

A notable difference between Load() and LoadQuery() is that Load() returns a collection of objects, whereas LoadQuery() returns an IEnumerable<T>.


using (ClientContext context = new ClientContext(@"http://splearn"))
{
    Web web = context.Web;
    IEnumerable<List> genericLists = context.LoadQuery(web.Lists.Where(
        list => list.BaseType == BaseType.GenericList));

    context.ExecuteQuery();
    foreach (List list in genericLists)
    {
        Console.WriteLine(list.Title);
    }
    Console.Read();
}

As seen in the preceding code, the query is much easier to read. Remember, you still have to use the ExecuteQuery() method to load the items mentioned in the query.

Creating, Updating, and Deleting Data Using the Client Object Model

You can use the client object model to insert data into SharePoint as well. The following example creates a new item in SharePoint and adds a new ListItem to the list:

using (ClientContext context = new ClientContext(@"http://splearn"))
{
    //Create a new list
    ListCreationInformation newList = new ListCreationInformation();
    newList.Title = "New List";
    newList.Description += "A new list created with Managed Client OM";
    newList.TemplateType = (int)ListTemplateType.GenericList;
    List list = context.Web.Lists.Add(newList);
    context.ExecuteQuery();

    //Create a new list item
    ListItemCreationInformation newListItem = new ListItemCreationInformation();
    ListItem item = list.AddItem(newListItem);
    item["Title"] = "New List Item";
    item.Update();
    context.ExecuteQuery();
}

For creating a new List and ListItem in SharePoint you have to use the ListCreationInformation and ListItemCreationInformation classes. As you can see the Update() method is used to update the changes made to the website. As in previous cases, you still have to call the ExecuteQuery() method to update the changes back to the SharePoint database. You can verify whether the new list got created by going to the SharePoint site.

The following code example illustrates how you can update a website’s description and a list’s description using the client object model:

using (ClientContext context = new ClientContext(@"http://splearn"))
{
    // Update Site Description
    Web web = context.Web;
    web.Description = "Learn SharePoint";
    web.Update();
    context.ExecuteQuery();
    Console.WriteLine(web.Description);
    Console.Read();

    // Update List Description
    List list = web.Lists.GetByTitle("Books");
    list.Description = "Updated Description";
    list.Update();
    context.ExecuteQuery();
    Console.WriteLine(list.Description);
    Console.Read();
}


By the Way

The most important thing to keep in mind here is you don’t have to load the item you are updating into context.


The preceding example sets the Description of web first and then calls the Update(). But still this won’t get reflected in the site until you call the ExecuteQuery() method.

For deleting data in SharePoint using the client object model, you use the DeleteObject() method. As in previous examples, call ExecuteQuery() to complete the deletion process:

using (ClientContext context = new ClientContext(@"http://splearn"))
{
    Web web = context.Web;
    List list = web.Lists.GetByTitle("ToDelete");
    list.DeleteObject();
    context.ExecuteQuery();
}

Understanding Exceptions

Because the client object model works in a disconnected way, error handling becomes all the more important. Table 8.3 depicts the various exceptions that can arise while working with the client object model.

Table 8.3. List of Exceptions Thrown by the Client Object Model

Image
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset