Tuesday, October 09, 2012

SharePoint Client Side Object Model

Retrieving the SharePoint List Items through Client Side Object Model(CSOM).
Below link highlights the advantages of using the client side object model in SharePoint.
http://msdn.microsoft.com/en-us/library/ff798473.aspx

Simple start up :)
add references of these two assembly files to your SharePoint project

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll

both available on ISAPI folder of the 14 Hive.

3 columns in the SharePoint List has been mapped with one generic class.


namespace CSCOM
{
   public class ListClass
    {
       public string _id;
       public string _title;
       public DateTime _publishedDate;
       public string NewsID
       {
           set { _id= value; }
           get { return _id; }
     
       }
       public DateTime PublishedDate
       {
           set { _publishedDate = value; }
           get { return _publishedDate; }

       }
       public string NewsTitle
       {
           set {  _title = value ; }
           get { return _title; }
       }
       public ListClass()
       { }
       public ListClass(string _strId, DateTime _dtPublished, string _strNewTitle)
       {
         
            NewsID= _strId;
            NewsTitle = _strNewTitle;
            PublishedDate = _dtPublished;

       }
    }
}

Retrieving the ListItem via client side object model. You need to load the list and list collection object and execute the whole context.



 List cl = new List();
            ClientContext context = new ClientContext(Web.Url);
            List list = context.Web.Lists.GetByTitle("Your List Name");
             CamlQuery q = new CamlQuery();
            q.ViewXml="";
            Microsoft.SharePoint.Client.ListItemCollection cols = list.GetItems(q);
            context.Load(list);
            context.Load(cols);
            context.ExecuteQuery();
            DataTable table = new DataTable();
            table.Columns.Add("Id");
            table.Columns.Add("Title");
            table.Columns.Add("Date Published");
            foreach (Microsoft.SharePoint.Client.ListItem item in cols)
            {
           
                ListClass obj = new ListClass();
                obj.NewsID = item["ID"].ToString();
                obj.NewsTitle = item["Title"].ToString();
                obj.PublishedDate = Convert.ToDateTime(item["Date_x0020_Published"].ToString());
                cl.Add(obj);
            }
            GridView1.DataSource = cl;
            GridView1.DataBind();