• Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
4,133
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
56
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    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.

Transcript

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