Saturday, 14 April 2018

CRUD Operation On List Items Using JSOM In SharePoint 2013

Introduction

The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the JSOM. I have explored the CRUD operation using Web Service.

Now, I will demo all the operations on list items, including retrieve, create, update and delete on list items.

<table>
   <tbody>
      <tr>
         <td>Employee Name:</td>
         <td> 
            <input type="text" name="EmployeName"  id="txtEmpName"/> 
         </td>
      </tr>
      <tr>
         <td>Father Name:</td>
         <td> 
            <input type="text" name="FatherName" id="txtFatherName"/> 
         </td>
      </tr>
  
   <tr>
         <td col=2>
<input type="submit" value="Add" id="btAdd" onclick="AddListItem();">
<input type="submit" value="Update" id="btUpdate" onclick="UpdateListItem();">
<input type="submit" value="View" id="btView"  onclick="FetchAllItems();">
<input type="submit" value="Delete" id="btDelete" onclick="DeleteItem();">
</td>
         
      </tr>
 
   </tbody>
</table>
<div id="ResultDiv">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">  

ExecuteOrDelayUntilScriptLoaded(AddListItem() ,"sp.js");
ExecuteOrDelayUntilScriptLoaded(UpdateListItem() ,"sp.js");
ExecuteOrDelayUntilScriptLoaded(DeleteItem() ,"sp.js");
ExecuteOrDelayUntilScriptLoaded(FetchAllItems() ,"sp.js");

var siteUrl = '/sites/PracticeSite';

function AddListItem()  
{  
var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('PracticeList');
var empName=$('#txtEmpName').val();
var fatherName=$('#txtFatherName').val();
        
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
        
    oListItem.set_item('Title',empName );   
oListItem.set_item('Father_x0020_Name',fatherName );  
        
    oListItem.update();

    clientContext.load(oListItem);
        
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}
function onQuerySucceeded() {

    alert('Item created: ' + oListItem.get_id());
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


function UpdateListItem()  
{  
var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('PracticeList');

    this.oListItem = oList.getItemById(12);

    oListItem.set_item('Title', 'Utpal');

    oListItem.update();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded() {

    alert('Item updated!');
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function DeleteItem()  
{  
this.itemId = 12;

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('PracticeList');

    this.oListItem = oList.getItemById(itemId);

    oListItem.deleteObject();

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded() {

    alert('Item deleted: ' + itemId);
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

function FetchAllItems()  
{  
var context = new SP.ClientContext();  
    var list = context.get_web().get_lists().getByTitle('PracticeList');  
    var caml = new SP.CamlQuery();  
    caml.set_viewXml("<View><Query><Where><IsNotNull><FieldRef Name='LinkTitleNoMenu' /></IsNotNull></Where></Query></View>");  
    returnedItems = list.getItems(caml);  
    context.load(returnedItems);  
    context.executeQueryAsync(onSucceededCallback, onFailedCallback); 
}

function onSucceededCallback(sender, args)  
{  
    var enumerator = returnedItems.getEnumerator();  
    //Formulate HTML from the list items   
    var MainResult = 'Items in the Divisions list: <br><br>';  
    //Loop through all the items   
    while (enumerator.moveNext())  
    {  
        var listItem = enumerator.get_current();  
        var EmployeeName = listItem.get_item("Title");   
        var FatherName = listItem.get_item("Father_x0020_Name");   
        MainResult += MainResult + EmployeeName + "-" + FatherName + "\n";  
    }  
                    //Display the formulated HTML in the displayDiv element   
ResultDiv.innerHTML = MainResult;  
}  
            //This function fires when the query fails   
function onFailedCallback(sender, args)  
{  
            //Formulate HTML to display details of the error   
var markup = '<p>The request failed: <br>';  
markup += 'Message: ' + args.get_message() + '<br>';  
            //Display the details   
    ResultDiv.innerHTML = markup;  
}  


</script>  

CRUD Operation On List Items Using REST API Services In SharePoint 2013

Introduction 

SharePoint 2013 has greatly expanded the REST services available to developers. With this, we have much more SharePoint functionality exposed via JSOM and Web Services. The goal of this article is to provide how to perform basic create, read, update, and delete (CRUD) operations on lists and list items with the REST services.

SharePoint REST endpoint Overview:
The following table contains typical REST endpoint URL examples to get you started working with SharePoint data. Prepend http://server/site/_api/ to the URL fragments shown in the table to construct a fully qualified REST URL. Below is a list of the basic commands used to get List Items from a SharePoint List through the SharePoint 2013 REST Services.
URL endpointDescriptionSupported HTTP Method
/_api/Web/Lists/ getbytitle('listname')Getting a list details by its title and updating it as well. Ifanyone changes your list title, your code will break.GET, POST
/_api/Web/Lists(guid'guid id of your list')Same as above but changing list title will not affect the code.GET, POST
/_api/Web/Lists/getbytitle(' listname ')/FieldsRetrieving all fields associated with a list and add new fieldsGET, POST
/_api/Web/Lists/getbytitle('listname')/
Fields/getbytitle('fieldname')
Getting details of a field, modifying and deleting it.GET, PUT, PATCH, MERGE, DELETE
/_api/Web/Lists/getbytitle('listname')
/Items
Retrieving all items in a list and adding new itemsGET, POST
/_api/web/lists/getbytitle('listname')
/GetItemById(itemId)
This endpoint can be used to get, update and delete a single item.GET, PUT, PATCH, MERGE, DELETE
/_api/lists/ getbytitle (‘'listname')/items?$orderby=TitleOrder Your ResultsGET, POST
/_api/lists/ getbytitle (‘'listname')/items?$select=Title,IdRetrieve Selected Column Data valueGET, POST
/_api/web/lists/getbytitle('listname')/Items/
?$select=Title,FieldName/Id&$expand= FieldName /Id
Retrieving the lookup valueGET, POST

Now, I will demo all the operations on list items, including retrieve, create, update and delete on list items.


List Name: PracticeList
Fields: EmpName(Title), Father Name(Father_x0020_Name)



<table>
   <tbody>
      <tr>
         <td>Employee Name:</td>
         <td> 
            <input type="text" name="EmployeName"  id="txtEmpName"/> 
         </td>
      </tr>
      <tr>
         <td>Father Name:</td>
         <td> 
            <input type="text" name="FatherName" id="txtFatherName"/> 
         </td>
      </tr>
  
   <tr>
         <td col=2>
<input type="submit" value="Add" id="btAdd">
<input type="submit" value="Update" id="btUpdate">
<input type="submit" value="View" id="btView">
<input type="submit" value="Delete" id="btDelete">
</td>
         
      </tr>
 
   </tbody>
</table>
<div id="ResultDiv">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">  

$(document).ready(function(){
    $('input[id*="btAdd"]').click(function(){
      AddListItem();
    });

$('input[id*="btUpdate"]').click(function(){
      UpdateListItem();
    });

$('input[id*="btDelete"]').click(function(){
      DeleteItem();
    });

$('input[id*="btView"]').click(function(){
      FetchAllItems();
    });

});

function AddListItem()  
{  
var listName="PracticeList";
    var Title = $("#txtEmpName").val();  
    var FatherName = $("#txtFatherName").val();  
var itemType = GetItemTypeForListName(listName);  
var item = {
        "__metadata": { "type": itemType },
        "Title": Title,
"Father_x0020_Name": FatherName
    };
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('PracticeList')/items",  
        type: "POST",  
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },  
        success: function(data)  
        {  
            alert('Success');  
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}

function UpdateListItem()  
{  

var listName="PracticeList";

    var FatherName = $("#txtFatherName").val();  
var itemType = GetItemTypeForListName(listName);  
var item = {
        "__metadata": { "type": itemType },
        "Father_x0020_Name": FatherName
    };
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('PracticeList')/items('2')",  
        type: "POST",  
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
             "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "MERGE",
            "If-Match": "*"
        },  
        success: function(data)  
        {  
            alert('Success');  
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}

function DeleteItem()  
{  
var listName="PracticeList";   
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items('7')",  
        type: "POST",  
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
             "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "DELETE",
            "If-Match": "*"
        },  
        success: function(data)  
        {  
            alert('Success');  
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}

function FetchAllItems()  
{  
var listName="PracticeList";   
 
    $.ajax  
        ({  
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items",  
        type: "GET",        
        headers: {
             "Accept": "application/json;odata=verbose"            
        },  
        success: function(data)  
        {  
            alert('Success'); 
var out = '<table>';
  
            for (var i = 0; i < data.d.results.length; i++)   
            {  
                var item = data.d.results[i];  
                
out+='<tr><td>"'+item.Title +'"</tr></td>';
            } 
out+='</table>';
document.getElementById("ResultDiv").innerHTML = out;
        },  
        error: function(data)  
        {  
alert('Error'); 
            $("#ResultDiv").empty().text(data.responseJSON.error);  
        }  
    });  
}


function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}  


</script>  

Thursday, 12 April 2018

SharePoint Client Object Modal (CSOM)

Introduction
Client Side Object Model (CSOM) was first introduced in SharePoint 2010. The Client Side Object Model is mainly used to build client applications and enable us to access SharePoint Sites that are hosted outside without using web services. Prior to the CSOM, developers had only a few choices to build client applications.

However, this has changed now. With the introduction of CSOM, developers now have more choices and will be able to access the core SharePoint functionalities to a wide extent. In SharePoint 2010, the CSOM exposed the core SharePoint functionalities only whereas in SharePoint 2013, the Microsoft SharePoint team has added a few more assemblies. Now we are able to access the Service Applications using the Client Side Object Model.
model
There are three programming models used for the Client Side Object Model; they are:
  • .Net Client Side Object Model.
  • JavaScript Object Model.
  • Silverlight Object Model.
model 
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
Assemblies for the above models are located in the SharePoint file system. The .Net Client Side Object Model is located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI. The Silverlight Object Model is located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\ClientBin. ECMAScripts are located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15 \TEMPLATE\LAYOUTS.
How CSOM works
If you use the Client Side API to perform a specific task then the SharePoint .Net client object model bundles up these uses of the API into XML and send them to the server. The server receives this request, and makes appropriate calls into the object model on the server, collects the responses, forms them into JavaScript Object Notation (JSON), and sends that JSON back to the SharePoint .Net client object model.

The client object model parses the JSON and presents the results to the application.
csom
Load() method: the Load() method does not actually load anything, only when the ExecuteQuery() method is called does it provide notification that these are the property values that should be loaded for the object. In the Load() method lambda expressions can be used to specify which property should be loaded instead of loading all the properties.

ExecuteQuery() method: the ExecuteQuery() method sends the request to the server. There is no network traffic until the application calls this method. Until the ExecuteQuery() method is called only the requests are registered by the application.

csom

Create a console application using Visual Studio

In this section you will see how to create a console application using Visual Studio 2012 which will be used to explain all the examples for the .Net Client Side Object Model.

Steps Involved:
  1. Run Visual Studio as Administrator
  2. Create a Console Application,

    Application
  3. In the Solution Explorer, right-click on the “References” folder and then click on “Add Reference”.
  4. Add the following assemblies from hive 15 (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI).

    solution
Perform SharePoint list tasks using CSOM
In this section you will see how to perform list related tasks using the SharePoint 2013 .Net Client Side Object Model.

In this example you will see how to get all the lists from the website using the .Net Client Side Object Model.

Replace Program.cs with the source code below and run the application.

Source Code
  1. using Microsoft.SharePoint.Client;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace RK_CSOM_Demo  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             // ClientContext - Get the context for the SharePoint Site  
  15.             // SharePoint site URL - http://RKTest.com/sites/testsite/  
  16.             ClientContext clientContext = new  
  17.                 ClientContext("http://RKTest.com/sites/testsite/");  
  18.   
  19.             // Get the SharePoint web  
  20.             Web web = clientContext.Web;  
  21.               
  22.             // Get the SharePoint list collection for the web  
  23.             ListCollection listColl = web.Lists;  
  24.               
  25.             // Retrieve the list collection properties  
  26.             clientContext.Load(listColl);  
  27.   
  28.             // Execute the query to the server.  
  29.             clientContext.ExecuteQuery();  
  30.               
  31.             // Loop through all the list  
  32.             foreach (List list in listColl)  
  33.             {  
  34.                 // Display the list title and ID  
  35.                 Console.WriteLine("List Name: " + list.Title + "; ID: " + list.Id);  
  36.             }  
  37.             Console.ReadLine();  
  38.         }  
  39.     }  
  40. }  
Output
Output

CRUD operations examples with Client Object Model

Here I would like to list some examples using the Client Object Model. For starting with the examples, please do the following:

Get List Items
Here we are querying the list items of the Tasks list.

Source Code
  1. using Microsoft.SharePoint.Client;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace RK_CSOM_Demo  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             ClientContext clientContext = new  
  15.                 ClientContext("http://RKTest.com/sites/testsite/");  
  16.   
  17.             List list = clientContext.Web.Lists.GetByTitle("RK_List");  
  18.   
  19.             CamlQuery query = new CamlQuery();  
  20.             query.ViewXml = "<View/>";  
  21.             ListItemCollection items = list.GetItems(query);  
  22.   
  23.             clientContext.Load(list);  
  24.             clientContext.Load(items);  
  25.   
  26.             clientContext.ExecuteQuery();  
  27.   
  28.             foreach (ListItem item in items)  
  29.             {  
  30.                 Console.WriteLine(item.Id + " - " + item["Name"]);  
  31.             }  
  32.   
  33.             Console.ReadLine();  
  34.         }  
  35.     }  
  36. }  
Output

Output

Insert an Item

Here we can try inserting a new item into the Tasks list.

Source Code
  1. List list = clientContext.Web.Lists.GetByTitle("RK_List");  
  2.   
  3. ListItemCreationInformation newItem = new ListItemCreationInformation();  
  4. ListItem listItem = list.AddItem(newItem);  
  5. listItem["Title"] = "Kiran";  
  6. listItem["Name"] = "Kiran";  
  7. listItem["Location"] = "Bangalore";  
  8. listItem.Update();  
  9. clientContext.ExecuteQuery();  
Output
After executing the query, please refresh the list page. You can see the following result.

Output

Update List Item
Here I would like to show the modification code. All the titles are appended with two asterisks whose IDs are even number.

Source Code
  1. foreach (ListItem item in items)  
  2. {  
  3.     if (item.Id.ToString() == "1")  
  4.     {  
  5.         item["Location"] = "Bangalore";  
  6.         item.Update();  
  7.     }  
  8. }  
  9. clientContext.ExecuteQuery();  
Output
After executing the query, please refresh the list page. You can see the following result.

Output

Delete an Item
Now we can try deleting an item from the List. Here is the code to achieve that.

Source Code
  1. foreach (ListItem item in items)  
  2. {  
  3.     if (item.Id.ToString() == "1")  
  4.     {  
  5.         item.DeleteObject();  
  6.         break;  
  7.     }  
  8. }  
  9. clientContext.ExecuteQuery();  
Output
After executing the query, please refresh the list page. You can see the following result.
 
Output