SlideShare uma empresa Scribd logo
1 de 29
Developing solutions for SP2010 using the Client Object Model Lyudmila Zharova SharePoint Developer at MRM Worlwide lzharova077@gmail.com 21/7/2010
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
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
  Supported Areas and Limitations: Supported Areas: With Client OM you can perform the most common CRUD operations in the following areas:  ,[object Object]
Files and Folders
Web Parts
Security
Content Types
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)
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
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
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();
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);
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.
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
Rules of using Client OM Consider the different semantics  of the LoadQuery()  and the Load() methods
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.
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
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"]);
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"]);
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",};
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
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:rogram Filesommon Filesicrosoft Sharedeb Server Extensions4SAPI” 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.
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();         }     }
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:rogram Filesommon Filesicrosoft Sharedeb Server Extensions4EMPLATEAYOUTSlientBin" 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
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
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 Filesommon Filesicrosoft Sharedeb Server Extensions4EMPLATEbr />       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.
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>
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

Mais conteúdo relacionado

Mais procurados

Taking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST APITaking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST API
Eric Shupps
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
SPTechCon
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote Authentication
Adil Ansari
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint Apps
Liam Cleary [MVP]
 
SharePoint 2007 Presentation
SharePoint 2007 PresentationSharePoint 2007 Presentation
SharePoint 2007 Presentation
Ajay Jain
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controls
Raed Aldahdooh
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
Spiffy
 

Mais procurados (20)

SharePoint Client Object Model (CSOM)
SharePoint Client Object Model (CSOM)SharePoint Client Object Model (CSOM)
SharePoint Client Object Model (CSOM)
 
Understanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST APIUnderstanding and programming the SharePoint REST API
Understanding and programming the SharePoint REST API
 
Introduction to the SharePoint 2013 REST API
Introduction to the SharePoint 2013 REST APIIntroduction to the SharePoint 2013 REST API
Introduction to the SharePoint 2013 REST API
 
Taking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST APITaking Advantage of the SharePoint 2013 REST API
Taking Advantage of the SharePoint 2013 REST API
 
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
Advanced SharePoint 2010 and 2013 Web Part Development by Rob Windsor - SPTec...
 
SharePoint 2013 REST APIs
SharePoint 2013 REST APIsSharePoint 2013 REST APIs
SharePoint 2013 REST APIs
 
Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365Develop iOS and Android apps with SharePoint/Office 365
Develop iOS and Android apps with SharePoint/Office 365
 
SharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote AuthenticationSharePoint 2013 REST API & Remote Authentication
SharePoint 2013 REST API & Remote Authentication
 
Are you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint AppsAre you getting Sleepy. REST in SharePoint Apps
Are you getting Sleepy. REST in SharePoint Apps
 
Sharepoint Online
Sharepoint OnlineSharepoint Online
Sharepoint Online
 
SharePoint 2007 Presentation
SharePoint 2007 PresentationSharePoint 2007 Presentation
SharePoint 2007 Presentation
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
Who Are You and What Do You Want? Working with OAuth in SharePoint 2013.
 
Client Object Model and REST Improvements in SharePoint 2013
Client Object Model and REST Improvements in SharePoint 2013Client Object Model and REST Improvements in SharePoint 2013
Client Object Model and REST Improvements in SharePoint 2013
 
CSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
CSOM (Client Side Object Model). Explained @ SharePoint Saturday HoustonCSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
CSOM (Client Side Object Model). Explained @ SharePoint Saturday Houston
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
 
Working With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps DevelopmentWorking With Sharepoint 2013 Apps Development
Working With Sharepoint 2013 Apps Development
 
Asp.net server controls
Asp.net server controlsAsp.net server controls
Asp.net server controls
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 

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

Wss Object Model
Wss Object ModelWss Object Model
Wss Object Model
maddinapudi
 
SharePoint Saturday The Conference DC - How the client object model saved the...
SharePoint Saturday The Conference DC - How the client object model saved the...SharePoint Saturday The Conference DC - How the client object model saved the...
SharePoint Saturday The Conference DC - How the client object model saved the...
Liam Cleary [MVP]
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
Chui-Wen Chiu
 

Semelhante a Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client Object (20)

4 - Silverlight y SharePoint, por Rodrigo Diaz y Mauricio Angulo
4 - Silverlight y SharePoint, por Rodrigo Diaz y Mauricio Angulo4 - Silverlight y SharePoint, por Rodrigo Diaz y Mauricio Angulo
4 - Silverlight y SharePoint, por Rodrigo Diaz y Mauricio Angulo
 
Asp objects
Asp objectsAsp objects
Asp objects
 
Developing With Data Technologies
Developing With Data TechnologiesDeveloping With Data Technologies
Developing With Data Technologies
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Wss Object Model
Wss Object ModelWss Object Model
Wss Object Model
 
SharePoint Saturday The Conference DC - How the client object model saved the...
SharePoint Saturday The Conference DC - How the client object model saved the...SharePoint Saturday The Conference DC - How the client object model saved the...
SharePoint Saturday The Conference DC - How the client object model saved the...
 
Active server pages
Active server pagesActive server pages
Active server pages
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
ADO.NET Data Services
ADO.NET Data ServicesADO.NET Data Services
ADO.NET Data Services
 
Rest API and Client OM for Developer
Rest API and Client OM for DeveloperRest API and Client OM for Developer
Rest API and Client OM for Developer
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
Ajax
AjaxAjax
Ajax
 
Active Server Page - ( ASP )
Active Server Page - ( ASP )Active Server Page - ( ASP )
Active Server Page - ( ASP )
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet
 
asp_intro.pptx
asp_intro.pptxasp_intro.pptx
asp_intro.pptx
 

Mais de SharePoint Saturday NY

Sb chatterjee share point workspace 2010 in action
Sb chatterjee   share point workspace 2010 in actionSb chatterjee   share point workspace 2010 in action
Sb chatterjee share point workspace 2010 in action
SharePoint Saturday NY
 
Joel Oleson: SharePoint 2010 Upgrade Drill Down
Joel Oleson: SharePoint 2010 Upgrade Drill DownJoel Oleson: SharePoint 2010 Upgrade Drill Down
Joel Oleson: SharePoint 2010 Upgrade Drill Down
SharePoint Saturday NY
 
Chris Geier: Information Management in SharePoint 2010
Chris Geier: Information Management in SharePoint 2010Chris Geier: Information Management in SharePoint 2010
Chris Geier: Information Management in SharePoint 2010
SharePoint Saturday NY
 
John Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nyc
John Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nycJohn Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nyc
John Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nyc
SharePoint Saturday NY
 
John Burkholder: Disaster Recovery in SharePoint 2010
John Burkholder: Disaster Recovery in SharePoint 2010John Burkholder: Disaster Recovery in SharePoint 2010
John Burkholder: Disaster Recovery in SharePoint 2010
SharePoint Saturday NY
 
Chris McNulty - Managed Metadata and Taxonomies
Chris McNulty - Managed Metadata and TaxonomiesChris McNulty - Managed Metadata and Taxonomies
Chris McNulty - Managed Metadata and Taxonomies
SharePoint Saturday NY
 
Chris McNulty: ECM/WCM Planning, Implementation and Migration Strategies
Chris McNulty: ECM/WCM Planning, Implementation and Migration StrategiesChris McNulty: ECM/WCM Planning, Implementation and Migration Strategies
Chris McNulty: ECM/WCM Planning, Implementation and Migration Strategies
SharePoint Saturday NY
 
Jaime Velez: SharePoint 2010 Social Computing
Jaime Velez: SharePoint 2010 Social ComputingJaime Velez: SharePoint 2010 Social Computing
Jaime Velez: SharePoint 2010 Social Computing
SharePoint Saturday NY
 
Matthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 DevelopmentMatthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 Development
SharePoint Saturday NY
 
Geoff Varosky: Creating Custom Actions in SharePoint 2010
Geoff Varosky: Creating Custom Actions in SharePoint 2010Geoff Varosky: Creating Custom Actions in SharePoint 2010
Geoff Varosky: Creating Custom Actions in SharePoint 2010
SharePoint Saturday NY
 
Brian Jackett: Managing SharePoint 2010 Farms with Powershell
Brian Jackett: Managing SharePoint 2010 Farms with PowershellBrian Jackett: Managing SharePoint 2010 Farms with Powershell
Brian Jackett: Managing SharePoint 2010 Farms with Powershell
SharePoint Saturday NY
 
Kathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All Together
Kathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All TogetherKathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All Together
Kathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All Together
SharePoint Saturday NY
 
Susan Lennon: Building SharePoint Dashboards
Susan Lennon: Building SharePoint DashboardsSusan Lennon: Building SharePoint Dashboards
Susan Lennon: Building SharePoint Dashboards
SharePoint Saturday NY
 
Mostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best Practices
Mostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best PracticesMostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best Practices
Mostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best Practices
SharePoint Saturday NY
 
Scott Lavoie: Best Practices and Pain Points of SharePoint Training
Scott Lavoie: Best Practices and Pain Points of SharePoint TrainingScott Lavoie: Best Practices and Pain Points of SharePoint Training
Scott Lavoie: Best Practices and Pain Points of SharePoint Training
SharePoint Saturday NY
 
Paul Galvin: Introduction to Infopath and Best Practices
Paul Galvin: Introduction to Infopath and Best PracticesPaul Galvin: Introduction to Infopath and Best Practices
Paul Galvin: Introduction to Infopath and Best Practices
SharePoint Saturday NY
 
Greg Hurlman: Developing Custom Service Applications
Greg Hurlman: Developing Custom Service ApplicationsGreg Hurlman: Developing Custom Service Applications
Greg Hurlman: Developing Custom Service Applications
SharePoint Saturday NY
 

Mais de SharePoint Saturday NY (20)

Sb chatterjee share point workspace 2010 in action
Sb chatterjee   share point workspace 2010 in actionSb chatterjee   share point workspace 2010 in action
Sb chatterjee share point workspace 2010 in action
 
Joel Oleson: SharePoint 2010 Upgrade Drill Down
Joel Oleson: SharePoint 2010 Upgrade Drill DownJoel Oleson: SharePoint 2010 Upgrade Drill Down
Joel Oleson: SharePoint 2010 Upgrade Drill Down
 
Peter Ward: The True Power of SharePoint Designer Workflows
Peter Ward: The True Power of SharePoint Designer WorkflowsPeter Ward: The True Power of SharePoint Designer Workflows
Peter Ward: The True Power of SharePoint Designer Workflows
 
Chris Geier: Information Management in SharePoint 2010
Chris Geier: Information Management in SharePoint 2010Chris Geier: Information Management in SharePoint 2010
Chris Geier: Information Management in SharePoint 2010
 
Mostafa Elzoghbi: SharePoint 2010 Sanbbox Solutions bestpractices - public
Mostafa Elzoghbi: SharePoint 2010 Sanbbox Solutions bestpractices - publicMostafa Elzoghbi: SharePoint 2010 Sanbbox Solutions bestpractices - public
Mostafa Elzoghbi: SharePoint 2010 Sanbbox Solutions bestpractices - public
 
John Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nyc
John Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nycJohn Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nyc
John Burkholder: SharePoint 2010 in a multi tenant and hosted environment-nyc
 
John Burkholder: Disaster Recovery in SharePoint 2010
John Burkholder: Disaster Recovery in SharePoint 2010John Burkholder: Disaster Recovery in SharePoint 2010
John Burkholder: Disaster Recovery in SharePoint 2010
 
Chris McNulty - Managed Metadata and Taxonomies
Chris McNulty - Managed Metadata and TaxonomiesChris McNulty - Managed Metadata and Taxonomies
Chris McNulty - Managed Metadata and Taxonomies
 
Chris McNulty: ECM/WCM Planning, Implementation and Migration Strategies
Chris McNulty: ECM/WCM Planning, Implementation and Migration StrategiesChris McNulty: ECM/WCM Planning, Implementation and Migration Strategies
Chris McNulty: ECM/WCM Planning, Implementation and Migration Strategies
 
Jaime Velez: SharePoint 2010 Social Computing
Jaime Velez: SharePoint 2010 Social ComputingJaime Velez: SharePoint 2010 Social Computing
Jaime Velez: SharePoint 2010 Social Computing
 
Matthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 DevelopmentMatthew Vignau: Memory Management in SharePoint 2007 Development
Matthew Vignau: Memory Management in SharePoint 2007 Development
 
Geoff Varosky: Creating Custom Actions in SharePoint 2010
Geoff Varosky: Creating Custom Actions in SharePoint 2010Geoff Varosky: Creating Custom Actions in SharePoint 2010
Geoff Varosky: Creating Custom Actions in SharePoint 2010
 
Brian Jackett: Managing SharePoint 2010 Farms with Powershell
Brian Jackett: Managing SharePoint 2010 Farms with PowershellBrian Jackett: Managing SharePoint 2010 Farms with Powershell
Brian Jackett: Managing SharePoint 2010 Farms with Powershell
 
Alphonso Scarborough: SharePoint 101
Alphonso Scarborough: SharePoint 101Alphonso Scarborough: SharePoint 101
Alphonso Scarborough: SharePoint 101
 
Kathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All Together
Kathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All TogetherKathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All Together
Kathryn Birstein: SharePoint 2010 Business Intelligence-Bringing it All Together
 
Susan Lennon: Building SharePoint Dashboards
Susan Lennon: Building SharePoint DashboardsSusan Lennon: Building SharePoint Dashboards
Susan Lennon: Building SharePoint Dashboards
 
Mostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best Practices
Mostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best PracticesMostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best Practices
Mostafa Elzoghbi: SharePoint 2010 Sandbox Solutions Best Practices
 
Scott Lavoie: Best Practices and Pain Points of SharePoint Training
Scott Lavoie: Best Practices and Pain Points of SharePoint TrainingScott Lavoie: Best Practices and Pain Points of SharePoint Training
Scott Lavoie: Best Practices and Pain Points of SharePoint Training
 
Paul Galvin: Introduction to Infopath and Best Practices
Paul Galvin: Introduction to Infopath and Best PracticesPaul Galvin: Introduction to Infopath and Best Practices
Paul Galvin: Introduction to Infopath and Best Practices
 
Greg Hurlman: Developing Custom Service Applications
Greg Hurlman: Developing Custom Service ApplicationsGreg Hurlman: Developing Custom Service Applications
Greg Hurlman: Developing Custom Service Applications
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

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

  • 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.
  • 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:rogram Filesommon Filesicrosoft Sharedeb Server Extensions4SAPI” 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:rogram Filesommon Filesicrosoft Sharedeb Server Extensions4EMPLATEAYOUTSlientBin" 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 Filesommon Filesicrosoft Sharedeb Server Extensions4EMPLATEbr /> 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.
  • 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!

Notas do Editor

  1. 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
  2. Client APIs are very intuitive .The naming convention rests very similar to the Server OM. “SP” prefix in the client objects has been dropped.
  3. 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.
  4. You “get connected” to the data in SharePoint with the new ClientContext object.
  5. 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.
  6. 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.
  7. think as a .NET class or structure that is marshaled by value
  8. (think as a .NET class or structure that is marshaled reference)
  9. 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.
  10. Before executing Client Object Model calls you need to get a ClientContext object through which calls can be made.
  11. 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.
  12. Calling Load() method won&apos;t load the object immediately. We need explicitly call it by using executeQueryAsync() method. It has the success method and the failure method
  13. 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.
  14. 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.
  15. 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&apos;t have permissions to modify then SharePoint returns a 401 Unauthorized.