Sunday, January 24, 2010

Client OM (Microsoft.SharePoint.Client) Samples for SharePoint 2010

SharePoint 2010 introduces a new client side object model for retrieving data from SharePoint. The client OM is included in Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll. Library reference for client OM is at http://msdn.microsoft.com/en-us/library/ee536622(office.14).aspx

Client OM is counterpart to the Server OM with notable differences
  • Client OM works on both on SharePoint server and client
  • Client OM does not fetch data implicitly
  • Client OM is supported for .NET as well as for ECMA (javascript etc)
The essence of the Client OM lies in ClientContext class ( Microsoft.SharePoint.Client.ClientContext ). This class allows you to get connected with the SharePoint server and then fetch data as required.

In this blog, I will covering few samples on how to use the Client OM.

Basics

First you will need to reference Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll and then use Microsoft.SharePoint.Client namespace.

using Microsoft.SharePoint.Client;

To connect to the SharePoint server, you will need SharePoint URL and create a ClientContext object.

ClientContext context = new ClientContext("http://sharepoint");

At this moment the client context for SharePoint is defined but no connection has been made. Now lets initialize the Web object (equivalent to SPWeb in Server OM).

Web web = context.Web;

To connect/fetch data from the SharePoint, ExecuteQuery needs to be call on ClientContext object.

context.ExecuteQuery();
Console.WriteLine("Web '{0}' [Id:{1}]",web.Title, web.Id);

If you run the above code, it will throw PropertyOrFieldNotInitializedException exception with following message

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.

The code throws exception because client OM does NOT fetch data implicitly. So, we will modify the code to fetch the data the data explicitly. Since we are only interested in Id and the Title of the Web, the code will explicitly request those data. Retreive method in the Web class to tell the client OM which data needs to be fetched. The complete code will look like

ClientContext context = new ClientContext("http://sharepoint");
Web web = context.Web;
web.Retrieve(
    WebPropertyNames.Id,
    WebPropertyNames.Title
);
context.ExecuteQuery();

Console.WriteLine("Web '{0}' [Id:{1}]",web.Title, web.Id);

The above code will print the title and the id for the Web.

ClientObject class is the base class for all Client OM object. ClientObject exposes the following important methods that code will use again and again.

IsPropertyAvailable(string propertyName) - Returns a flag that indicates whether the specified property has been retrieved or set, or has not been retrieved or set.
Retreive() - Retreives all properties associated with the object
Retreive(params string[] propertyNames) - Retreives the specified properties associated with the object

All classes deriving from ClientObject class has a property names class ( for example, Web class has WebPropertyNames class ) which tells what properties can be fetched for the object.

Sample 1: Get all lists in web

The following sample will get all the lists in a web. For the list, the code will fetch the list id, list title and the type of the list.

public void GetAllList()
{
    ClientContext context = new ClientContext("http://sharepoint");
    ClientObjectPrototype allListsPrototype = context.Web.Lists.RetrieveItems();
    allListsPrototype.Retrieve(
        ListPropertyNames.Title,
        ListPropertyNames.Id,
        ListPropertyNames.BaseType);
    context.ExecuteQuery();

    foreach (SPClient.List list in context.Web.Lists)
    {
        Console.WriteLine("List : {0}, Id: {1}, BaseType : {2}", list.Title, list.Id, list.BaseType);
    }

}

Sample 2: Get list details
In this sample, given a list the code gets the details for the list. The details include the Fields and Views of the list.

public void GetListDetails(string listName)
{
    ClientContext context = new ClientContext("http://sharepoint");
    List list = context.Web.Lists.GetByTitle(listName);            

    // get fields name and their types
    ClientObjectPrototype allFieldsPrototype = list.Fields.RetrieveItems();
    allFieldsPrototype.Retrieve( FieldPropertyNames.Id,
        FieldPropertyNames.Title, 
        FieldPropertyNames.FieldTypeKind);

    // get view title
    ClientObjectPrototype allViewsPrototype = list.Views.RetrieveItems();
    allViewsPrototype.Retrieve(
        ViewPropertyNames.Id,
        ViewPropertyNames.Title);

    context.ExecuteQuery();

    foreach (Field field in list.Fields)
    {
        Console.WriteLine("Field '{0}', Type : {1}", field.Title, field.FieldTypeKind);
    }

    ViewCollection views = list.Views;
    foreach (View view in views)
    {
        Console.WriteLine("View '{0}', Id : {1}", view.Title, view.Id);
    }

}

Sample 3: Get list items
The following code gets the list items in the given list.

public void GetListItems(string listName)
{          
    // build the CAML query to get ALL items
    CamlQuery query = new CamlQuery();
    query.ViewXml = "";

    ClientContext context = new ClientContext("http://sharepoint");
    List list = context.Web.Lists.GetByTitle(listName);
    ListItemCollection items = list.GetItems(query);
    items.RetrieveItems().Retrieve();
    context.ExecuteQuery();

    foreach (ListItem item in items)
    {
        // assumes that the list has a field with name 'Title'
        Console.WriteLine("Item : {0}, Id : {1}", item.FieldValues["Title"], item.Id);
    }
}

Sample 4: Add item to a list
The following code adds a list item in the given list.

public void AddItemToList(string listName)
{
    ClientContext context = new ClientContext("http://sharepoint");

    List list = context.Web.Lists.GetByTitle(listName);
    ListItemCreationInformation lic = new ListItemCreationInformation();
    ListItem item = list.AddItem(lic);

    //add the item information
    item["Title"] = "Adding a new Item";

    // List has a field name Checkbox which is a checkbox type field
    item["Checkbox"] = true;  

    item.Update();
    item.Retrieve(ListItemPropertyNames.Id);

    context.ExecuteQuery();

    Console.WriteLine("Id : {0}", item.Id);

}


Client OM is very useful however it takes time to understand how to use the API and get the best out of it. Enjoy !!

1 comment:

Anonymous said...

Банкоматы банка Точка: где снять наличные без комиссии. Условия по бизнес-картам. Как бесплатно пополнить счет, снятие/прием наличных денег 24 часа в сутки https://snowcredit.ru/bankomaty-tochka-banka/