Wednesday, December 30, 2015

Basic details about SharePoint Client Object Model



Basic details about SharePoint Client Object Model


SharePoint 2010 introduces a new client side object model.  It supports a subset of functionality contained in the server side object model, but generally speaking gives you ready access to the data in your SharePoint site using standard object model nomenclature.  
SharePoint exposes three OMs which are as follows:
·          Managed
·          Silverlight
·          JavaScript (ECMAScript)

Each of these OMs provide object interface to functionality exposed in Microsoft. SharePoint namespace. While none of the object models expose the full functionality that the server-side object exposes, the understanding of server Object Models will easily translate for a developer to develop applications using an OM. A managed OM is used to develop custom .NET managed applications (service, WPF, or console applications). You can also use the OM for ASP.NET applications that are not running in the SharePoint context as well. A Silverlight OM is used by Silverlight client applications. A JavaScript OM is only available to applications that are hosted inside the SharePoint applications like web part pages or application pages.
Even though each of the OMs provides different programming interfaces to build applications, behind the scenes, they all call a service called Client.svc to talk to SharePoint. This Client.svc file resides in the ISAPI folder. The service calls are wrapped around with an Object Model that developers can use to make calls to SharePoint server. This way, developers make calls to an OM and the calls are all batched together in XML format to send it to the server. The response is always received in JSON format which is then parsed and associated with the right objects. The basic architectural representation of the client interaction with the SharePoint server is as shown in the following image:
 
The three Object Models come in separate assemblies. The following table provides the locations and names of the assemblies:

Object OM
Location
Names
Managed
ISAPI folder
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Silverlight
Layouts\ClientBin
Microsoft.SharePoint.Client. Silverlight.dll
Microsoft.SharePoint.Client.
Silverlight.Runtime.dll
JavaScript
Layouts
SP.js
REST/OData
NA
NA

Naming conventions

As a small side-note I would like to mention that the objects you are comfortable with calling “SPWeb”, “SPSite”, “SPList” and so on are now named “Web”, “Site”, “List”.
So to conclude the naming convention, the “SP” in the objects has been dropped. Easy enough to remember, right?
Authentication Options for application

Quite naturally, the question of how you can authenticate to SharePoint often pops up when I do my SP 2010 training and seminars. With that said, I’ll walk you through the different authentication options you’ve got for your client application.
Basically there are three (3) authentication options you can use when you’re working with the Client Object Model in SharePoint 2010:
§  Anonymous

§  Default
§  FormsAuthentication
If you do not choose an authentication method in your code, the application will default to using the client’s Windows Credentials (DefaultCredentials)
Example 1: Using anonymous authentication
ctx.AuthenticationMode = SP.ClientAuthenticationMode.Anonymous;
Example 2: Using Forms Authentication with the Client Object Model
SP.FormsAuthenticationLoginInfo formsLoginInfo =  
new SP.FormsAuthenticationLoginInfo("SureshNV", "SecretPassword");
ctx.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
ctx.FormsAuthenticationLoginInfo = formsLoginInfo;
When you call the Forms Authentication, it will automatically call the Authentication Web Service for you and return the authenticated cookie.
By default, ClientContext instance uses windows authentication. It makes use of the windows identity of the person executing the application. Hence, the person running the application should have proper authorization on the site to execute the commands. Exceptions will be thrown if proper permissions are not available for the user executing the application. The following is the code for passing FBA credentials if your site supports it:
using (ClientContext clientCtx = new ClientContext("http://polasoft"))
 { 
clientCtx.AuthenticationMode = ClientAuthenticationMode. 
FormsAuthentication; 
FormsAuthenticationLoginInfo fba = new FormsAuthenticationLoginInfo("u 
sername", "password"); 
clientCtx.FormsAuthenticationLoginInfo = fba; 
//Business Logic 
}
Impersonation:

In order to impersonate you can pass in credential information to the ClientContext as shown in the following code:
clientCtx.Credentials = new NetworkCredential("username",
 "password", "domainname");
Passing credential information this way is supported only in Managed OM.

Authenticating .NET Client Object Model in Office 365

The process of authenticating the .NET Client Object Model in SharePoint Online has been greatly simplified in the 2013 version. Earlier (2010), you had to go through a lot of steps for doing the exact same thing. You had to open a web browser instance, force the user to enter the credentials in the browser and then grab that cookie from Internet Explorer and pass it to the .NET CSOM. If you are interested, the code of the old authentication method can be found here:
http://blogs.msdn.com/b/cjohnson/archive/2011/05/03/authentication-with-sharepoint-online-and-the-client-side-object-model.aspx

Fortunately in the 2013 version, the process is a lot simplified by the introduction of the SharePointOnlineCredentials class. This class is part of the Microsoft.SharePoint.Client.dll itself so you don't have to include an extra assembly in your application. All you have to do is pass an instance of the SharePointOnlineCredentials class to the ClientContext.Credentials property. The SharePointOnlineCredentials takes in two parameters which are your Login Email for your Office 365 SharePoint site and your password in the SecureString format.
You can grab all the required SharePoint 2013 client assemblies from here:
http://www.microsoft.com/en-us/download/details.aspx?id=35585
For this particular demo, you will need to reference the Microsoft.SharePoint.Client.dll and the Microsoft.SharePoint.Client.Runtime.dll assemblies in your project.
 The code is as follows:
using (ClientContext clientContext = new ClientContext("https://yoursite.sharepoint.com/"))
{
    SecureString passWord = new SecureString(); 
    foreach (char c in "yourpassword".ToCharArray()) passWord.AppendChar(c); 
    clientContext.Credentials = new 
          SharePointOnlineCredentials("loginname@yoursite.onmicrosoft.com", passWord); 
    Web web = clientContext.Web; 
    clientContext.Load(web); 
    clientContext.ExecuteQuery(); 
    Console.WriteLine(web.Title);
    Console.ReadLine();
}

Initializing the Client-side object model:  
Much like the Server -side object model, which is the other framework for development in SharePoint, CSOM also needs a starting point in the form of a central object which will instantiate and provide access to the client object model.  This central object is called the Client Context. The Client Context object orchestrates requests and initiates actions within a site collection. Once the Client Context Object is initialized, it provides information to the site collection or website through which we can access other SharePoint client object remotely as depicted in the below code.
//Managed  Client Object  Model
using (ClientContext ctx = new ClientContext(“http://MyServer/sites/MySiteCollection”))
{
Site siteCollection =ctx.site;
ctx.Load(siteCollection);
ctx.ExecuteQuery();
string url=siteCollection.Url;
}
//Javascript Client Object Model
var siteCollection;
var ctx= new SP.ClientContext.get_current();
siteCollection=ctx.get_site();
ctx.load(siteCollection);
ctx.executeQueryAsync(success,failuer);

function success()
{
var url= siteCollection.get_url();
}

function failure()
{
alert(“Failuer!”);
}
The Client Context class in managed object model inherits from the ClientContextRuntime class.
The SP.ClientContext object in JavaScript client object model inherits from the  SP.ClientContextRuntime object and provides equivalent functionality to the ClientContext  class found in the managed client object model.

What’s New in SharePoint 2013 CSOM and REST APIs






With the new SharePoint App Model in SharePoint 2013, every SharePoint developer will encounter SharePoint 2013 CSOM and REST based APIs while building apps for the corporate or public market place. In past, CSOM and REST based APIs weren’t popular compare to Server Side Object Model for many reasons including limited API support. Unless you were building applications using JavaScript or Silverlight or from remote clients like CRM or other SharePoint farms, many times Server Side Object Model with the full API was a better choice over CSOM or REST based APIs.With the SharePoint 2013 Apps Model, Microsoft has improved both CSOM and REST based APIs and added much needed support for the Search, User Profiles, Taxonomies, and Publishing Object Model. In addition to additional APIs, both REST and CSOM APIs are available through same endpoint making it almost equivalent APIs.
Basic operations using Managed Client Object Model

In the managed client object, you can do all the SharePoint website related tasks such as read and write all the website related properties, create a new SharePoint web site, SharePoint List operations (create new SharePoint lists, retrieve all SharePoint lists in a SharePoint website, insert, update and delete in SharePoint lists), SharePoint Document Library operations (the same as SharePoint List operations).

Much like the server-side object model (that is the other framework for development in SharePoint) CSOM also needs a starting point in the form of a central object that will instantiate and provide access to the client object model. This central object is called the Client Context. The Client Context object orchestrates requests and initiates actions within a site collection. Once the Client Context Object is initialized, it provides information to the site collection or website through that we can access other SharePoint client objects remotely as depicted in the following code.
Example Code

Add the references Microsoft.SharePoint.dll and Microsoft.SharePoint.Client.dll.
Create List Item

1.  using System;  
2.  using System.Collections.Generic;  
3.  using System.Linq;  
4.  using System.Text;  
5.  using Microsoft.SharePoint;  
6.  using Microsoft.SharePoint.Client;  
7.  namespace CreateListItem  
8.  {  
9.      class Program  
10.     {  
11.         static void Main(string[] args)  
12.         {  
13.             string siteUrl = "http://SPPractice:2222/";  
14.             ClientContext clientContext = new ClientContext(siteUrl);  
15.          List oList = clientContext.Web.Lists.GetByTitle("TestList");  
16.      ListItemCreationInformation listCreationInformation =  
                             new ListItemCreationInformation();  
17.             ListItem oListItem = oList.AddItem(listCreationInformation);  
18.             oListItem["Title"] = "Hello World";  
19.             oListItem.Update();  
20.             clientContext.ExecuteQuery();  
21.         }  
22.     }  
23. }


Update List Item
1.  using System;  
2.  using System.Collections.Generic;  
3.  using System.Linq;  
4.  using System.Text;  
5.  using Microsoft.SharePoint;  
6.  using Microsoft.SharePoint.Client;  
7.    
8.  namespace UpdateListItem  
9.  {  
10.     class Program  
11.     {  
12.         static void Main(string[] args)  
13.         {  
14.             string siteUrl = "http://SPPractice:2222";  
15.             ClientContext clientContext = new ClientContext(siteUrl);  
16.             List oList = clientContext.Web.Lists.GetByTitle("TestList");  
17.             ListItem oListItem = oList.GetItemById(5);  
18.             oListItem["Title"] = "Hello World Updated!!!";  
19.             oListItem.Update();  
20.             clientContext.ExecuteQuery();  
21.         }  
22.     }  
23. }


Delete List Item
1.  using System;  
2.  using System.Collections.Generic;  
3.  using System.Linq;  
4.  using System.Text;  
5.  using Microsoft.SharePoint;  
6.  using Microsoft.SharePoint.Client;  
7.    
8.  namespace UpdateListItem  
9.  {  
10.     class Program  
11.     {  
12.         static void Main(string[] args)  
13.         {  
14.             string siteUrl = "http://SPPractice:2222";  
15.             ClientContext clientContext = new ClientContext(siteUrl);  
16.             List oList = clientContext.Web.Lists.GetByTitle("TestList");  
17.             ListItem oListItem = oList.GetItemById();           
18.             oListItem.DeleteObject();  
19.             clientContext.ExecuteQuery();  
20.         }  
21.     }  
22. }


Conclusion
Using the SharePoint Client object model, developers can work with the SharePoint web application remotely.
In SharePoint 2013, a new API support has been added along with the one provided in SharePoint 2010. This provides access to its APIs in several forms, to help development of remote applications using REST/OData for .NET as well as for working with frameworks other than .NET. With this new set of APIs, if developers want to use client applications not using managed code or Silverlight, they can consider the use of REST/OData endpoints to read/write data from and to SharePoint. Since the REST interface doesn’t require any reference to assemblies, it also allows you to manage and limit the footprint of your Web applications; an important consideration especially when you are building mobile apps for Windows Phone written using HTML and JavaScript. One of the biggest advantage is that we can make use of JavaScript libraries like, jQuery, Knockout, Angular, etc to build applications, ultimately making use of the skillsets most developers are equipped with.
The APIs endpoints can be accessed using _API. This is a single endpoint for all remote APIs provided in SharePoint 2013. _API is fully REST and OData enabled. Some example url’s are as shown here:
http://HostServer/sites/MyDeveloper/_api/web/Lists
http://HostServer/sites/MyDeveloper/_api/web/Lists/getbytitle('MyList')/

Using REST in SharePoint App

In SharePoint 2013 with SharePoint Hosted Apps, we often need to access SharePoint List data for performing CRUD operations. Since SharePoint Apps are programmed using JavaScript and we have a REST API with us, it is possible to use Ajax methods to make calls to the SharePoint List.
The scenario discussed here is that the SharePoint List is available on the site collection. This list can be accessed using SharePoint App for performing CRUD operations. But there exists an isolation between List and the SharePoint App. So in this type of a scenario, our SharePoint App must have access permissions to the specific list on which operations need to perform.
The SharePoint App JavaScript code can locate the List in the site collection using the following url approaches:
var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target)" +
    "/web/lists/getbytitle('" + listName + "')/items?" +
    "@target='" + SPHostUrl + "'"
In the above code, the SPAppWebUrl represents the SharePoint App URL where the App is hosted andSPHostUrl represents the URL for the Site collection from where the List is accessed. The listName is the list on which operations are to be performed.
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle
('" + listName + "')/items"
In the above code, the _spPageContextInfo is the JavaScript or jQuery variable that provides properties used during SharePoint App development for locating the SharePoint Site collection for performing Ajax calls.

Introduction to SharePoint 2013 JavaScript Object Model

SharePoint 2013 Client Object Model is a set of libraries and classes with which you can consume SharePoint data through a specific object model that is a subset of the SharePoint Server Object Model.
This figure shows the overall architecture of the Client Object Model.


JSOM or JavaScript Object Model is a set of .js files built for ECMAScript-enabled platforms. The main .js files that are available are:
o    SP.js

o    SP.Core.js
o    SP.Ribbon.js
o    SP.Runtime.js
These files are deployed in the SharePoint15_Root\TEMPLATE\LAYOUTS directory. The default master pages of SharePoint define a ScriptManager control, which automatically includes references to these .js files. You could also reference them by yourself.
For Security reasons, if you use the Client Object Model within a custom ASPX page, you will need to include the FormDegist control by yourself.
Hope this will helps some one :)

No comments:

Post a Comment