Client Side Object model and REST API

Discussion in 'ASP.NET' started by MinalS, Apr 28, 2015.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    32
    Trophy Points:
    0
    The CSOM consist of Managed code, ECMA script, and Silverlight. The developers can access from remote code applications. Silverlight applications execute a web page call back to the SharePoint and access data. The protocols used by CSOM are XML and JSON. They are documented making it a benefit for HTTP requests to make similar calls if needed.

    SharePoint 2013 provides remote APIs with CSOM and the protocols as the primary API for interacting with SharePoint. They provide access to APIs in various forms. They are as listed below:
    1. Managed code assemblies ( .NET )
    2. JavaScript
    3. Windows Phone assemblies
    4. REST / ODATA
    5. Silverlight assemblies
    The suitability of the API depends on the project. If user needs to create a Windows Forms application, the managed CSOM is used. If the Web part is to be created, The JavaScript CSOM is used for the front end code and managed CSOM for the server side code.

    The _API is the core of the new API set. It is used as an endpoint for the remote APIs in SharePoint 2013. _API refers to the location from where the SharePoint URL structure is accessible. _API provides a central location for API services.

    _API is fully REST and OData enabled. REST defines Representational State Transfer. It is referred to an API as RESTful. The Open Data Protocol ( OData ) specifies the protocol for requesting and working with the data over the web protocols as HTTP, JSON, XML.

    _API is built on the foundation of SharePoint 2010 CSOM and provides access to various areas of SharePoint.

    1. Managed Code ( .NET )



    In SharePoint 2010, Microsoft consists of version of managed code CSOM for developers of .NET applications. The library is rebuilt for SharePoint 2013. It is built up by various assemblies of .NET. The assemblies are Microsoft.SharePoint.Client.Runtime.dll, Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Publishing.dll, etc.

    Setup

    The DLLS can be added on the computer by downloading the SharePoint Client Components SDK. User can fund them on the location where the SharePoint is installed. The path is is %ProgramFiles%\Common Files\Microsoft Shared\ web server extensions\15\ISAPI.

    The client Context object needs to be instantiated for communicating with the services. The following code shows the ClientContext instantiation.

    Code:
    ClientContext cont = new ClientContext("http://SharePointSite");
    
    Once the object is created, user must know the ways to interact with the data. The core objects in the CSOM are Site, Web, List, and ListItem.

    Querying

    The two important features of CSOM are as mentioned below:
    1. Batching
    2. Returning data need by the user
    When the user works with the remote server, the two important points to be considered are the number of calls and minimum responses for a job. CSOM executes calls only when the user needs them and adds the operations the last time it was executed.
    The core object for CSOM is the Site or Web object. The .Site and .Web properties are used.

    The following code snippet demonstrates the querying of data using CSOM.
    Code:
    ClientContext cont = new ClientContext("http://SharePointSiteUrl");
    Site site = cont.Site;
    Web web = cont.Web;
    
    The site and web context objects are created. The CSOM brings the data on when user needs it.

    The Load method can be used with the CSOM as mentioned below:
    Code:
    List list = web.Lists.GetByGender("Male");
    ListItemCollection list1 = list.GetItems(query.CreateAllItemsQuery(20) ) ;
    cont.Load(list1, items = > items.Include(item = > item [ "Gender" ] ) ) ;
    cont.ExecuteQuery();
    
    The similar concept is used for bringing the data back with the properties user needs. The following code snippet shows the concept.
    Code:
    ClientContext cont = new ClientContext("http://SharePointSiteUrl");
    Web web = cont.Web;
    cont.Load(web, w = > w.Gender );
    cont.ExecuteQuery();
    
    The Load method is called by the user. It returns the values of the properties as the default ones.

    The CSOM provides operations for creating data. If the user does not contain an reference to the existing object, the CSOM creates an object ListItemCreationInformation for collecting the information.

    The following code snippet shows the use of ListItemCreationInformation class for adding a new row to the list.

    Code:
    ClientContext cont = new ClientContext("http://SharePointUrl");
    Web web = cont.Web;
    List list = web.Lists.GetByGender["Names"];
    cont.Load(web);
    cont.Load(list);
    ListItemCreationInformation itemInfo = new ListItemCreationInformation();
    ListItem list1 = list.AddItem(iteminfo);
    list1["Names"] = "Sam";
    list1.Update();
    cont.ExecuteQuery();
    

    2. JavaScript



    The Managed .NET client side object model is JavaScript Client Object Model ( JS CSOM ). JS CSOM allows the JavaScript code to execute on pages within the context of SharePoint to talk back without complete page postback.

    The JS CSOM is built to execute batch requests for good performance. The JS CSOM is designed for asynchronous calls and callbacks. The transactions needs time to complete the execution.

    For accessing the JS CSOM calling page, the following files are referred.
    1. SP.Runtime.js
    2. SP.js
    User can find these files in the following locations of the SharePoint 2013 server.

    Code:
    %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS
    
    Setup

    The pages executing within the context of SharePoint has appropriate JavaScript references defined in the master. User does not need to refer them in every page of the application. The page is served from the same domain as SharePoint.

    User can view in the Page declaration that the page used the SharePoint master page.
    Code:
    <%@ Page Inherits="Microsoft.SharePoint.WebPartsPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, MasterPageFile="~masterurl/default.master" language="C#" %>
    
    If the page does not use the SharePoint pages, the references are added to the JavaScript files. The following code adds the references to the page.
    Code:
    <script type="text/javascript">
    	src = "https"//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js">
    </script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.debug.js">
    </script>
    <script type="text/javascript" src="/_layouts/15/sp.debug.js">
    </script>
    
    Querying

    The JS CSOM contains built in batching and filtering. When the browser executing the client side code is remote, it is useful. The responsiveness and faster execution of an application depends on few requests and return the data really in need.

    The get_Current() method is used for returning the context associated with site.

    Code:
    var clientcontext = context = new SP.ClientContext.get_current();
    
    When the user queries list and libraries, choice for a specific item is possible. The ID can be known by the getItemsById ( id ) method or using the getItems(query) method.

    The following code snippet shows the code for querying the data using simple list of all items where Title column is Books.
    Code:
    var list = listContent.get_web().get_lists().getByTitle('Custom List');
    
    var query1 = new SP.CamlQuery();
    
    query1.set_viewXml(
    '<View><Query><Where><Eq><FieldRef= Name=\'Title\'>' +
    '<Value Type=\'Text\'>New Item 1</Value></Eq></Where></Query>' + 
    '<RowLimit>20</RowLimit></View>');
    
    	items = list.getItems(query1);
    	cont.load(items);
    	cont.executeQueryAsync(myQuerySucceded, myQueryFailed);
    

    3. Windows Phone assemblies



    The CSOM libraries are useful for both Windows Phone and Silverlight. The common library for integrating the Windows phone mobile apps is similar to JavaScript based SharePoint hosted application.

    The Windows Phone CSOM provides support to the authentication options like forms authentication, basic authentication, and Office 365 authentication. Every authentication option is wrapped separately.

    Setup

    The following components are needed for communicating with SharePoint.
    1. Windows Phone SDK 7.1
    2. Windows 7 or vista
    3. Visual Studio
    4. SharePoint SDK for Windows Phone
    5. SharePoint server with Office 365 site
    The CSOM libraries are located in the following reference.
    Code:
    %ProgramFiles (x86) %\Microsoft SDKs \ SharePoint\v15.0\Phone\v7.1\Libraries
    
    The directory consists of the DLLs Microsoft.SharePoint.Client.Phone.dll, Microsoft.SharePoint.Client.Phone.Runtime.dll, Microsoft.SharePoint.Phone.Application.dll.

    Querying

    Create a ClientContext object and set the Credentials property. The following code snippet shows the setting of the property using Office 365.
    Code:
    Clientcontext cont = new ClientContext("https://user.sharepoint.com/");
    Authenticator auth = new Authenticator();
    auth.AuthenticationMode = ClientAuthenticationMode.MicrosoftOnline;
    cont.Credentials = auth;
    
    If the Forms Authentication is used, username and password can be added as shown below:
    Code:
    auth.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
    
    auth.UserName = "User1";
    auth.Password = "Pass";
    
    Once the authentication options are specified, CSOM calls can be made to the SharePoint. The following code shows the CSOM call for accessing a list from the server.
    Code:
    List list = cont.Web.Lists.GetByTitle('Custom List");
    cont.Load(list);
    cont.ExecuteQueryAsync( ( object obj, ClientRequestSuccededEventArgs args) =>
    {
    	var SiteId = list.Id;
    },
    (object obj, ClientRequestFailedEventArgs args ) =>
    {
    	//query failed
    });
    
    In the above code, the success or failure function using lambda expression is defined.

    4. REST and OData



    REST represents Representational State Transfer used for designing the consumed APIs over Internet. The principles of the REST are as mentioned below:
    1. Client server: The client is not aware of the server, the storage mechanism, etc
    2. Stateless: The server does not save the state about the client
    3. Cacheable: The results define they are cacheable or not
    4. Layered: The client is not concerned about the calls to the API through common internet technology
    OData or Open Data Protocol is used for querying, finding, and updating data through HTTP. The common query operations are defined in the format the data is returned. The combination of REST and ODATA helps user with simple and easy APIs.

    _api is the base URI for REST/OData calls. The GET request is used to query the data. The PUT or MERGE request is used to pass the data user wants to update. The _api/web, _api/site, _api/search, _api/publishing are used with groups.

    If user wants all the list of SharePoint site, use the GET request as shown below:
    Code:
    https://servername/sitename/_api/web/lists
    
    Filtering and selecting data

    The data that is needed by the user needs to be retrieved. The delivery of data is faster. _Api uses the OData semantics helps user to filter records and select properties user wants. The operators used for data manipulation are as mentioned below:
    1. $filter is used for filtering the result
      Code:
      ?$filter=Names eq 'John'
      
    2. $select is used for selecting the properties to be returned
      Code:
      ?$filter=Names eq 'John' &$select=Names
      
    3. $expand is used to expand the properties
    4. $orderby is used to order the result
      Code:
      ?$select=Names&$orderby=Names
      
    5. $top is used to extract the top results
      Code:
      ?$select=Names&$orderby=Names&$top=1
      

    5. Silverlight assemblies



    The SharePoint 2013 object model of Silverlight is useful in all the applications that use Silverlight. It is not dependent on the xap file. They are in the assets library on the website, in cloud storage, client computer, or an external source.

    The client object model resembles to .NET framework client object model. In Silverlight, the commands are sent to the server asynchronously and the application remains active. The assemblies of the Silverlight object model are present at the location
    %ProgramFiles%\CommonFiles\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS\ClientBin.

    The .xap files are included in apps for SharePoint. The .xap file is deployed in the library on the app web. The Silverlight application a useful way of including custom SharePoint code in an app. The custom server side code is not allowed in apps for SharePoint.

    The SilverlightWebPart object is used in SharePoint 2013. The Silverlightweb Part class consists of constructors, members, methods, properties, and events.

    1. Constructor

    The syntax for the Silverlight Web part constructor is as shown below:

    public SilverlightWebPart()

    2. Properties
    1. AccessKey: It is inherited from the WebControl
    2. AllowClose: It is inherited from WebPart
    3. AllowHide: It is inherited from WebPart
    4. ApplicationXml: It is inherited from ClientApplicationWebPartBase
    3. Methods
    1. AddedControl: It is inherited from Control
    2. AddAttributesToRender: It is inherited from Panel
    3. ApplyStyle: It is inherited from WebControl
    4. BeginLoad: It is inherited from ClientApplicationwebPartBase
    5. CreateControlCollection: It is inherited from Control
    6. GetRouteUrl(String,Object): It is inherited from Control
    4. Events
    1. DataBinding: It is used for binding data to the specific control. It is inherited from the Control class.
    2. Init: It is used for initialization of the control.
    3. PreRender: It is the event rasied prior to rendering the control
    4. Unload: It is used when user needs to unload the components
    OAUTH in SharePoint

    OAuth is the open standard used for managing the Internet engineering task force. It is designed to allow applications to access the services in a Web friendly manner. The OAuth is used for calls authorization to SharePoint APIs. When discussing OAuth in context of SharePoint, the following naming convections are commonly used.
    1. Content owner: The user who installs the app and grants the application access to particular resources
    2. Client app: The app uses an API to access and make calls to the content server
    3. Content server: The SharePoint environment has the resources the client application needs to access.
    4. Authentication server: A service that server app and content server trust creates various tokens used for the OAuth process.
    The SharePoint apps fall into two different types in context to authentication and authorization.
    1. Internally authenticated apps: It includes SharePoint hosted apps
    2. Externally authenticated apps: It includes Auto hosted and provider hosted apps
    The difference between two categories is that the externally authenticated apps are authenticated with SharePoint. The internally authenticated apps are not.

    The externally authenticated app is where the code executes outside the security boundary. There are various IDs and tokens used for authenticating and authorizing the data.
    1. Client ID and client secret are pre issued identifiers that only SharePoint and the app is aware.
    2. Context token contains information about the caller. The Security Token Services are signed and issued tokens for the server.
    3. Access token is the token passed when the API is accessed.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice