SharePoint 2010: Add/Delete/update/search list items with Managed Client Object Model

Managed client Object model is a rich extension to SharePoint 2010. You can almost perform all kinds operations against SharePoint using Client OM. In this post I’ll show you how to use Managed client Object Model (OM) to manipulate list items. The code snippet I’ll use in the examples below is depend on a product list. The product list has four fields: Product Name, Product Description, Product launch date, available quantity. The product list is represented with a class as shown below:
public class Product
{
    public string ProductName { get; set; }
    public int ProductID { get; set; }
    public string ProductDescription { get; set; }
    public DateTime LaunchDate { get; set; }
    public int AvailableQuantity { get; set; }
}

Add new list item

To add a new item in a list you may or may not need to pass ListItemCreationInformation.  Let me explain when you need to pass ListItemCreationInformation or when not:
  • If you need to add item at the root (not under a subfolder) then you can ignore ListItemCreationInformation by passing null in place of ListItemCreationInformation.
  • If you need to add item somewhere inside subfolder then you need to create an instance of ListItemCreationInformation and set it’s Folderurl to url of the folder you want to save the list item.
The code snippet below add a new list item (Product item in my case):
public void AddNewProduct(string siteUrl, string folderPath, Product product)
{
    const string listName = "Product";
    using (var clientContext = new ClientContext(siteUrl))
    {
        var list = clientContext.Web.Lists.GetByTitle("Product");

        ListItemCreationInformation listItemCreationInformation = null;
        if (!string.IsNullOrEmpty(folderPath))
        {
            listItemCreationInformation = new ListItemCreationInformation();
            listItemCreationInformation.FolderUrl = string.Format("{0}/lists/{1}/{2}", siteUrl, listName, folderPath);
        }

        var listItem = list.AddItem(listItemCreationInformation);
        listItem["ProductName"] = product.ProductName;
        listItem["ProductDescription"] = product.ProductDescription;
        listItem["LaunchDate"] = product.LaunchDate;
        listItem["AvailableQuantity"] = product.AvailableQuantity;
        listItem.Update();
        clientContext.ExecuteQuery();

    }
}
The method in above code snippet takes a site url  and optional folder url and a product. If you want to add item in the root folder then you can pass folderPath parameter empty or null in the above method. Depending on whether you have passed folderPath or not, the ListItemCreationInformation will be initialized or not. If you don’t pass folderPath, the ListItemCreationInformation variable will be null. but if you want to add item in a specific subfolder then pass the folder name as parameter and the ListItemCreationInformation will be initialized and teh FolderUrl of the instance will be set with parameter folderaPath.

Delete list item

In the code snippet below, I have used the same product list. I have passed the product Id as parameter and the get the list item by id. Once I get the list item, I have invoked the DeleteObject method of the list item.
public void DeleteProduct(string siteUrl, int productId)
{
    using (var clientContext = new ClientContext(siteUrl))
    {
        var list = clientContext.Web.Lists.GetByTitle("Product");
        var product = list.GetItemById(productId);
        product.DeleteObject();
        clientContext.ExecuteQuery();
    }
}

Update List Item

The following code snippet shows how to update a product list.
public void UpdateProduct(string siteUrl, Product product)
{
    using (var clientContext = new ClientContext(siteUrl))
    {
        var list = clientContext.Web.Lists.GetByTitle("Product");
        var productToModify = list.GetItemById(product.ProductID);
        productToModify["ProductName"] = product.ProductName;
        productToModify["ProductDescription"] = product.ProductDescription;
        productToModify["LaunchDate"] = product.LaunchDate;
        productToModify["AvailableQuantity"] = product.AvailableQuantity;
        productToModify.Update();
        clientContext.ExecuteQuery();
    }
}

Get a single List Item

To get a lsit item you need to specify the fields you want to retrieve from the list item.
public Product GetProductById(string siteUrl, int productId)
{
    Product product = null;
    try
    {

        using (var clientContext = new ClientContext(siteUrl))
        {
            var list = clientContext.Web.Lists.GetByTitle("Product");
            var productItem = list.GetItemById(productId);
            clientContext.Load(productItem, pi => pi.Id, pi => pi["ProductName"], pi => pi["ProductDescription"], pi => pi["AvailableQuantity"], pi => pi["LaunchDate"]);
            clientContext.ExecuteQuery();
            product = new Product();
            product.AvailableQuantity = Convert.ToInt32(productItem["AvailableQuantity"]);
            product.LaunchDate = Convert.ToDateTime(productItem["LaunchDate"]);
            product.ProductDescription = productItem["ProductDescription"].ToString();
            product.ProductID = productItem.Id;
            product.ProductName = productItem["ProductName"].ToString();
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);

    }
    return product;
}
As shown in the example below, the field values I like to retrieve are passed in the ClientContext.Load method. If you want to retrive all fields (which is not recommended) then call the Load method with the list item, as shown below:
clientContext.Load(productItem);

Get Collection of List Items

To get a list of items as per any condition, you can use CAML  query (or in Linq to SharePoint extension). I’ve covered in another post on how to use Linq to SharePoint. One important point to notice here in the code snippet below is that if you want to look for items inside subfolders thenyou need to add an extra attribute Scope=’RecursiveAll’ in view tag.
public IList<Product> FindProductsByName(string siteUrl, string productName, bool includeSubfolder)
{
    IList<Product> products = new List<Product>();
    try
    {
        string scope = string.Empty;
        if (includeSubfolder)
        {
            scope = "Scope='RecursiveAll'";
        }

        using (var clientContext = new ClientContext(siteUrl))
        {
            List list = clientContext.Web.Lists.GetByTitle("Product");
            CamlQuery query = new CamlQuery();
            query.ViewXml = string.Format(@"<View {0}>
                                <Query>
                                    <Where>
                                    <Contains>
                                        <FieldRef Name='ProductName'/>
                                        <Value Type='Text'>{1}</Value>
                                    </Contains>
                                    </Where>
                                </Query>
                                </View>", scope, productName);
            ListItemCollection listItems = list.GetItems(query);
            clientContext.Load(listItems, li => li.Include(pi => pi.Id, pi => pi["ProductName"], pi => pi["ProductDescription"], pi => pi["AvailableQuantity"], pi => pi["LaunchDate"]));
            clientContext.ExecuteQuery();

            foreach (var productItem in listItems)
            {
                var product = new Product();
                product.AvailableQuantity = Convert.ToInt32(productItem["AvailableQuantity"]);
                product.LaunchDate = Convert.ToDateTime(productItem["LaunchDate"]);
                product.ProductDescription = productItem["ProductDescription"].ToString();
                product.ProductID = productItem.Id;
                product.ProductName = productItem["ProductName"].ToString();
                products.Add(product);
            }
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);

    }
    return products;
}
You can notice that I have passed the fields I want to load as per the query result in ClientContext.Load’s li.Include extension method. If you want to load all properties then you can call the Load method in a way as shown below:
clientContext.Load(listItems, li => li);

If you don’t specify a field to load but try to access it then you will get an exception of type ‘PropertyOrFieldNotInitializedException’ with the 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.