Ads

Showing posts with label CSOM. Show all posts
Showing posts with label CSOM. Show all posts

Friday, 17 February 2017

REST API to Delete folder from document library

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
    <p>
        <b>Create Folder</b>
        <br />
        <input type="text" value="List Name Here" id=" DeleteFolder " />
        <button id="btnclick"> Delete Folder </button>
    </p>
</div>
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function FolderCreation()
{
    var executor;
 var getfoldername= document.getElementById("DeleteFolder").value;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
   url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('lib/Folder B')?@target='" + hostweburl + "'",
        method: "POST",
}        
          headers:  
            {
              "X-HTTP-Method":"DELETE"  
            },  
success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  
//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    alert("Folder Deleted successfully in Library");
}  
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not Delete a Folder in  Library: " + errorMessage);
}
//Utilities
// Retrieve a query string value.
// For production purposes you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) return singleParam[1];
    }
}  

REST to create folder in doc libraries

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
    <p>
        <b>Create Folder</b>
        <br />
        <input type="text" value="List Name Here" id="CreateFolder" />
        <button id="btnclick">Create Folder</button>
    </p>
</div>
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function FolderCreation()
{
    var executor;
    var getfoldername= document.getElementById("CreateFolder").value;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
  url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('lib')/folders?@target='" + hostweburl + "'",
        method: "POST",
        body: "{ '__metadata':{ 'type': 'SP.Folder' }, 'ServerRelativeUrl':'Folder B' }",
}
          headers:  
           {
             "accept": "application/json; odata=verbose",
    "content-type": "application/json; odata=verbose"
            },  
success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  
//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    alert("Folder Created successfully in Library");
}
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not Create a Folder in  Library: " + errorMessage);
}

Use REST API to play with list & Document library

Here we will use NAPA tool to write the REST scripts.

Open developer site --> Open NAPA office 365 development tool --> Add new project
If you don't have NAPA tool then search and install NAPA App in your site.

In default.aspx page write your HTML like below so that we can trigger the methods as per our need
Ex:
  1. <button id="btn_ID_Here"> Delete Folder </button>  (Here we need jQuery to fire click event) 
  2. <input id="btn_ID_Here" type="button" value="Click" onclick="ButtonClickFunction()"/>  
Now we will replace the default "app.js " file with below codes

------------------------------------------ JS code Start Here --------------------------
'use strict';
var hostweburl;
var appweburl;
 // Get the URLs for the app web the host web URL from the query string.
$(document).ready(function ()
 {
    //Get the URI decoded URLs.
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
 
    // Resources are in URLs in the form:
    // web_url/_layouts/15/resource  
 
    // Load the js file and continue to load the page with information about the folders.
    // SP.RequestExecutor.js to make cross-domain requests
    $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js");

//Below one is optional to bind click function to normal html as in example 1 above
         $("#btn_ID_Here").click(function (event)
        {  
            ButtonClickFunction();  
            event.preventDefault();  
        }); 
});

// ------- Your Custom functions Starts Here
//Button Click Calling Function Here
function ButtonClickFunction()
{
     
}
//1. REST API to Upload file in document library
//2. REST API to Get File versions in document library
//3. REST API to CheckIn file
//4. REST API to Add template file in doc lib
//5. REST API to Checkout file
//6. REST to Delete folder from document library
//7. REST to Create folder in doc lib
//8. REST to Get all folders from root site


// ------- Your Custom functions Ends Here    

function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) return singleParam[1];
    }
}
------------------------------------------JS Code End Here --------------------------

Once coding done specify the permissions that your app needs as in the following:
Choose the Properties button at the bottom of the page.

    In the Properties window, choose Permissions.
    In the Content category, set Write permissions for the Tenant scope.
    In the Social category, set Read permissions for the User Profiles scope.
    Close the Properties window.

Publish the App and Click the Trust it Button.









REST to Get all folders from root site

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
        <p>
            <b>Retrive Folders</b>
            <br />
            <select style="height:500px; width:510px" multiple="multiple" id="allFolders"></select>
        </p>
</div
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function getFolders() {
    var executor;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/folders?@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  

//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    var jsonObject = JSON.parse(data.body);
    var allFolders = document.getElementById("allFolders");
    if (allFolders.hasChildNodes()) {
        while (allFolders.childNodes.length >= 1) {
            allFolders.removeChild(allFolders.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++) {
        var Option = document.createElement("option");
        Option .value = results[i].Name;
        Option .innerText = results[i].Name;
        allFolders.appendChild(Option );
    }
}
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not retrieve  Folders: " + errorMessage);
}




REST APIs to play with SharePoint Groups


Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

Source Code in JS file:
Here we can call different methods from html button click as per need to perform action.
------------------------------------------------------------------------------------------------------------------------
    'use strict';
     
    var hostweburl;
    var appweburl;
 
    $(document).ready(function ()
    {
        //Get the URI decoded URLs.
        hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
     
        // Load the js file and continue to load the page with information about the folders.
        // SP.RequestExecutor.js to make cross-domain requests
        $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js",creategroup);
    });
//--------------- ----------------------
     
    //Create Group
    function creategroup()
    {
        var executor;
         // Initialize the RequestExecutor with the app web URL.
        executor = new SP.RequestExecutor(appweburl);
     
        executor.executeAsync({
      url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups?@target= '" + hostweburl + "'",  
            method: "POST",
      body: “{'__metadata':{ 'type': 'SP.Group' }, 'Title':'New Group'}”,
            headers:  
            {  
                "content-type": "application/json; odata=verbose"
            },  
            success: function(data)  
            {  
                alert("Group CREATED SUCCESSFULLY ");  
            },  
            error: function(err)  
            {  
                alert("error: " + JSON.stringify(err));  
            }      });
    }
//--------------- ----------------------     

//Retrieve Groups
function retrivegroup()
{
    var executor;
    // Initialize the RequestExecutor with the app web URL.  
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups?@target= '" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: getGroupsSuccessHandler,
        error: function(err) {
            alert("error: " + JSON.stringify(err));
        }
    });
}

function getGroupsSuccessHandler(data)
{
    var jsonObject = JSON.parse(data.body);
    var Groups = document.getElementById("RetriveGroups");
    if (Groups.hasChildNodes())
    {
        while (Groups.childNodes.length >= 1)
        {
            Groups.removeChild(Groups.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++)
    {
        var allgroups = document.createElement("option");
        allgroups.value = results[i].Title;
        allgroups.innerText = results[i].Title;
        Groups.appendChild(allgroups);
    }
}
//--------------- ----------------------

//Delete Users in groups
function DeleteUser()
{
    var executor;
    var userEmail = "gowthamdev@Gauti.onmicrosoft.com";
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users/getbyemail('" + userEmail + "')?@target='" + hostweburl + "'",
        method: "POST",
        headers: {
            "X-HTTP-Method": "DELETE"
        },
        success: function(data) {
            alert("User Deleted successfully in SharePoint Group");
        },
        error: function(err) {
            alert("error: " + JSON.stringify(err));
        }
    });
}
//--------------- ----------------------

//GetUsers in group
function getuser()
{
    var executor;
    var userEmail = "gowthamdev@Gauti.onmicrosoft.com";
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users?@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: getUsersFromGroupSuccess,
        error: getUsersFromGroupError
    });
}
//Populate the selectUsers control after retrieving all of the users from group.
function getUsersFromGroupSuccess(data)
{
    var jsonObject = JSON.parse(data.body);
    var RetriveUsers = document.getElementById("RetriveUsers");
    if (RetriveUsers.hasChildNodes())
    {
        while (RetriveUsers.childNodes.length >= 1)
        {
            RetriveUsers.removeChild(RetriveUsers.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++)
    {
        var selectOption = document.createElement("option");
        selectOption.value = results[i].LoginName;
        selectOption.innerText = results[i].LoginName;
        RetriveUsers.appendChild(selectOption);
    }
}
function getUsersFromGroupError(data, errorCode, errorMessage)
{
    alert("Could not get users from group: " + errorMessage);
}
//--------------- ----------------------

    //Utilities
    // Retrieve a query string value.
    // For production purposes you may want to use a library to handle the query string.
    function getQueryStringParameter(paramToRetrieve)
    {
        var params = document.URL.split("?")[1].split("&");
        for (var i = 0; i < params.length; i = i + 1)
       {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve) return singleParam[1];
        }
    }

Refer Here: One, 

Use REST API & Angular JS Implement custom search for lookup & person/group

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Create 2 custom lists
    Product Sales
    Phone

In Phone Custom list, I created  Title,Priority, and Demo single line text data type columns. And in second List i.e Produc Sales, I have created Product,Total_x0020_Sales,Sales_x0020_Target,SalesPerson,LPhone and SalesName.
    Here,"LPhone" is Lookup Field link with our Phone Custom list field of Title.
    "SalesName" is person/Group filed type and Show Field is FirstName.

angularGet.js (Upload it in Site Asset library of SharePoint along with angular js file)
var spApp = angular
                .module("spApp", [])
                .controller("viewItemController", function ($scope, $http) {
                    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Product%20Sales')/items?$select=Product,Total_x0020_Sales,Sales_x0020_Target,SalesPerson,SalesName/FirstName,LPhone/Title&$expand=LPhone,SalesName";
                    $http(
                    {
                        method: "GET",
                        url: url,
                        headers: { "accept": "application/json;odata=verbose" }
                    }
                    ).success(function (data, status, headers, config) {
      var dataResults=data.d.results;
      var item = data.d.results[1];  
         
                        $scope.contacts = dataResults;
       $scope.productItems = function(item)
      {
       
        if($scope.searchText==undefined)
       {
         return true;
        }
        else{
         if((item.SalesPerson.toLowerCase().indexOf($scope.searchText.toLowerCase())!=-1)||(item.Product.toLowerCase().indexOf($scope.searchText.toLowerCase())!=-1))
         {
          return true;
         }
        }
        return false;
       }
                    }).error(function (data, status, headers, config) {
                    });
                   
                })

Create.HTML file: (Upload in site asset library or write in content editor webpart)
<html>

<head>
    <script type="text/javascript" src="/SiteAssets/angular.min.js"></script>
    <script type="text/javascript" src="/SiteAssets/angularGet.js"></script>
</head>

<body>
    <h3>View Contacts</h3>
    <hr/>
    <div ng-app="spApp">
        <div ng-controller="viewItemController"> <input type="text" placeholder="Product&SalesPerson" ng-model="searchText" /> <br/><br/>
            <table>
                <tr>
                    <th>Product</th>
                    <th>Total Sales</th>
                    <th>Sales Target</th>
                    <th>Sales Peron</th>
                    <th>LookUPFieldData</th>
                    <th>Person/GroupField</th>
                </tr>
                <tr ng-repeat="contact in contacts|filter:productItems">
                    <td>{{contact.Product}}</td>
                    <td>{{contact.Total_x0020_Sales}}</td>
                    <td>{{contact.Sales_x0020_Target}}</td>
                    <td>{{contact.SalesPerson}}</td>
                    <td>{{contact.LPhone.Title}}</td>
                    <td>{{contact.SalesName.FirstName}}</td>
                </tr> <br /> </table>
        </div>
        <hr /> </body>

</html>

Now finally add this in share point page add see the result. or open that html page if uploaded in site asset library and check.


AngularJS in a SharePoint 2013 page to add list item using CSOM

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Lets create one simple list form in angular to submit list item.

  1. Create one custom list "Employee Details"
    • FirstName, LastName, Location 
  2. Add one script editor web part to add script in page
    • Add web part --> Media & Content --> Script Editor --> ok to Add it
  3. Edit webpart in "edit Snippet" and write below codes

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  
<script>  
    function ContactsCtrl($scope) {  
        $scope.contact = { firstName: "", lastName: "", location: "" };  
        $scope.addContact = function ($event) {  
            var x = $scope.contact;  
            $event.preventDefault();  
            var clientContext = new SP.ClientContext.get_current();  
            var web = clientContext.get_web();  
            var list = web.get_lists().getByTitle('Employee Details');  
  
            // create the ListItemInformational object  
            var listItemInfo = new SP.ListItemCreationInformation();  
            // add the item to the list  
            var listItem = list.addItem(listItemInfo);  
            // Assign Values for fields  
            listItem.set_item('Title', x.firstName);  
            listItem.set_item('LastName', x.lastName);  
            listItem.set_item('FullName', x.firstName + " " + x.lastName);  
            listItem.set_item('Location', x.location);  
  
            listItem.update();  
  
            clientContext.executeQueryAsync(  
                Function.createDelegate(this, onQuerySucceeded),  
                Function.createDelegate(this, onQueryFailed)  
            );  
  
        };  
  
        onQuerySucceeded = function () {  
            alert('Successfully updated the contact');  
        }  
  
        onQueryFailed = function (sender, args) {  
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
        }  
    }  
</script>  
   
<h1>Employee Information:</h1>  
<br />  
<div ng-app="">  
    <div ng-controller="ContactsCtrl">  
        <strong>Emp First Name</strong>  
        <input type="text" ng-model="contact.firstName" /><br />  
        <br />  
        <strong>Emp Last Name</strong>   
        <input type="text" ng-model="contact.lastName" /><br />  
        <br />  
        <strong>Emp Location </strong> 
        <input type="text" ng-model="contact.location" /><br />  
        <br />  
        <input type="submit" value="Submit" ng-click="addContact($event)" />  
    </div>  
</div>  


Tuesday, 14 February 2017

Get "CreatedBy" and "ModifiedBy" from list using client coding

<script language="ecmascript" type="text/ecmascript">

        var listItem;
        var list;
        var clientContext;

        function getFieldUserValue() {

            this.clientContext = SP.ClientContext.get_current();
            if (this.clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("CustomList");
                this.listItem = list.getItemById(1);
                clientContext.load(this.listItem);
                this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }

        function OnLoadSuccess(sender, args) {
            var fieldUserValueCreatedBy = this.listItem.get_item("Author");
            var fieldUserValueModifiedBy = this.listItem.get_item("Editor");
            alert("Created By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n Modified By: " + fieldUserValueModifiedBy.get_lookupValue() + "\n");
        }


        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>

    <input id="btnGetFieldUserValue" onclick="getFieldUserValue()" type="button" value="Get Created by and Modified by" />

Connect SharePoint online using CSOM from console application


Create new console application project in VS 2013
R-click on References in the Solution Explorer --> click on Manage NuGet Packages.
Search for Microsoft.SharePointOnline.CSOM and then click on Install

Code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Security;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.SharePoint.Client;
    namespace CSOMOffice365  
    {
        class Program  
        {
            static void Main(string[] args)  
          {
                string userName = "BlaBla.onmicrosoft.com";
                Console.WriteLine("Enter password.");
                SecureString password = GetPassword();  
                using(var clientContext = new ClientContext("SharePoint site URL"))  
                {
                    // SharePoint Online Credentials
                    clientContext.Credentials = new SharePointOnlineCredentials(userName, password);  
                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                    Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
                    Console.ReadLine();
                }
            }
            private static SecureString GetPassword()
          {
                ConsoleKeyInfo info;
                SecureString securePassword = new SecureString();
                do  
                {
                    info = Console.ReadKey(true);
                    if (info.Key != ConsoleKey.Enter)  
                    {
                        securePassword.AppendChar(info.KeyChar);
                    }
                }
                while (info.Key != ConsoleKey.Enter);
                return securePassword;
            }
        }
    }


List search using Angular JS

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Lets assume to do search in a custom list called "ListA"

Create one js file "ListSearch.js" and upload in any library
var spApp = angular.module("spApp", []).controller("viewItemController", function($scope, $http) {
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('ListA')/items";
    $http({
        method: "GET",
        url: url,
        headers: {
            "accept": "application/json;odata=verbose"
        }
    }).success(function(data, status, headers, config) {
        var dataResults = data.d.results;
        $scope.contacts = dataResults;
    }).error(function(data, status, headers, config) {});
})

Create one html file with below html or we can put it in a content editor to get the result.

    <html>
   
    <head>
        <script type="text/javascript" src="/SiteAssets/jquery-3.0.0.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/angular.min.js"></script>
        <script type="text/javascript" src="/SiteAssets/listSearch.js"></script>
    </head>
   
    <body>
        <h3>View Contacts</h3>
        <hr/>
        <div ng-app="spApp">
            <div ng-controller="viewItemController"> Search Items:<input type="text" placeholder="searchItems" ng-model="searchText" />
                <table>
                    <tr>
                        <th>Product</th>
                        <th>Total Sales</th>
                        <th>Sales Target</th>
                    </tr>
                    <tr ng-repeat="contact in contacts|filter:searchText">
                        <td>{{contact.Product}}</td>
                        <td>{{contact.Total_x0020_Sales}}</td>
                        <td>{{contact.Sales_x0020_Target}}</td>
                    </tr> <br /> </table>
            </div>
            <hr /> </body>
   
    </html>



Get lookup column values using REST


I have source list named: Managers
I have one site column Managers which is a lookup column to Managers--> Title column
I have another list "Details" where we use lookup column "Manager"

getListItems(_spPageContextInfo.webAbsoluteUrl,'?$select=Managers/Title,Managers/Id&$expand=Managers','Details',
function(items){
if(items.length > 0)
console.log(items[0].Managers.Title);
console.log(items[0].Managers.Id);
},
function(error){
console.log(error.responseText);
});

Wednesday, 1 April 2015

Start Client Object Model

SharePoint 2007 allows using its Object model to run against server running SharePoint. For clients (not running SharePoint in the box) the simplest way to communicate with SharePoint server is web services. SharePoint Client Object Model (OM) can be run on client PC (where SharePoint is not installed) to communicate with SharePoint server. So whereas SharePoint (Server) Object Model runs in a SharePoint server and can manipulate SharePoint objects, Client OM can run in client PC and communicate with SharePoint server remotely.

SharePoint 2010 introduces three new client APIs which can be used to interact with SharePoint sites. The three APIs are targeted for three different types of clients:
  1. For .net Managed applications (Eg: console applications, window applications, web applications).
  2. For Silverlight applications.
  3. For using with JavaScript (called ECMAScript or JSOM). 
    • This API is only available for applications hosted inside SharePoint (for example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript).
Lets see  some basic problems SharePoint 2017 in absence of Client Object Model.

Why Client Object Model (OM)?

SharePoint 2007 had no Client Object model available. So you may ask why this is introduced in SharePoint 2010? We had no problem without Client OM and millions of sites are running smoothly without having Client OM. The main reason is that Microsoft has found lot of requests from SharePoint users to introduce more and more web services to get data out of SharePoint in the last couple of years. But introducing web services will not fix the issues, as Microsoft found, because then the request for more functionality in the web services will continue. Even if Microsoft provides a good numbers of web services with SharePoint, customization in web services will be required for different clients and this will make the out of the box web services unusable. Also introducing a large number of web services will be a waste as not all companies will use all the web services functionalities.

In response to add more web services from users, Microsoft has taken a different approach called Client Object Model (OM). This SharePoint Client OM will allow getting data out of SharePoint from PCs that are not hosting SharePoint. Also Client OM provides complete API to interact with SharePoint Server which is more intuitive and useful and very much similar with SharePoint Object Model.

Similarity with SharePoint Object Model

The Client OM familiar with SharePoint Object Model as below.
Server (Microsoft.SharePoint) Client Object Model
SPContext ClientContext
SPSite Site
SPWeb Web
SPList List
SPListItem ListItem
SPField Field
So the class names in Client OM are similar as like SharePoint Object Model. However the way client OM will be used a bit different than usual SharePoint Object Model that we will explore in the upcoming posts.

How Client OM is developed and work under the hood?

It’s interesting how SharePoint team has developed the same set of classes for three different sets of applications (Managed, Silverlight and ECMAScript)
Client Type Assembly/File
Managed Client Microsoft.SharePoint.Client
Silverlight Microsoft.SharePoint.Client.Silverlight
ECMAScript SP.js or SP.debug.js
To ensure the same class object (say ListItem) behaves similarly in three different types of applications SharePoint team followed the steps described below:
a) SharePoint team first set attributes to the SharePoint classes and methods and properties that need to be exposed in Client OM.
b) Then a code generator is run against the SharePoint object model to generate client OM automatically.

This automated code generation has ensured maximum compatibility between these three sets of APIs. As the following figure shows client communicate to the server thorough Client OM which under the hood uses Client.svc WCF service to communicate with SharePoint Server. Client.svc service uses Server OM as per client request and return result to the client in JSON format.


image
Figure: How Client Object model works with Server
With this new Client OM, we almost don’t need to use web service to communicate with SharePoint server.
  
Client Object Model for JavaScript (ECMAScript)

Lets go through Client OM for JavaScript. ECMAScript Client OM is SharePoint 2010 client object model extension for using with JavaScript or JScript. Few points to notice about ECMAScript Client OM:
  • ECMAScript object model can only be used in SharePoint sites. So you can’t use this object model in an asp.net site to access SharePoint resources deployed in another url as this is cross-site scripting and not allowed.
  • You can’t use this object model in a SharePoint site to access resources in different SharePoint sites(i.e., different urls).
  • You can use JQuery with ECMAScript Client OM by adding reference to JQuery.js.
    • <SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true" 
          Localizable="false" /> 
  • You can use this ECMAScript Client OM in web part pages or application pages (aspx pages) by referencing a javascript file (SP.js). You don’t need to add reference to the file manually.
    •  Rather use <SharePoint:ScriptLink Name=”sp.js” ………. />. 
    • Location: “Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS”
  • To update with JavaScript, you need to add a FormDigest tag in your page for security purpose. I’ll explain it later in details. 
    •  If your code modifies SharePoint content add a FormDigest control inside your page. The FormDigest add a security token inside your page based on user, site and time. 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. Add the FormDigest inside <form>…</form> tag, as shown below:
    • <SharePoint:FormDigest runat="server" />
       
 Use Client OM to retrieve data:
 
<script type="text/javascript">
    function getWebProperties() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        ctx.load(this.web);
        ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
            Function.createDelegate(this, this.onFail));
    }
    function onSuccess(sender, args) {
        alert('web title:' + this.web.get_title() + '\n ID:' + this.web.get_id() + 
            '\n Created Date:' + this.web.get_created());
    }
    function onFail(sender, args) {
        alert('failed to get list. Error:'+args.get_message());
    }
</script>

 Load minimal data if need:
  1. ctx.load(this.web,'Title','Id','Created');
 Execute your JavaScript function after sp.js is loaded:
  1.  ExecuteOrDelayUntilScriptLoaded(myjsfucntion, "sp.js");

 Update with ECMAScript Library:


<script type="text/javascript">
    function updateTitle() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
        web.set_title('UpdatedTitle');
        this.web.update();
        ctx.executeQueryAsync(Function.createDelegate(this, this.onUpdate),
            Function.createDelegate(this, this.onFail));
    }
    function onUpdate(sender, args) {
        alert('title updated');
    }
    function onFail(sender, args) {
        alert('failed to update title. Error:'+args.get_message());
    }
</script>

Deployment Consideration

SharePoint provides two sets of JavaScript file: minified and unminified/debug version.
  1. sp.js file is minified 
  2. sp.debug is minified and debug version. 
The default master page in SharePoint has a scriptmanager in the page and whose ScriptMode is set to auto, as a result the minified version of js file loaded. If you want to use debug version you can add the
<deployment retail="false" /> in the <system.web> section of the web.config.

The ECMAScript supported in the following browsers:
  • Microsoft Internet Explorer 7.0 or greater.
  • Firefox 3.5 or greater
  • Safari 4.0 or greater

Monday, 8 July 2013

Client Object Model Access Large Lists

If you want retrieve large list using Client Object Model. You can use the ListItemCollectionPosition class to implement paging list item retrieval according to the position of items relative to their collection. Use the RowLimit element to specify the number of items to return per page.

Download Working Example


 static void Main(string[] args)
        {
            ClientContext clientContext = new ClientContext("URL Here");

            List list = clientContext.Web.Lists.GetByTitle("Tasks");

            ListItemCollectionPosition itemPosition = null;
            while (true)
            {
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ListItemCollectionPosition = itemPosition;
                camlQuery.ViewXml = @"<View>
                                        <ViewFields>
                                          <FieldRef Name='Title'/>
                                        </ViewFields>
                                        <RowLimit>1</RowLimit>
                                      </View>";

                ListItemCollection listItems = list.GetItems(camlQuery);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
                
                itemPosition = listItems.ListItemCollectionPosition;
                
                foreach (ListItem listItem in listItems)
                    Console.WriteLine("Item Title: {0}", listItem["Title"]);
                
                if (itemPosition == null)
                    break;
                
                Console.WriteLine(itemPosition.PagingInfo);
                Console.WriteLine();
            }

            Console.ReadLine();
        }

Client Object Model Exception Handling Scope

When we perform the operations on client side, we need to make a require to execute some operations that depend on the presence of an exception or not. We all have used try and catch blocks so far.
Lets take an example to understand: if you want to access a specific list in the SharePoint 2010 site in order to modify its property to allow Folder creation and versioning.

public void AllowFolderAndVersionCreation(string listName)
        {
            ClientContext context = new ClientContext("
http://anmol-pc");
            using (context)
            {
                List myList = null;
                try
                {
                    myList = context.Web.Lists.GetByTitle(listName);
                    context.Load(myList);
                    context.ExecuteQuery();

                }
                catch
                {
                    ListCreationInformation info = new ListCreationInformation();
                    info.Title = listName;
                    info.TemplateType = (int)ListTemplateType.GenericList;

                    myList = context.Web.Lists.Add(info);
                    context.ExecuteQuery();
                }
                finally
                {
                    myList.EnableVersioning = true;
                    myList.EnableFolderCreation = true;
                    myList.Update();
                    context.ExecuteQuery();
                }

            }
        }



Issue with Try and Catch Block
If you see the above i am first trying to get a list by Title in try block, and if list not found in catch block i tried to create a new list and Then in finally block i updated "EnableFolderCreation", "EnableVersioning" properties of list. To acheive this I require to send three commands to the server. So in SharePoint 2010 Client Object Model it is not convenient to use the try and catch blocks in the operations. The reason why is very easy to understand: we are in a client-side context and we have to pay attention to the number of queries to the server in order to execute our operations.

How ExceptionHandlingScope comes to rescue?
SharePoint 2010 Client object Model provides a class ExceptionHandlingScope for exception management. It exposes basic four methods StartScope(), StartTry(), StartCatch() and StartFinally().
Exception Handling scope begins with Startscope() and other three as three difrent sections inside

 public void AllowFolderAndVersionCreation(string listName)
        {
            var context = new ClientContext("
http://anmol-pc");
            var _ExceptionHandlingScope = new ExceptionHandlingScope(context);

            using (_ExceptionHandlingScope.StartScope())
            {
                using (_ExceptionHandlingScope.StartTry())
                {
                    // the code you want to try
                }
                using (_ExceptionHandlingScope.StartCatch())
                {
                    //code to run on error
                }
                using (_ExceptionHandlingScope.StartFinally())
                {
                    // the code that will execute finally
                }

           }
    }

lets place our example code inside this structure


public static void AllowFolderAndVersionCreation(string listName)
        {
            var context = new ClientContext("
http://anmol-pc");
            var _ExceptionHandlingScope = new ExceptionHandlingScope(context);
            List myList = null;

            using (_ExceptionHandlingScope.StartScope())
            {
                using (_ExceptionHandlingScope.StartTry())
                {
                    myList = context.Web.Lists.GetByTitle(listName);
                    context.Load(myList);
                    // context.ExecuteQuery() not required here
                }
                using (_ExceptionHandlingScope.StartCatch())
                {
                    ListCreationInformation info = new ListCreationInformation();
                    info.Title = listName;
                    info.TemplateType = (int)ListTemplateType.GenericList;
                    myList = context.Web.Lists.Add(info);
                    // context.ExecuteQuery() not required here
                }
                using (_ExceptionHandlingScope.StartFinally())
                {
                    myList.EnableVersioning = true;
                    myList.EnableFolderCreation = true;
                    myList.Update();
                    // context.ExecuteQuery() not required here
                }
            }
            context.ExecuteQuery();
        }


So you can notice that same thing can be acheived using ExceptionHandlingScope using less calls to the server.

Use of the "Try and catch" block:
  • Definetly more than 1 call
  • The debug operations are more complicated.
  • Easily understandable code as we are known to this type of code.
Use of the "ExceptionHandlingScope" class:
  • With one call to server we can acheive our goal.
  • The debug operations are much easier.
  • The code may not look that clear.

Monday, 1 July 2013

Get Lookupvalue in client context using ecma script

<script language="ecmascript" type="text/ecmascript">

        var listItem;
        var list;
        var clientContext;

        function getLookUp() {
            this.clientContext = SP.ClientContext.get_current();
            if (this.clientContext != undefined && clientContext != null) {
                var webSite = clientContext.get_web();
                this.list = webSite.get_lists().getByTitle("Custom");
                this.listItem = list.getItemById(5);
                clientContext.load(this.listItem);
                this.clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
            }
        }

        function OnLoadSuccess(sender, args) {
            var lookup = this.listItem.get_item("LookupSingleValue");
            alert("Lookup Id: " + lookup.get_lookupId() + "\n Lookup Value: " + lookup.get_lookupValue());


        }

        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }</script>
    <input id="btnGetLookUp" onclick="getLookUp()" type="button" value="Get Look Up" />

Wednesday, 3 April 2013

How to handle Exception in client object model coding in Sharepoint

We are familiar with try, catch and finally. It has been around for many years. We cannot ignore that at all as it plays a vital role in development.

Same is the case when we write a client object model code for SharePoint 2010.

ExceptionHandlingScope is a new class that has been introduced in SharePoint 2010 which allows us to perform the same action.

Let’s say you are working with managed client object model.

Here is a way to get a context of ExceptionHandlingScope and to work with it.
ClientContext ccontext = new ClientContext("site collection path");           
ExceptionHandlingScope exceptionscope = new ExceptionHandlingScope(ccontext);           
using (exceptionscope.StartScope())
            {
                using (exceptionscope.StartTry())
                {
                               // Code Block
                }
 
                using (exceptionscope.StartCatch())
                {                    
                     //Code Block which handles the exception
                }
 
                using (exceptionscope.StartFinally())
                {                    
                    //Code Block that always executes
                }
            }
Let’s say you are working in ECMA client object model and would like to handle exception

function Example()
{
this.clientcontext = new SP.ClientContext.get_current();
var clientScope = new SP.ExceptionHandlingScope(this.clientcontext);
var startScope = clientScope.startScope();
var tryScope = clientScope.startTry();
// Code Block
tryScope.dispose();
var catchScope = clientScope.startCatch();
 //Code Block which handles the exception
catchScope.dispose();
var finallyScope = clientScope.startFinally();
//Code Block that always executes
finallyScope.dispose();
startScope.dispose();

}

Ads