Upload
sharepoint-saturday-ny
View
5.118
Download
4
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
Developing solutions for SP2010 using the Client Object Model
Lyudmila ZharovaSharePoint Developer at MRM [email protected]/7/2010
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
AGENDA
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
The goal of Client Object Model
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• Files and Folders• Web Parts• Security• Content Types• Site Templates and Site Collection Operations Access an External List using Office Add-insLimitations 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)
Supported Areas and Limitations:
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
Client Object Model Overview
Server OM
(Microsoft.SharePoint)
.NET Framework
(Microsoft.SharePoint.Client)
14\ISAPI
Silverlight
(Microsoft.SharePoint.Client.Silverlight)
14\TEMPLATE\LAYOUS\ClientBin
ECMAScript
(SP.js)
14\LAYOUTS
SPContext ClientContext ClientContext ClientContext
SPSite Site Site Site
SPWeb Web Web Web
SPList List List List
SPListItem ListItem ListItem ListItem
SPField Field Field Field
Client object model bundles the uses of the APIs into XML and returns result to the client in JSON format
How the Client-Side Object Model Works
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();
ClientContext
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
Load () - In-place load LoadQuery () - Queryable load
Loads an entire collection into the client context
Returns an enumerable collection of results(you can query the same object collection multiple time and keep separate result sets for each query)
These collections are eligible for garbage collection only when the client context variable itself goes out of scope
You can let these collections go out of scope, and thereby become eligible for garbage collection
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"]);
Rules of using Client OM
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"]);
Object Identity
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
Authentication
.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 client
and SharePoint server (145 kb) “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI”
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:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin"
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 Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\ 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 page load) 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() + '\n ID:' + web.get_id());
}
function onFaiureMethodl(sender, args) {
alert('request failed ' + args.get_message() + '\n' + 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> (FormDigest control adds 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
Implementing the Client Object Model
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)
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
Calling REST services in SharePoint 2010
Videoshttp://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.aspxhttp://blogs.technet.com/b/speschka/archive/2009/11/01/using-the-sharepoint-2010-client-object-model-part2.aspxhttp://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.aspxhttp://blogs.technet.com/b/speschka/archive/2009/11/01/using-the-sharepoint-2010-client-object-model-part5.aspxhttp://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
Links
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!