client object model examples

Upload: anupama-kolla

Post on 07-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Client Object Model Examples

    1/29

    1 SharePoint 2010 Client Object Model

    SharePoint 2010 Client Object Model

    Microsoft SharePoint 2010 introduces three new client APIs for interacting with SharePoint sites:

    from a .NET managed application (not earlier than Microsoft .NET Framework 3.5), from a

    Microsoft Silverlight application (not earlier than Silverlight 2.0), or from ECMAScript (JavaScript,

    JScript) that executes in the browser. These new APIs provide access to a subset of the types andmembers that are contained in theMicrosoft.SharePointnamespace of the server-side object

    model.

    Microsoft SharePoint Foundation 2010 introduces three new client APIs for interacting with

    SharePoint sites: from a .NET managed application (not earlier than Microsoft .NET Framework

    3.5), from a Microsoft Silverlight application (not earlier than Silverlight 2.0), or from ECMAScript

    (JavaScript, JScript) that executes in the browser. These new APIs provide access to a subset of

    the types and members that are contained in theMicrosoft.SharePoint namespace of the server-

    side object model.

    The new client object models provide an object-oriented system for interoperating with

    SharePoint data from a remote computer, and they are in many respects easier to use than the

    already existing SharePoint FoundationWeb services. You start by retrieving a client context

    object that represents the current request context, and through this context, you can obtain

    access to client objects at site-collection level or lower in the SharePoint Foundation hierarchy.

    Client objects inherit from theClientObjectclass (ECMAScript:ClientObject), and you can use

    them to retrieve properties for a specific SharePoint object, to retrieve child objects and their

    properties, or to retrieve child items from a collection.

    Namespaces

    Namespaces of the Microsoft .NET managed and Microsoft Silverlight managed client object

    models .

    These two object models generally overlap and are described together, but the reference indicates where a

    specific type or member applies to only one API.

    Name Description

    Microsoft.SharePoint.Client Core namespace that provides types and members for working with

    SharePoint Foundation Web sites, list data, and users within a site

    collection.

    Microsoft.SharePoint.Client.Utilities Provides types and members for encoding strings, for working with

    security principals, and for performing specific utilities tasks.

    Microsoft.SharePoint.Client.WebParts Provides types and members for managing Web Parts within Web Parts

    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspxhttp://msdn.microsoft.com/en-us/library/aa979690.aspxhttp://msdn.microsoft.com/en-us/library/aa979690.aspxhttp://msdn.microsoft.com/en-us/library/aa979690.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.clientobject.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.clientobject.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.clientobject.aspxhttp://msdn.microsoft.com/en-us/library/ff410042.aspxhttp://msdn.microsoft.com/en-us/library/ff410042.aspxhttp://msdn.microsoft.com/en-us/library/ff410042.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.utilities.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.utilities.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.webparts.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.webparts.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.webparts.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.utilities.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.aspxhttp://msdn.microsoft.com/en-us/library/ff410042.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.clientobject.aspxhttp://msdn.microsoft.com/en-us/library/aa979690.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.aspx
  • 8/3/2019 Client Object Model Examples

    2/29

    2 SharePoint 2010 Client Object Model

    pages.

    Microsoft.SharePoint.Client.Workflow Provides types and members for managing workflow templates and

    workflow associations.

    The members of the Microsoft.SharePoint.Client.Application namespace are reserved for internal use and not

    intended to be used directly from your code.

    Namespaces of the ECMAScript (JavaScript, JScript) object model.

    Namespace ECMAScript File

    CUI Namespace CUI.js, SP.UI.Rte.js

    CUI.Controls Namespace CUI.js

    CUI.Page Namespace CUI.js, SP.UI.Rte.js

    SP Namespace SP.Core.js, SP.js, SP.Ribbon.js, SP.Runtime.js

    SP.ListOperation Namespace SP.Core.js

    SP.Ribbon Namespace SP.Ribbon.js

    SP.Ribbon.PageState Namespace SP.Ribbon.js

    SP.UI Namespace SP.Core.js, SP.js, SP.UI.Dialog.js

    SP.Utilities Namespace SP.Core.js, SP.js, SP.Exp.js

    SP.WebParts Namespace SP.js

    SP.Workflow Namespace SP.js

    Examples on

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.SharePoint.Client;

    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.workflow.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.workflow.aspxhttp://msdn.microsoft.com/en-us/library/ff408756.aspxhttp://msdn.microsoft.com/en-us/library/ff408756.aspxhttp://msdn.microsoft.com/en-us/library/ff408532.aspxhttp://msdn.microsoft.com/en-us/library/ff408532.aspxhttp://msdn.microsoft.com/en-us/library/ff411766.aspxhttp://msdn.microsoft.com/en-us/library/ff411766.aspxhttp://msdn.microsoft.com/en-us/library/ee557057.aspxhttp://msdn.microsoft.com/en-us/library/ee557057.aspxhttp://msdn.microsoft.com/en-us/library/ff410358.aspxhttp://msdn.microsoft.com/en-us/library/ff410358.aspxhttp://msdn.microsoft.com/en-us/library/ee549700.aspxhttp://msdn.microsoft.com/en-us/library/ee549700.aspxhttp://msdn.microsoft.com/en-us/library/ee547686.aspxhttp://msdn.microsoft.com/en-us/library/ee547686.aspxhttp://msdn.microsoft.com/en-us/library/ee552096.aspxhttp://msdn.microsoft.com/en-us/library/ee552096.aspxhttp://msdn.microsoft.com/en-us/library/ee549589.aspxhttp://msdn.microsoft.com/en-us/library/ee549589.aspxhttp://msdn.microsoft.com/en-us/library/ee557858.aspxhttp://msdn.microsoft.com/en-us/library/ee557858.aspxhttp://msdn.microsoft.com/en-us/library/ee550060.aspxhttp://msdn.microsoft.com/en-us/library/ee550060.aspxhttp://msdn.microsoft.com/en-us/library/ee550060.aspxhttp://msdn.microsoft.com/en-us/library/ee557858.aspxhttp://msdn.microsoft.com/en-us/library/ee549589.aspxhttp://msdn.microsoft.com/en-us/library/ee552096.aspxhttp://msdn.microsoft.com/en-us/library/ee547686.aspxhttp://msdn.microsoft.com/en-us/library/ee549700.aspxhttp://msdn.microsoft.com/en-us/library/ff410358.aspxhttp://msdn.microsoft.com/en-us/library/ee557057.aspxhttp://msdn.microsoft.com/en-us/library/ff411766.aspxhttp://msdn.microsoft.com/en-us/library/ff408532.aspxhttp://msdn.microsoft.com/en-us/library/ff408756.aspxhttp://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.workflow.aspx
  • 8/3/2019 Client Object Model Examples

    3/29

    3 SharePoint 2010 Client Object Model

    namespace SP2010_Managed_ClientOM

    {

    class Program

    {

    static void Main(string[] args)

    {

    LoadSiteData();

    }

    private static void LoadSiteData()

    {

    string webUrl = "http://nb16";

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    //Loads all web properties.

    context.Load(web);

    //Execute the query and load the object into the response given in load() method.

    context.ExecuteQuery();

    Console.WriteLine(web.Title);

    Console.ReadLine();

    }

    }

    }

  • 8/3/2019 Client Object Model Examples

    4/29

    4 SharePoint 2010 Client Object Model

    2.

    string webUrl = "http://nb16";

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("Images");

    //Loads all List properties.

    context.Load(list);

    context.ExecuteQuery();

    Console.WriteLine("List Title" + list.Title + "List ID" + list.Id);

    Console.ReadLine();

    3. Load Quey example

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.SharePoint.Client;

    namespace Managed_ClientOM_LoadQuery

    {

    class Program

    {

    static void Main(string[] args)

  • 8/3/2019 Client Object Model Examples

    5/29

    5 SharePoint 2010 Client Object Model

    {

    LoadQueryUsage();

    }

    private static void LoadQueryUsage()

    {

    string webUrl = "http://nb16";

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    ListCollection lists = web.Lists;

    IEnumerable listCollection = context.LoadQuery(lists.Include(list => list.Title, list => list.Id,

    list => list.Fields.Include(field=>field.Title, field => field.InternalName)));

    context.ExecuteQuery();

    foreach (List list in listCollection.ToList())

    {

    Console.WriteLine("Title is " + list.Title + ", ID is " + list.Id);

    foreach (Field field in list.Fields)

    {

    Console.WriteLine("Field Title "+ field.Title + " Internal Name " + field.InternalName);

    }

    }

    Console.ReadLine();

    }

    }

    }

  • 8/3/2019 Client Object Model Examples

    6/29

    6 SharePoint 2010 Client Object Model

    4. Create Site

    private static void CreateSite()

    {

    string webUrl = "http://nb16";

    ClientContext clientContext = new ClientContext(webUrl);

    Web oWebsite = clientContext.Web;

    WebCreationInformation webCreateInfo = new WebCreationInformation();

    webCreateInfo.Title = "Rare Solutions Blog";

    webCreateInfo.Description = "Blog is about the Rare solutions.";

    webCreateInfo.Url = "RareSolutions";

    webCreateInfo.UseSamePermissionsAsParentSite = true;

    webCreateInfo.WebTemplate = "BLOG#0";

    Web oNewWebsite = oWebsite.Webs.Add(webCreateInfo);

    clientContext.Load(

    oNewWebsite,

    website => website.ServerRelativeUrl,

    website => website.Created);

    clientContext.ExecuteQuery();

  • 8/3/2019 Client Object Model Examples

    7/29

    7 SharePoint 2010 Client Object Model

    Console.WriteLine("Server-relative Url: {0} Created: {1}", oNewWebsite.ServerRelativeUrl,

    oNewWebsite.Created);

    Console.ReadLine();

    }

    5. Create a List

    static void Main(string[] args)

    {

    CreateList();

    }

    private static void CreateList()

    {

    string webUrl = "http://nb16";

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    //Add list to the site

    ListCreationInformation listCreation = new ListCreationInformation();

    listCreation.Title = "My List";

    listCreation.TemplateType = (int)ListTemplateType.GenericList;

    listCreation.Description = "My custom test list";

    List list = web.Lists.Add(listCreation);

    //Add fields to the list

    Field firstName = list.Fields.AddFieldAsXml("",

    true, AddFieldOptions.DefaultValue);

  • 8/3/2019 Client Object Model Examples

    8/29

    8 SharePoint 2010 Client Object Model

    Field lastName = list.Fields.AddFieldAsXml("", true,

    AddFieldOptions.DefaultValue);

    Field branchID = list.Fields.AddFieldAsXml("",

    true, AddFieldOptions.DefaultValue);

    //Add listitems to the list.

    ListItemCreationInformation listItemCreation = new ListItemCreationInformation();

    ListItem listItem = list.AddItem(listItemCreation);

    listItem["FirstName"] = "Venkat";

    listItem["LastName"] = "Ramavath";

    listItem["BranchID"] = 1;

    listItem["Title"] = "Venkat Ramavath";

    listItem.Update();

    listItem = list.AddItem(listItemCreation);

    listItem["FirstName"] = "Rare";

    listItem["LastName"] = "Solutions";

    listItem["BranchID"] = 2;

    listItem["Title"] = "Rare Solutions";

    listItem.Update();

    context.ExecuteQuery();

    }

    }

    }

    6. Retreving items from the List

    private static void LoadListItems()

    {

    string webUrl = "http://nb16";

  • 8/3/2019 Client Object Model Examples

    9/29

    9 SharePoint 2010 Client Object Model

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("Pages");

    CamlQuery caml = new CamlQuery();

    caml.ViewXml = "";

    ListItemCollection listItems = list.GetItems(caml);

    //Load all list items and all properties in the list item.

    context.Load(listItems);

    context.ExecuteQuery();

    foreach (ListItem listItem in listItems)

    {

    Console.WriteLine("Title is " + listItem["Title"]+ ", ID is" +listItem.Id);

    }

    Console.ReadLine();

    }

    7. CAML and LINQ

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.SharePoint.Client;

    namespace Managed_ClientOM_CAMLAndLINQ

  • 8/3/2019 Client Object Model Examples

    10/29

    10 SharePoint 2010 Client Object Model

    {

    class Program

    {

    static string webUrl = "http://nb16";

    static void Main(string[] args)

    {

    LoadDataUsingCAMLQuery();

    LoadDataUsingLINQ();

    }

    private static void LoadDataUsingLINQ()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("My List");

    CamlQuery query = new CamlQuery();

    query.ViewXml = "";

    ListItemCollection listItems = list.GetItems(query);

    context.Load(listItems, items => items.Include(item => item["Title"],

    item => item["FirstName"], item => item["LastName"], item => item["BranchID"]).Where(

    item => item.Id != 1));

    context.ExecuteQuery();

    foreach (ListItem listItem in listItems)

    {

    Console.WriteLine("Title is " + listItem["Title"] + ", Branch ID is " + listItem["BranchID"]);

  • 8/3/2019 Client Object Model Examples

    11/29

    11 SharePoint 2010 Client Object Model

    }

    Console.ReadLine();

    }

    private static void LoadDataUsingCAMLQuery()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("My List");

    CamlQuery caml = new CamlQuery();

    caml.ViewXml = @"

    Venkat

    10

    ";

    ListItemCollection listItems = list.GetItems(caml);

    //Load only properties you need.

    context.Load(listItems, items => items.Include(item => item["Title"],

    item => item["FirstName"], item => item["LastName"], item => item["BranchID"]));

  • 8/3/2019 Client Object Model Examples

    12/29

    12 SharePoint 2010 Client Object Model

    context.ExecuteQuery();

    foreach (ListItem listItem in listItems)

    {

    Console.WriteLine("Title is " + listItem["Title"]+ ", Branch ID is " +listItem["BranchID"]);

    }

    Console.ReadLine();

    }

    }

    }

    8.

    private static void LoadOnlyResultsYouNeed()

    {

    string webUrl = "http://nb16";

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    //Loads only two properties instead of all default properties from server.

    context.Load(web, w => w.Title, w => w.Description);

    context.ExecuteQuery();

    Console.WriteLine("Title is " + web.Title + ", Description is "+ web.Description);

    Console.ReadLine();

    }

    9. List Manipulations

    using System;

    using System.Collections.Generic;

  • 8/3/2019 Client Object Model Examples

    13/29

    13 SharePoint 2010 Client Object Model

    using System.Linq;

    using System.Text;

    using Microsoft.SharePoint.Client;

    namespace Managed_ClientOM_Manipulate_ClientObjects

    {

    class Program

    {

    static string webUrl = "http://nb16";

    static void Main(string[] args)

    {

    CreateList();

    UpdateList();

    CreateListItem();

    UpdateListItem();

    DeleteListItem();

    DeleteList();

    }

    private static void CreateList()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    //Add list to the site

    ListCreationInformation listCreation = new ListCreationInformation();

  • 8/3/2019 Client Object Model Examples

    14/29

    14 SharePoint 2010 Client Object Model

    listCreation.Title = "Test List";

    listCreation.TemplateType = (int)ListTemplateType.GenericList;

    listCreation.Description = "My custom test list";

    List list = web.Lists.Add(listCreation);

    //Add fields to the list

    Field firstName = list.Fields.AddFieldAsXml("",

    true, AddFieldOptions.DefaultValue);

    Field lastName = list.Fields.AddFieldAsXml("", true,

    AddFieldOptions.DefaultValue);

    Field branchID = list.Fields.AddFieldAsXml("",

    true, AddFieldOptions.DefaultValue);

    //Add listitems to the list.

    ListItemCreationInformation listItemCreation = new ListItemCreationInformation();

    ListItem listItem = list.AddItem(listItemCreation);

    listItem["FirstName"] = "Venkat";

    listItem["LastName"] = "Ramavath";

    listItem["BranchID"] = 1;

    listItem["Title"] = "Venkat Ramavath";

    listItem.Update();

    listItem = list.AddItem(listItemCreation);

    listItem["FirstName"] = "Rare";

    listItem["LastName"] = "Solutions";

    listItem["BranchID"] = 2;

    listItem["Title"] = "Rare Solutions";

    listItem.Update();

    listItem["FirstName"] = "Venkat";

    listItem["LastName"] = "B";

  • 8/3/2019 Client Object Model Examples

    15/29

    15 SharePoint 2010 Client Object Model

    listItem["BranchID"] = 3;

    listItem["Title"] = "Venkat B";

    listItem.Update();

    listItem = list.AddItem(listItemCreation);

    listItem["FirstName"] = "Venkat";

    listItem["LastName"] = "Kumar";

    listItem["BranchID"] = 4;

    listItem["Title"] = "Venkat Kumar";

    listItem.Update();

    context.ExecuteQuery();

    }

    private static void UpdateList()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("Test List");

    context.Load(list);

    list.Description = "Test list description";

    list.Update();

    context.ExecuteQuery();

    }

    private static void DeleteList()

  • 8/3/2019 Client Object Model Examples

    16/29

    16 SharePoint 2010 Client Object Model

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("Test List");

    context.Load(list);

    list.DeleteObject();

    context.ExecuteQuery();

    }

    private static void CreateListItem()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("Test List");

    ListItemCreationInformation listItemCreation = new ListItemCreationInformation();

    ListItem listItem = list.AddItem(listItemCreation);

    listItem["FirstName"] = "Hello";

    listItem["LastName"] = "World";

    listItem["BranchID"] = 99;

    listItem["Title"] = "Hello World";

    listItem.Update();

    context.ExecuteQuery();

    }

  • 8/3/2019 Client Object Model Examples

    17/29

    17 SharePoint 2010 Client Object Model

    private static void UpdateListItem()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("Test List");

    CamlQuery camlQuery = new CamlQuery();

    camlQuery.ViewXml = @"

    99

    1

    ";

    ListItemCollection listItems = list.GetItems(camlQuery);

    context.Load(listItems, items => items.Include(item => item["FirstName"], item =>

    item["LastName"],

    item => item["BranchID"], item => item["Title"]));

    context.ExecuteQuery();

    foreach (ListItem listItem in listItems.ToList())

    {

    if (listItem != null)

    {

  • 8/3/2019 Client Object Model Examples

    18/29

    18 SharePoint 2010 Client Object Model

    listItem["FirstName"] = "Hello !!!";

    listItem["LastName"] = "World !!!";

    listItem["BranchID"] = 99;

    listItem["Title"] = "Hello !!!";

    listItem.Update();

    }

    }

    context.ExecuteQuery();

    }

    private static void DeleteListItem()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    List list = web.Lists.GetByTitle("Test List");

    CamlQuery camlQuery = new CamlQuery();

    camlQuery.ViewXml = @"

    99

  • 8/3/2019 Client Object Model Examples

    19/29

    19 SharePoint 2010 Client Object Model

    1

    ";

    ListItemCollection listItems = list.GetItems(camlQuery);

    context.Load(listItems, items => items.Include(item => item["FirstName"], item =>

    item["LastName"],

    item => item["BranchID"], item => item["Title"]));

    context.ExecuteQuery();

    ListItem listItem = listItems[0];

    if (listItem != null)

    {

    listItem.DeleteObject();

    }

    context.ExecuteQuery();

    }

    }

    }

    10. Paging For Large Lists

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.SharePoint.Client;

    namespace Managed_ClientOM_Paging_ForLarge_Lists

  • 8/3/2019 Client Object Model Examples

    20/29

    20 SharePoint 2010 Client Object Model

    {

    class Program

    {

    static void Main(string[] args)

    {

    LoadDataByPaging();

    }

    private static void LoadDataByPaging()

    {

    string webUrl = "http://nb16";

    ClientContext context = new ClientContext(webUrl);

    List list = context.Web.Lists.GetByTitle("Test List");

    // First, add 20 items to Client API Test List so that there are

    // enough records to show paging.

    ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

    for (int i = 0; i < 20; i++)

    {

    ListItem listItem = list.AddItem(itemCreateInfo);

    listItem["Title"] = String.Format("Venkat {0}", i);

    listItem["FirstName"] = String.Format("FirstName {0}", i);

    listItem["LastName"] = String.Format("LastName {0}", i);

    listItem["BranchID"] = i;

    listItem.Update();

  • 8/3/2019 Client Object Model Examples

    21/29

    21 SharePoint 2010 Client Object Model

    }

    context.ExecuteQuery();

    // This example shows paging through the list ten items at a time.

    // In a real-world scenario, you would want to limit a page to 2000 items.

    ListItemCollectionPosition itemPosition = null;

    while (true)

    {

    CamlQuery camlQuery = new CamlQuery();

    camlQuery.ListItemCollectionPosition = itemPosition;

    camlQuery.ViewXml =

    @"

    5

    ";

    ListItemCollection listItems = list.GetItems(camlQuery);

    context.Load(listItems);

    context.ExecuteQuery();

    itemPosition = listItems.ListItemCollectionPosition;

    foreach (ListItem listItem in listItems)

  • 8/3/2019 Client Object Model Examples

    22/29

    22 SharePoint 2010 Client Object Model

    Console.WriteLine(" Item Title: {0}", listItem["Title"]);

    if (itemPosition == null)

    break;

    Console.WriteLine(itemPosition.PagingInfo);

    Console.WriteLine();

    }

    Console.ReadLine();

    }

    }

    }

    11. Manipulating Site

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.SharePoint.Client;

    namespace Managed_ClientOM_Manipulate_Site

    {

    class Program

    {

    static string webUrl = "http://nb16";

    static void Main(string[] args)

    {

  • 8/3/2019 Client Object Model Examples

    23/29

    23 SharePoint 2010 Client Object Model

    UpdateSite();

    //Uncomment the belo line to delete a specific web site.

    //DeleteSite();

    }

    private static void UpdateSite()

    {

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    var query = from w in web.Webs where w.Title == "Rare Solutions" select w;

    IEnumerable result = context.LoadQuery(query.Include(w => w.Title, w => w.Id));

    context.ExecuteQuery();

    Web website = result.ElementAt(0);

    if (website != null)

    {

    website.Title = "Rare Solutions";

    website.Update();

    }

    context.ExecuteQuery();

    Console.WriteLine("Web site title updated" + website.Title);

    Console.ReadLine();

    }

    private static void DeleteSite()

    {

  • 8/3/2019 Client Object Model Examples

    24/29

    24 SharePoint 2010 Client Object Model

    ClientContext context = new ClientContext(webUrl);

    Web web = context.Web;

    var query = from w in web.Webs where w.Title == "Rare Solutions" select w;

    IEnumerable result = context.LoadQuery(query.Include(w => w.Title, w => w.Id));

    context.ExecuteQuery();

    Web website = result.ElementAt(0);

    if (website != null)

    {

    website.DeleteObject();

    }

    context.ExecuteQuery();

    Console.WriteLine("Web site deleted");

    Console.ReadLine();

    }

    }

    }

    12. Client Object Model Example Using Silverlight

    using System;

    using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;

    using System.Windows.Controls;using System.Windows.Documents;

  • 8/3/2019 Client Object Model Examples

    25/29

    25 SharePoint 2010 Client Object Model

    using System.Windows.Input;

    using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using Microsoft.SharePoint.Client;

    namespace Guardian.SharePoint2010{

    publicpartialclassMainPage : UserControl{

    ListItemCollection _projectItems;

    public MainPage()

    {

    InitializeComponent(); var context = newClientContext(@http://SharePoint2010.Guardian.com/ );

    context.Load(context.Web);

    var projects = context.Web.Lists.GetByTitle("Projects");var query = new Microsoft.SharePoint.Client. CamlQuery();

    query.ViewXml =@"

    ";

    _projectItems = projects.GetItems(query);

    context.Load(_projectItems);context.ExecuteQueryAsync(Succeeded, Failed);

    }

    void Succeeded(object s, ClientRequestSucceededEventArgs c){

    Dispatcher.BeginInvoke(BindData);}

    void Failed(object s, ClientRequestFailedEventArgs c){

    }

    privatevoid BindData(){

    var list = newList();foreach (ListItem li in _projectItems){

    list.Add(newProject{

    Title = li["Title"].ToString(),Target = Convert.ToInt32(li["Target"]),

    http://sharepoint2010.guardian.com/http://sharepoint2010.guardian.com/http://sharepoint2010.guardian.com/
  • 8/3/2019 Client Object Model Examples

    26/29

    26 SharePoint 2010 Client Object Model

    Current = Convert.ToInt32(li["Current"])

    });}

    dataGrid1.DataContext = _projectItems;

    }

    publicclassProject

    {publicString Title { get; set; }publicInt32 Target { get; set; }publicInt32 Current { get; set; }

    }}

    }

    Client Object Model for JavaScript (ECMAScript)

    At first use Visual Studio 2010 to create a SharePoint web part project. As a result, VS2010

    will open a ascx control for you on the designer.

    1. Add reference to js file:

    To use Client OM, add an entry like below in your web part ascx control. For your information,

    theres an debug version of the sp.js called sp.debug.js which you can use for debugging butshould not be used in production.

    Here, OnDemand means whether the sp.js file need to be loaded on demand (not in page load) or

    not.

    2. Add FormDigest tag:

    If your code modifies SharePoint content add a FormDigest control inside your page. The

    FormDigest add a security token inside your page based on user, site and time. Once the page is

    posted back the security token is validated. Once the security token is generated its valid for aconfigurable amount of time. Add the FormDigest inside tag, as shown

    below:

    3. Use Client OM to retrieve data:

  • 8/3/2019 Client Object Model Examples

    27/29

    27 SharePoint 2010 Client Object Model

    Now you can use SharePoint ECMAScript library. Lets dissect the code snippet below. The

    first thing in using this library is that you need to get the ClientContext (just like SPContext).

    Then the context.get_web returns the current web (just like SPContext.Current.Web). Then client

    contexts load method is invoked passing the web object. Then the executequery method is

    invoked asynchronously passing two functions: onSuccess and OnFailed which will be called on

    success and fail correspondingly.

    function getWebProperties() {

    var ctx = new SP.ClientContext.get_current();

    this.web = ctx.get_web();

    ctx.load(this.web);

    ctx.executeQueryAsync(Function.createDelegate(this,

    this.onSuccess),

    Function.createDelegate(this, this.onFail));

    }

    function onSuccess(sender, args) {

    alert('web title:' + this.web.get_title() + '\n ID:' +

    this.web.get_id() +

    '\n Created Date:' + this.web.get_created());

    }

    function onFail(sender, args) {

    alert('failed to get list. Error:'+args.get_message());

    }

    By calling getWebProperties method from any web part, you can get the current webs title, idand creation date.

    4. Load minimal data you need:

    In the above code snippet, the Ctx.load method is invoked with only one parameter (web).

    The load method will load all properties of the web object. But we are only using Id, Title

    and Created Date properties. If you know which properties you are interested in, you can

    pass the properties names in the load method and only those properties will be loaded. For

    example the following load method will return only ID, Title and Created Date.

    Collapse |Copy Code

    ctx.load(this.web,'Title','Id','Created');

    Remember, here the properties names are properties of SPWeb. You need to pass Title instead of

    title. The properties name uses CAML casing. You can get the full lists of ECMAScript

    namespaces, object , properties following thelink on MSDN. The document is not final yet and

    http://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspxhttp://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspxhttp://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspxhttp://msdn.microsoft.com/en-us/library/ee538253%28office.14%29.aspxhttp://msdn.microsoft.com/en-us/library/ee538253%28office.14%29.aspxhttp://msdn.microsoft.com/en-us/library/ee538253%28office.14%29.aspxhttp://msdn.microsoft.com/en-us/library/ee538253%28office.14%29.aspxhttp://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspx
  • 8/3/2019 Client Object Model Examples

    28/29

    28 SharePoint 2010 Client Object Model

    may be changed. You can also look into the sp.debug.js file in the folder Program

    Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS, to

    get an idea of objects, properties and methods of ECMAScript Client OM.

    5. Execute your Javascript function after sp.js is loaded:

    Sometimes you may need to execute your Javascript (that uses ECMAScript Client OM) on page

    load in the browser. But since your Javascript is using sp.js file and if the sp.js file is not loaded

    yet (since to lazy loading nature of sp.js), when your custom Javascriptwill be executing, youll

    get your Javascript function not executed. In this case you need to make sure your Javascript

    code runs after sp.js finishes loading. You can do so by putting your Javascript method call

    inside a js function as shown below:

    Collapse |Copy Code

    ExecuteOrDelayUntilScriptLoaded(myjsfucntion, "sp.js");

    Putting your Javascript function (i.e., myjsfunction) inside the ExecuteOrDelyUntilScriptLoaded

    method delays your method call until the sp.js file is loaded.

    6. Update with ECMAScript Library:

    You can use the Client OM to update SharePoint contents. The following code snippet shows

    how to update web title.

    function updateTitle() {var ctx = new SP.ClientContext.get_current();

    this.web = ctx.get_web();

    web.set_title('UpdatedTitle');

    this.web.update();

    ctx.executeQueryAsync(Function.createDelegate(this,

    this.onUpdate),

    Function.createDelegate(this, this.onFail));

    }

    function onUpdate(sender, args) {

    alert('title updated');

    }function onFail(sender, args) {

    alert('failed to update title. Error:'+args.get_message());

    }

    http://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspxhttp://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspxhttp://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspxhttp://www.codeproject.com/Articles/60348/SharePoint-2010-Client-Object-Model-for-JavaScript.aspx
  • 8/3/2019 Client Object Model Examples

    29/29

    By calling the updateTitle method from any web part or SharePoint application pages, you can

    change the title of current web site (where the web part or application page is deployed). For

    your information, in ECMAScript Client OM, to get an property use get_propertyName and to

    set a property use set_propertyName. To update list with ECMAScript library you need to add

    FormDigest tag.

    Use JQuery with ECMAScript

    You can use JQuery with ECMAScript without any conflict. As usual, you need to add jquery.js

    file reference to your page/web part or in master page. Then you can use JQuery as like normal

    asp.net applications. But make sure that if you need to execute any Javascript function on page

    load event, you put this inside ExecuteOrDelayUntilScriptLoaded function.

    Deployment Consideration

    SharePoint provides two sets ofJavascript file: minified and unminified/debug version. For

    example sp.js file is minified and sp.debug is minified and debug version. The default masterpage in SharePoint has a scriptmanager in the page and whose ScriptMode is set to auto, as a

    result the minified version of js file loaded. If you want to use debug version you can add the

    in the section of the web.config. In the production

    you need to remove this entry to make sure minified version is used. The ECMAScript supported

    in the following browsers:

    Microsoft Internet Explorer 7.0 or greater. Firefox 3.5 or greater Safari 4.0 or greater