Académique Documents
Professionnel Documents
Culture Documents
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 and members that are contained in the Microsoft.SharePoint namespace 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 the Microsoft.SharePoint namespace of the serverside 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 Foundation Web 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 the ClientObject class (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 Microsoft.SharePoint.Client Description 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
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.
ECMAScript File
CUI.js, SP.UI.Rte.js CUI.js CUI.js, SP.UI.Rte.js SP.Core.js, SP.js, SP.Ribbon.js, SP.Runtime.js SP.Core.js SP.Ribbon.js SP.Ribbon.js SP.Core.js, SP.js, SP.UI.Dialog.js SP.Core.js, SP.js, SP.Exp.js SP.js SP.js
Examples on
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint.Client;
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(); } } }
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();
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint.Client;
{ LoadQueryUsage(); }
private static void LoadQueryUsage() { string webUrl = "http://nb16"; ClientContext context = new ClientContext(webUrl); Web web = context.Web; ListCollection lists = web.Lists; IEnumerable<List> 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(); } } }
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";
clientContext.ExecuteQuery();
5. Create a List
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("<Field Type='Text' DisplayName='FirstName' />", true, AddFieldOptions.DefaultValue);
Field lastName = list.Fields.AddFieldAsXml("<Field Type='Text' DisplayName='LastName' />", true, AddFieldOptions.DefaultValue); Field branchID = list.Fields.AddFieldAsXml("<Field Type='Number' DisplayName='BranchID' />", 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";
ClientContext context = new ClientContext(webUrl); Web web = context.Web; List list = web.Lists.GetByTitle("Pages"); CamlQuery caml = new CamlQuery(); caml.ViewXml = "<View />"; 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(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint.Client;
namespace Managed_ClientOM_CAMLAndLINQ
{ 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 = "<View />"; 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"]);
10
} 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 = @"<View> <Query> <Where> <Eq> <FieldRef Name='FirstName'/> <Value Type='Text'>Venkat</Value> </Eq> </Where> </Query> <RowLimit>10</RowLimit> </View>"; 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"]));
11
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;
12
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();
13
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("<Field Type='Text' DisplayName='FirstName' />", true, AddFieldOptions.DefaultValue); Field lastName = list.Fields.AddFieldAsXml("<Field Type='Text' DisplayName='LastName' />", true, AddFieldOptions.DefaultValue); Field branchID = list.Fields.AddFieldAsXml("<Field Type='Number' DisplayName='BranchID' />", 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";
14
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(); }
15
{ 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(); }
16
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 = @"<View> <Query> <Where> <Eq> <FieldRef Name='BranchID'/> <Value Type='Text'>99</Value> </Eq> </Where> </Query> <RowLimit>1</RowLimit> </View>"; 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) {
17
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 = @"<View> <Query> <Where> <Eq> <FieldRef Name='BranchID'/> <Value Type='Text'>99</Value> </Eq> </Where> </Query>
18
<RowLimit>1</RowLimit> </View>"; 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(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint.Client;
namespace Managed_ClientOM_Paging_ForLarge_Lists
19
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();
20
} 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 = @"<View> <ViewFields> <FieldRef Name='Title'/> <FieldRef Name='FirstName'/> <FieldRef Name='LastName'/> <FieldRef Name='BranchID'/> </ViewFields> <RowLimit>5</RowLimit> </View>"; ListItemCollection listItems = list.GetItems(camlQuery); context.Load(listItems); context.ExecuteQuery(); itemPosition = listItems.ListItemCollectionPosition; foreach (ListItem listItem in listItems)
21
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) {
22
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<Web> 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(); }
23
ClientContext context = new ClientContext(webUrl); Web web = context.Web; var query = from w in web.Webs where w.Title == "Rare Solutions" select w; IEnumerable<Web> 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(); } } }
24
namespace Guardian.SharePoint2010 { public partial class MainPage : UserControl { ListItemCollection _projectItems; public MainPage() { InitializeComponent(); var context = new ClientContext(@http://SharePoint2010.Guardian.com/); context.Load(context.Web); var projects = context.Web.Lists.GetByTitle("Projects"); var query = new Microsoft.SharePoint.Client.CamlQuery(); query.ViewXml = @"<View> <ViewFields> <FieldRef Name='Title' /> <FieldRef Name='Target' /> <FieldRef Name='Current' /> </ViewFields> </View>"; _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) { } private void BindData() { var list = new List<Project>(); foreach (ListItem li in _projectItems) { list.Add(new Project { Title = li["Title"].ToString(), Target = Convert.ToInt32(li["Target"]),
25
Current = Convert.ToInt32(li["Current"]) }); } dataGrid1.DataContext = _projectItems; } public class Project { public String Title { get; set; } public Int32 Target { get; set; } public Int32 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 but should not be used in production.
<SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true" Localizable="false" />
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 a configurable amount of time. Add the FormDigest inside <form></form> tag, as shown below:
<SharePoint:FormDigest runat="server" />
3. Use Client OM to retrieve data:
26
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.
<script type="text/Javascript"> 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()); } </script>
By calling getWebProperties method from any web part, you can get the current webs title, id and 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 the link on MSDN. The document is not final yet and
27
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 Javascript will 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.
<script
type="text/ Javascript "> 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()); } </script>
28
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.
Deployment Consideration
SharePoint provides two sets of Javascript file: minified and unminified/debug version. For example sp.js file is minified and sp.debug is minified and debug version. The default master page 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 <deployment retail="false" /> in the <system.web> 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
29