Module 5 - Code Snippets: Accessing SharePoint 2010 Data with Client-Side APIs

The following code shows how to use the client object model from a console application. The code first of all lists the Web templates available for a specific Web, and then creates a new Web based on a specific template:

ClientContext clientCtx = new ClientContext("https://intranet.contoso.com");
Site thatSite = clientCtx.Site;
clientCtx.Load(thatSite.RootWeb);
Web thatWeb = thatSite.RootWeb;
WebTemplateCollection templates =
thatWeb.GetAvailableWebTemplates(1033, true);
clientCtx.Load(templates);
clientCtx.ExecuteQuery();
foreach (WebTemplate template in templates)
{
Console.WriteLine(template.Id + " : "
+ template.Name + " : "
+ template.Title);
}
WebCreationInformation webInfo = new WebCreationInformation();
webInfo.Description = "My client-created Web";
webInfo.Title = "Created by Client OM";
webInfo.Url = "Client3";
webInfo.Language = 1033;
webInfo.UseSamePermissionsAsParentSite = true;
webInfo.WebTemplate = "MPS#2";
Web newWeb = thatWeb.Webs.Add(webInfo);
clientCtx.ExecuteQuery();
clientCtx.Dispose();
Console.WriteLine("Web was created");

 

The following code shows how to use the client object model from a Windows Presentation Foundation (WPF) application. The code enumerates the lists in a Web, and adds them to a WPF Expander control.
Note: The code relies on there being an Expander control named expander1 on the WPF form.

try
{
ClientContext clientCtx = new ClientContext(siteUrl.Text);
Web thatWeb = clientCtx.Web;
clientCtx.Load(thatWeb);
clientCtx.Load(thatWeb.Lists);
clientCtx.Load(thatWeb, lists => lists.Lists.Where(list => list.Title != null));
clientCtx.ExecuteQuery();
AllLists.Items.Clear ();
foreach (Microsoft.SharePoint.Client.List lst in thatWeb.Lists)
{
AllLists.Items.Add(lst.Title);
}
clientCtx.Dispose();
}
catch (Exception ex)
{
AllLists.Items.Clear ();
AllLists.Items.Add(ex.Message);
}
expander1.IsExpanded = false;

Note: To see code samples that use the client object model from a Silverlight application, please see:
https://blogs.msdn.com/pandrew/pages/GettingStarted2010Snippets8.aspx