Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client Object


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Client object model focuses on the most relevant APIs for client-side development. But limiting the size of the client libraries reduces the amount of time that is required to download the libraries in the Silverlight and ECMAScript contexts. Http throttling is a new feature in SharePoint 2010 that allows the server to “back off” of serving requests when it is too busy. Requests generated prior to the server entering into the throttling mode will be completed. Access an External List using Office Add-ins• Chose Word 2010 Document Add-in• Chose the document• Added a WPF User Control• Added references• Added using statements• Created a class for data-binding• Instantiated a ClientContext• Retrieved List data
  • Client APIs are very intuitive .The naming convention rests very similar to the Server OM. “SP” prefix in the client objects has been dropped.
  • Client communicates to the server thorough Client OM which under the hood uses Client.svc WCF. Client.svc service uses Server OM as per client request and returns result to the client in JSON format.
  • You “get connected” to the data in SharePoint with the new ClientContext object.
  • The items parameter of the lambda expression is of type ListItemCollection . It does not contain an indexed property that allows us to specify which properties to load for items in the collection. Parameters to lambda expressions in the Include extension method are of type of the items of the collection. Therefore, you can specify the properties that you want to load for each item in the collection.
  • For instance, you can query for all items in a project list that are assigned to a certain person, and separately query for all items that have an estimated hours that is larger than a certain threshold, and access both result sets at the same time.
  • think as a .NET class or structure that is marshaled by value
  • (think as a .NET class or structure that is marshaled reference)
  • Initializinganother ClientContext to the same SP site doesn’t allow you to useobjectsfrom one client context with the other one. Client OM remembers that the list object is the one that was initialized by using the GetByTitle method, and that the client object model should execute the CAML query on that same list object after the list object is retrieved from the SharePoint database. The code uses that list client object to call the List.GetItems method, and then calls the ExecuteQuery method again. Any class that derives from the ClientObject class has these semantics.
  • Before executing Client Object Model calls you need to get a ClientContext object through which calls can be made.
  • The Dispatcher maintains a prioritized queue of work items for a specific thread.Dispatcher.BeginInvoke method executes a delegate asynchronously on the thread the Dispatcher is associated with.
  • Calling Load() method won't load the object immediately. We need explicitly call it by using executeQueryAsync() method. It has the success method and the failure method
  • You can obtain the PublicKeyToken value for the current SharePoint Foundation deployment from the default.aspx file in the %ProgramFiles% Common FilesMicrosoft Sharedweb server extensions14TEMPLATESiteTemplatessts folder, or from information provided for the Microsoft.SharePoint assembly at Local_Drive:WINDOWSWINNTassembly in Windows Explorer. Once the page is posted back the security token is validated. Once the security token is generated it’s valid for a configurable amount of time. By default, the ScriptMode property of ScriptManager is set to auto, as a result the minified version of js file loaded.
  • REST is a term coined by Roy Fielding in his Ph.D. dissertation [1] to describe an architecture style of networked systems. In WSS 3.0 you were able to access list data with the SOAP based Lists.asmx. This technique worked well for .Net desktop apps or server side application pages, but not so well with client side JavaScript.
  • For instance if you modify the row level permissions for a list item to deny read permissions to a user then ListData.svc will not return that list item for that user. If you try to access the URL for that list item directly SharePoint returns a 404. If you try to modify or delete a list item you don't have permissions to modify then SharePoint returns a 401 Unauthorized.
  • Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client Object

    1. 1. Developing solutions for SP2010 using the Client Object Model<br />Lyudmila Zharova<br />SharePoint Developer at MRM Worlwide<br /><br />21/7/2010<br />
    2. 2. AGENDA<br />The goal of Client Object Model <br /> Supported Areas<br /> Limitations<br />Client Object Model Overview<br /> Server and Client Objects Comparison<br /> How the Client-Side Object Model Works<br /> ClientContext <br /> Rules of using Client OM<br /> Object Identity<br /> Authentication <br />Implementing the Client Object Model<br /> .NET Client OM<br /> Silverligt Client OM<br /> ECMAScript Client OM<br />Calling REST services in SharePoint 2010<br />Demo<br />Links<br />
    3. 3. The goal of Client Object Model<br />Provides an object-oriented system for interoperating with SharePoint data without installing code on the installing code on the server <br />Provides complete API instead of more services and PRC protocols<br />Enable 3rd parties to create add-ons for the Microsoft Office products that enable new features.<br />Consistent developer experience across platforms (.NET, Silverlight, ECMAScript)<br /> - .NET Managed Applications (console, window, web applications , which are not running<br /> inside SharePoint Context; not earlier than Microsoft .NET Framework 3.5)<br /> - Silverlight applications (not earlier than Silverlight 2.0)<br /> - JavaScript (called ECMAScript) JavaScript APIs are only available for applications hosted<br /> inside SharePoint (web parts deployed in SharePoint site can use these APIs<br /> for accessing SharePoint from browser)<br /> Designed to minimize the number of round trips that must be implemented for common actions<br />
    4. 4. Supported Areas and Limitations:<br />Supported Areas:<br />With Client OM you can perform the most common CRUD operations in the following areas: <br /><ul><li>Site Collections, Sites, Lists, Views, List Schemas, List Items
    5. 5. Files and Folders
    6. 6. Web Parts
    7. 7. Security
    8. 8. Content Types
    9. 9. Site Templates and Site Collection Operations </li></ul>Access an External List using Office Add-ins<br />Limitations<br />To improve security and performance Client OM does not contain all the types and members that are represented in the server object model (no administration objects)<br /> Client APIs are scoped not higher than the site collection <br /> No elevation of privilege capabilities<br /> Requests are throttled (managed on a per web application basis in central admin)<br />
    10. 10. Client Object Model Overview <br />The client APIs provide developers with a subset of the Microsoft.SharePoint namespace which is based on the server-side object model <br />SharePoint Foundation 2010 managed client OM uses the same legacy naming pattern for site collections and sites as the server object model<br />
    11. 11. How the Client-Side Object Model Works<br />Client object model bundles the uses of the APIs into XML and returns result to the client in JSON format<br />
    12. 12. ClientContext<br />All three client object models have a single center of gravity: the ClientContext object<br /> - Provide connection to SharePoint data<br /> - Manages authentication<br /> - Issues queries<br /> - Handles the execution of code on the server queued by the client<br />Creating an instance of the ClientContext object is the first step in any client object model solution<br /> ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection")<br /> ClientContext clientContext = ClientContext.Current; <br /> var clientContext = new SP.ClientContext.get_current(); <br />
    13. 13. Rules of using Client OM<br />The Client OM provides 2 different mechanisms for data retrieval: in-place load - Load(), and queryable load - LoadQuery() <br />Call Load() or LoadQuery() Before Accessing Value Properties<br />ClientContext clientContext = new ClientContext("http://sp2010");<br /> Web oWebsite = clientContext.Web;<br /> Console.WriteLine(oWebsite.Title);<br />PropertyOrFieldNotInitializedException <br />(initializing a site is not enough to start working with object)<br />Initialize and load all the properties filled with data:<br />clientContext.Load(oWebsite)<br />Use a Lambda expression or Link to load the properties in a smaller result set <br /> and a more manageable object <br />Specify the properties in the lambda expression that you add directly in the Load method if<br />the Client OM loads certain properties of client object (not a collection of them)<br />clientContext.Load(oWebsite, w=>w.Title, w=>w.Created);<br />
    14. 14. Rules of using Client OM<br />Include System.Linq namespace to use Link <br />using System.Linq;<br /> Note: You are using LINQ to Objects, not the LINQ to SharePoint provider<br />        ListCollection listCollection = clientContext.Web.Lists;<br />        clientContext.Load(<br />            listCollection,<br />            lists => lists<br />                .Include(<br />                    list => list.Title,<br />                    list => list.Hidden)<br />                . Where(list => ! list.Hidden));<br />You are using LINQ to Objects, not the LINQ to SharePoint provider<br /> which can only be used when you write code against the server object model.<br />
    15. 15. Rules of using Client OM<br />Do not use the IQueryable<T>.Where when querying ListItem objects (use CAML query instesd)<br /> ClientContext clientContext = new ClientContext<br /> ("http://sp2010");<br /> List list = clientContext.Web.Lists.GetByTitle("Client API Test List");<br /> CamlQuery camlQuery = new CamlQuery();<br /> camlQuery.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='Category'/><br /> <Value Type='Text'>Development</Value><br /> </Eq></Where></Query><RowLimit>100</RowLimit></View>";<br /> ListItemCollection listItems = list.GetItems(camlQuery);<br /> clientContext.Load(listItems,<br />items => items // is of type ListItemCollection<br /> .Include(item=> item["Title"], // is of type item<br /> item => item["Category"],<br /> item => item["Estimate"]));<br />Use the Include extension method, and pass the lambda expressions to specify your desired properties if Client OM loads certain properties of each item in a collection of client objects<br />
    16. 16. Rules of using Client OM<br />Consider the different semantics of the LoadQuery() and the Load() methods<br />
    17. 17. Rules of using Client OM<br />Before accessing any of the properties of the object, the request must be sent<br /> to the server for processing by using the ClientContext.ExecuteQuery() method <br /> (or the ExecuteQueryAsync() method in the Silverlight <br /> and ECMAScript client object model)<br />ClientContext clientContext =<br /> new ClientContext("http://sp2010");<br /> Web site = clientContext.Web;<br /> ListCollection lists = site.Lists;<br /> IEnumerable<List> newListCollection = clientContext.LoadQuery(<br /> lists.Include(<br /> list => list.Title,<br /> list => list.Id,<br /> list => list.Hidden));<br /> clientContext.ExecuteQuery();<br /> foreach (List list in newListCollection)<br /> Console.WriteLine("Title: {0} Id: {1}", <br /> list.Title.PadRight(40), list.Id.ToString("D")); <br /> The LoadQuery method returns a new list collection that you can iterate through. <br /> It has a type of IEnumerable<List>instead of ListCollection.<br />
    18. 18. Rules of using Client OM<br />Value Objects Cannot Be Used Across Methods in the same Query;<br />- A value object is any object that inherits from the ClientValueObject class<br /> - Value objects have properties but do not have methods<br /> - FieldUrlValue and other field’s value objects are value objects<br />ClientContext clientContext = new ClientContext("http://sp2010");<br /> Web oWebsite = clientContext.Web;<br /> clientContext.Load(oWebsite, <br /> w => w.Title); <br />clientContext.ExecuteQuery();<br /> ListCreationInformation listCreationInfo = <br /> new ListCre ationInformation();<br /> listCreationInfo.TemplateType = 104;<br /> listCreationInfo.Title = oWebsite.Title;<br /> List oList = oWebsite.Lists.Add(listCreationInfo);<br /> clientContext.ExecuteQuery();<br />PropertyOrFieldNotInitializedException<br />
    19. 19. Rules of using Client OM<br />Client Objects Can Be Used Across Methods in the same Query<br /> - Client objects returned through method or property can be used as a parameter<br /> for another method or property call in the same query<br /> - ListItem is a client object<br /> - Microsoft SharePoint Foundation 2010 keeps track of how objects are created <br /> by using object paths.<br /> //object path of oItem results from using several members:<br />ClientContext clientContext = new ClientContext("http://sp2010");<br /> Web oWebsite = clientContext.Web;<br /> List oList = oWebsite.Lists.GetByTitle("Announcements");<br /> ListItem oItem = oList.GetItemById(1); <br /> clientContext.Load(oItem);<br /> clientContext.ExecuteQuery();<br /> Console.WriteLine(oItem["Title"]);<br />
    20. 20. Object Identity<br />When you work with SharePoint objects in one of the client object models, SharePoint Foundation retains object identity<br />Client object identity is valid only for a single ClientContext object<br />The list object retains its identity through the call to ExecuteQuery method:<br />ClientContext clientContext =new ClientContext("http://sp2010");<br /> List list = clientContext.Web.Lists.GetByTitle("Announcements");<br /> clientContext.Load(list);<br /> clientContext.ExecuteQuery();<br /> Console.WriteLine("List Title: {0}", list.Title);<br /> CamlQuery camlQuery = new CamlQuery();<br /> camlQuery.ViewXml = "<View/>";<br /> ListItemCollection listItems = list.GetItems(camlQuery);<br /> clientContext.Load(listItems);<br /> clientContext.ExecuteQuery();<br /> foreach (ListItem listItem in listItems)<br /> Console.WriteLine("Id: {0} Title: {1}",<br /> oListItem.Id, listItem["Title"]);<br />
    21. 21. Authentication<br />Changing the authentication mechanism is allowed only in the .NET client object model<br />The ECMAScript Client OM uses the authentication of the page it's hosted within; <br /> it cannot change its authentication<br /> - Client OM properties: AuthenticationMode, Credentials, FormsAuthcenticationLoginInfo<br /> - Windows credentials (DefaultCredentials) are used by default<br /> - Use the ClientContext.AuthenticationMode property<br /> to change the authentication to use anonymous or forms-based authentication<br />context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;<br />context.FormsAuthenticationLoginInfo = <br />new FormsAuthenticationLoginInfo {<br /> LoginName="username",<br /> Password="password",};<br />
    22. 22. Authentication<br />You can use the Credentials property for the windows Authentication:<br />using (clientContext = new ClientContext(siteUrl)){<br />NetworkCredential credential = new NetworkCredential(“username”, “password”, “domain”);<br />clientContext.AuthenticationMode = ClientAuthenticationMode.Default;<br />clientContext.Credentials = credential;}<br />You can configure the authentication <br /> and security for the SP application <br /> from the central administration site<br />
    23. 23. Implementing the Client Object Model<br />.NET Client OM<br />.NET Client Object model can be utilized from managed code and from office client<br /> Microsoft.SharePoint.Client.dll — contains the client object model (281 kb)<br /> Microsoft.SharePoint.Client.Runtime.dll — handles all communication between the clientand SharePoint server (145 kb)<br /> “C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPI”<br />NET client object model offers only the synchronous ClientContext.ExecuteQuery() method<br />This means that, if your application needs to create asynchronous calls, you'll need to build it on your own.<br />
    24. 24. Implementing the Client Object Model<br />Asynchronous call in .Net Client OM example:<br />class AsynchronousAccess{ <br />delegate void AsynchronousDelegate();<br /> public void Run() {<br /> string webUrl = "http://sp2010";<br /> Console.WriteLine("About to start a query that will take a long time.");<br /> Console.WriteLine();<br /> ClientContext clientContext = new ClientContext(webUrl);<br /> ListCollection lists = clientContext.Web.Lists;<br /> IEnumerable<List> newListCollection = clientContext.LoadQuery(<br /> lists.Include(list => list.Title));<br /> AsynchronousDelegate executeQueryAsynchronously =<br /> new AsynchronousDelegate(clientContext.ExecuteQuery);<br /> executeQueryAsynchronously.BeginInvoke(arg =><br /> {<br /> Console.WriteLine("Long running query has completed.");<br /> foreach (List list in newListCollection)<br /> Console.WriteLine("Title: {0}", list.Title);<br /> }, null);<br /> Console.ReadLine();<br /> }<br /> }<br />
    25. 25. Implementing the Client Object Model<br />Silverligt Client OM<br />SP2010 supports implementation of the Silverlight client object model in 2 contexts: <br /> within a Silverlight Web Part, and within the Silverlight Cross-Domain Data Access system<br />Microsoft.SharePoint.Client.Silverlight.dll(262 kb)<br /> Microsoft.SharePoint.Client.Silverlight.Runtime.dll(138 kb)<br /> "C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATELAYOUTSClientBin"<br />ClientContext.Current is only initialized when the Silverlight application is running on a page in a SharePoint site:<br />ClientContext clientContext = ClientContext.Current;<br />ClientContext.Current returns NULL if you run the Silverlight application on a page<br /> in non SP web site<br />ExecuteQuery() - can be called synchronously from threads that do not modify the user interface (UI)<br />ExecuteQueryAsync() - asynchronous method are for cases where threads do modify the UI<br />
    26. 26. Implementing the Client Object Model<br />Silverligt Client OM<br />Web oWebsite; ListCollection collList; IEnumerable<List> listInfo; <br />private delegate void UpdateUIMethod();<br />ClientContext clientContext = ClientContext.Current;<br /> oWebsite = clientContext.Web;<br /> ListCollection collList = oWebsite.Lists;<br />  clientContext.Load(oWebsite, website=>website.Title);<br />  listInfo = clientContext.LoadQuery(<br /> collList.Include(list=>list.Title,<br /> list=>list.Fields.Include(<br /> field=>field.Title).Where(<br /> field=>field.Required == true && field.Hidden != true));<br />clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed); <br /> private void onQuerySucceeded(object sender,<br /> ClientRequestSucceededEventArgs args) { <br /> //pass delegate for callback methods as parameters <br /> UpdateUIMethod updateUI = DisplayInfo;<br /> this.Dispatcher.BeginInvoke(updateUI); } //to make changes in UI<br />
    27. 27. Implementing the Client Object Model<br />ECMAScript Client OM<br />ECMAScript works only for the current context. No cross-site scripting support<br />Supported browsers: IE 7.0 or greater, Firefox 3.5 or greater, Safari 4.0 or greater<br />“Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATE<br /> LAYOUTS” <br />Main files for development: SP.js, SP.Core.js, SP.Ribbon.js, SP.Runtime.js<br />How to add the reference to SP.js and access the data?<br />- from the server side (webpart or application page):<br /><SHAREPOINT:SCRIPTLINK name="SP.js" runat="server" <br /> ondemand="true" localizable="false"></SHAREPOINT:SCRIPTLINK><br />On Demand means whether the sp.js file need to be loaded on demand<br /> (not in pageload) or not.<br /> - to execute javascript function on page load event:<br />ExecuteOrDelayUntilScriptLoaded(myjsfunction.js,"sp.js");<br /> (delays your method call until the sp.js file is loaded)<br /> Tip: To use JQuery with ECMAScript Client OM add reference to YourJQuery.js file. <br />
    28. 28. Implementing the Client Object Model<br />ECMAScript Client OM<br /><script type="text/javascript">   <br />ExecuteOrDelayUntilScriptLoaded(getWebSiteData, "sp.js");   <br />var context = null;   var web = null;   <br />    function getWebSiteData() {   <br />        context = new SP.ClientContext.get_current();   <br />        web = context.get_web();   <br />        context.load(web);<br />        context.executeQueryAsync(<br /> Function.createDelegate(this, this.onSuccessMethod), <br /> Function.createDelegate(this, this.onFailureMethod));<br /> }  <br />    function onSuccessMethod(sender, args) {   <br />        alert('web title:' + web.get_title() + '  ID:' + web.get_id());   <br />    }   <br />    function onFaiureMethodl(sender, args) {   <br />   alert('request failed ' + args.get_message() + ' ' + args.get_stackTrace());    }   <br /> </script><br />
    29. 29. Implementing the Client Object Model<br />ECMAScript Client OM<br />Load only the data you want, not the whole web object:<br />context.load(web, 'Title','Id'); (properties are case sensitive)<br />loadQuery()<br /> var collList = clientContext.get_web().get_lists();<br /> this.lists = clientContext.loadQuery(collList, 'Include(Title)');<br />For filtering data write the CAML Queries<br /> Add page directive and FormDigest control inside your page to modifies SP content <br /><%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><br /><form>… <SharePoint:FormDigest runat="server" /> …</form><br /> (FormDigestcontroladds a security token inside your page based on user, site and time)<br />SharePoint provides 2 sets of JavaScript files: minified (default) and debug versions.<br /> For debug version add the <deployment retail="false" /> in the <system.web> section of the web.config file. <br /> It gives an error because the “deployment section” is marked as “MachineOnly” in machine.config.<br /> To fix it remove the attribute from machine.config :<br />allowDefinition="MachineOnly"from <section name="deployment" type="System.Web.Configuration.DeploymentSection<br />
    30. 30. Calling REST services in SharePoint 2010 <br />REST – (Representational State Transfer) is one of the many data access mechanisms used in SharePoint 2010 development<br />Use REST to pull data from Lists, Cloud and Excel sheets remotely<br />Rest APIs are provided through ADO.NET Data Services Framework via WCF <br />/_vti_bin/ListData.svc is the base service (case sensitive)<br />REST Responses can be represented via JSON or Atom <br />HTTP Accept header value for Atom is application/atom+xml<br /> HTTP Accept header value for JSON is application/json<br />For XML output - Tools –> Internet Options –> Content tab –> Feeds and web slices Settings (IE 8)<br />Parameters can be stacked together to filter, sort, or paginate the data <br />$filter - formatted like a CAML query<br />$expand - allows to embed one or more sets of related entities in the results (similar to a SQL JOIN)<br />$orderby - sets return order by<br />$skip - skip x item<br />$top - return top x<br />$metadata (will bring back all the XML metadata about the object ( like WSDL for your REST call) <br />
    31. 31. Calling REST services in SharePoint 2010<br /><ul><li>Read, create, update, and delete operations are mapped directly to GET, POST, PUT, and DELETE HTTP verbs</li></ul>Syntax: <br /> http://[server]/[optional site]/_vti_bin/ListData.svc<br /> http://localhost/site/_vti_bin/ListData.svc/ListName<br />/_vti_bin/ListData.svc/{Entity}[({identifier})]/[{Property}]<br />/_vti_bin/ListData.svc/Projects(4)/BudgetHours <br /> /_vti_bin/ListData.svc//Projects?$filter=Client/City eq ‘Chicago’ <br />404, 401 errors if list item row level permission is set to deny read permissions<br />SharePoint also performs data validation and returns the appropriate HTTP error codes if you for instance violate the new uniqueness constraint<br />
    32. 32. Links<br />Videos<br /><br />SharePoint 2010 developer – Client Object Model <br /><br />MSDN<br /><br /> AD4BA33A35C5&displaylang=en<br />Blog posts:<br /><br /><br /> <br /><br /><br /><br />SharePointPro Connections <br /><br />
    33. 33. Please Don’t Forget to Complete Your Evaluation FormYour input is important!Plus, this is how you’ll get the chance to enter the raffle draws throughout the event<br />Thank you!<br />