Friday, 3 February 2017

CRUD Operation On List Items Using JSOM In SharePoint 2013


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. 

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

SharePoint  

Retrieve the list items

Retrieve the list items

Here is the main code in detail:
  1. function retriveListItem()  
  2. {  
  3.     //Get the current context   
  4.     var context = new SP.ClientContext();  
  5.     var list = context.get_web().get_lists().getByTitle(‘companyInfo’);  
  6.     var caml = new SP.CamlQuery();  
  7.     caml.set_viewXml("<View><Query><OrderBy><FieldRef Name=’Company’ Ascending='TRUE' /></OrderBy></Query></View>");  
  8.     returnedItems = list.getItems(caml);  
  9.     context.load(returnedItems);  
  10.     context.executeQueryAsync(onSucceededCallback, onFailedCallback);  
  11. }  
  12.   
  13. function onSucceededCallback(sender, args)  
  14. {  
  15.     var enumerator = returnedItems.getEnumerator();  
  16.     //Formulate HTML from the list items   
  17.     var MainResult = 'Items in the Divisions list: <br><br>';  
  18.     //Loop through all the items   
  19.     while (enumerator.moveNext())  
  20.     {  
  21.         var listItem = enumerator.get_current();  
  22.         var companyName = listItem.get_item(“Company ");   
  23.                 var Industry = listItem.get_item(“Industry ");   
  24.                         MainResult += MainResult + companyName + "-" + Industry + "\n";  
  25.                     }  
  26.                     //Display the formulated HTML in the displayDiv element   
  27.                 displayDiv.innerHTML = MainResult;  
  28.             }  
  29.             //This function fires when the query fails   
  30.         function onFailedCallback(sender, args)  
  31.         {  
  32.             //Formulate HTML to display details of the error   
  33.             var markup = '<p>The request failed: <br>';  
  34.             markup += 'Message: ' + args.get_message() + '<br>';  
  35.             //Display the details   
  36.             displayDiv.innerHTML = markup;  
  37.         } 
  38.    }
Create list item

Create list item

Here is the main code in detail:
  1. function AddListItem()  
  2. {  
  3.     var listTitle = "companyInfo";  
  4.     //Get the current client context  
  5.     context = SP.ClientContext.get_current();  
  6.     var airportList = context.get_web().get_lists().getByTitle(listTitle);  
  7.     //Create a new record  
  8.     var listItemCreationInformation = new SP.ListItemCreationInformation();  
  9.     var listItem = airportList.addItem(listItemCreationInformation);  
  10.     //Set the values  
  11.     Var industryVal = $("#Industry").val();  
  12.     var Company = $("#Company").val();  
  13.     listItem.set_item('Industry', +industryVal);  
  14.     listItem.set_item('Company', +new item);  
  15.     listItem.update();  
  16.     context.load(listItem);  
  17.     context.executeQueryAsync(AddListItemSucceeded, AddListItemFailed);  
  18. }  
  19.   
  20. function AddListItemSucceeded()  
  21. {  
  22.     retriveListItem();  
  23. }  
  24.   
  25. function AddListItemFailed(sender, args)  
  26. {  
  27.     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  28. }  
Update list item

Update list item

Here is the main code in detail:
  1. function updateListItem()  
  2. {  
  3.     var ListName = "companyInfo";  
  4.     var context = new SP.ClientContext.get_current(); // the current context is taken by default here  
  5.     //you can also create a particular site context as follows  
  6.     var lstObject = context.get_web().get_lists().getByTitle(ListName);  
  7.     this.lstObjectItem = lstObject.getItemById(1);  
  8.       
  9.     Var industryVal = $("#Industry").val();  
  10.     var Company = $("#Company").val();  
  11.     lstObjectItem.set_item('Industry', “+industryVal + ”);  
  12.     lstObjectItem.set_item('Company', ”+Company + ”);  
  13.     lstObjectItem.update();  
  14.         context.executeQueryAsync(Function.createDelegate(thisthis.onSuccess), Function.createDelegate(thisthis.onFailure));  
  15. }  
  16.   
  17. function onSuccess()  
  18. {  
  19.     retriveListItem();  
  20. }  
  21.   
  22. function onFailure(sender, args)  
  23. {  
  24.     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  25. }  
Delete list item

Delete list item

Here is the main code in detail:
  1. function deleteListItem()  
  2. {  
  3.     var listTitle = "companyInfo";  
  4.     //get the current client context  
  5.     context = SP.ClientContext.get_current();  
  6.     var airportList = context.get_web().get_lists().getByTitle(listTitle);  
  7.     //get the list item to delete  
  8.     var listItem = airportList.getItemById(1);  
  9.     //delete the list item  
  10.     listItem.deleteObject();  
  11.     context.executeQueryAsync(DeleteItemSucceeded, DeleteItemFailed);  
  12. }  
  13.   
  14. function DeleteItemSucceeded()  
  15. {  
  16.     retriveListItem();  
  17. }  
  18.   
  19. function DeleteItemFailed(sender, args)  
  20. {  
  21.     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  22. }  
Summary

In this article we explored SharePoint JSOM for CRUD operations on list items level. Hope it will be helpful.

Working with JSOM (JavaScript Object Model) on SharePoint Apps

In this article i have written how a developer should start working woith JSOM ( JavaScript Object Model) in SharePoint Apps development. Before going through code sample, these prerequisites to be taken care.  

Prerequisites:
















Make sure that these frameworks has been referred in the page:
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.RequestExecutor.js"></script>

Note: The sequence of these JS Frameworks should be as it is. 

CAML Query:

Sample Query:
"<View Scope='RecursiveAll'>"+
    "<ViewFields>"+
        "<FieldRef Name='FIELD_1' />"+
        "<FieldRef Name='FIELD_2' />" +
    "</ViewFields>" +
"<Query>" +
    "<OrderBy>" +
        "<FieldRef Name='Title' Ascending='False' />" +
    "</OrderBy>" +
"</Query>" +
"<RowLimit>3</RowLimit>" +
"</View>";

Note: 
<ViewFields> will load only selective fields
<OrderBy> will do sorting of data by Ascending or Descending
<RowLimit> will restrict the no of rows to be fetched from the list
<Query> may contain additional query which can be easily generated by U2U CAML builder
Intention to mention these parts because using U2U CAML Query builder, you will not get first three directly. But first three is very important from performance point of view. Load only that much data which is required. 

Code Samples

Sample code to retrieve list data :
var hostweburl;
var appweburl;
var context;
var appContextSite;
var factory;
var web;
var list;
var listitemcollection;

$(document).ready(function () {
    // Getting values from query string
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));     
    // Calling function to retrive data from list
    GetListData();
});

// Function to retrieve a query string value.
function getQueryStringParameter(paramToRetrive) {
    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] == paramToRetrive) return singleParam[1];
    }
}

// Function to get existing List data
function GetListData() {
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);
    web = appContextSite.get_web();
    list = web.get_lists().getByTitle("YOUR_LIST_NAME");
    var camlString = "YOUR_CAML QUERY GOES HERE";
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(camlString);
    listitemcollection = list.getItems(camlQuery);
    context.load(listitemcollection, "Include(FIELD_1, FIELD_2, FIELD_3)");
    context.executeQueryAsync(GetListSuccess, GetListError);
}

// Function to handle the success event for GetListData.
function GetListSuccess(data, req) {
    var enumerator = listitemcollection.getEnumerator();
    // iterating data from listitemcollection
    while (enumerator.moveNext()) {
        var results = enumerator.get_current();
        // data can be utilised here.. 
        console.log(results.get_item("FIELD_1"));
    }
}
// Function to handle the error event for GetListData
function GetListError(data, error, errorMessage) {
    console.log("Error: " + errorMessage);
}

Sample code to add list data : 

var hostweburl;
var appweburl;
var context;
var appContextSite;
var factory;
var web;
var list;
var listitemcollection;

$(document).ready(function () {

    // Getting values from query string
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
     
    // Calling function to add data to list
    AddListData();
});

// Function to retrieve a query string value.
function getQueryStringParameter(paramToRetrive) {
    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] == paramToRetrive) return singleParam[1];
    }
}

// Function to add new List data
function AddListData() {
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);    
    web =  appContextSite.get_web();
    list = web.get_lists().getByTitle("YOUR_LIST_NAME");

    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = list.addItem(listItemCreationInfo);
    newItem.set_item('FIELD_1', 'VALUE');
    newItem.update();
    context.load(newItem);
    context.executeQueryAsync(AddListSuccess, AddListError);
}

// Function to handle the success event for AddListData.
function AddListSuccess(data, req) {
    console.log("Details added successfully");
}

// Function to handle the error event for AddListData
function AddListError(data, error, errorMessage) {
    console.log("Could not complete cross-domain call: " + errorMessage);
}

Sample code to edit/update list data :

var hostweburl;
var appweburl;
var context;
var appContextSite;
var factory;
var web;
var list;
var listitemcollection;

$(document).ready(function () {

    // Getting values from query string
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
     
    // Calling function to add data to list
    EditListData();
});

// Function to retrieve a query string value.
function getQueryStringParameter(paramToRetrive) {
    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] == paramToRetrive) return singleParam[1];
    }
}

// Function to edit List data
function EditListData() {
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    appContextSite = new SP.AppContextSite(context, hostweburl);
    web = appContextSite.get_web();
    list = web.get_lists().getByTitle("YOUR_LIST_NAME");

    var oListItem = list.getItemById('LIST_ITEM_ID');    
    oListItem.set_item('FIELD_1', 'VALUE');
    oListItem.update();
    context.executeQueryAsync(EditListSuccess, EditListError);
}

// Function to handle the success event for EditListData.
function EditListSuccess(data, req) {
    console.log("Details updated successfully");

}

// Function to handle the error event for EditListData
function EditListError(data, error, errorMessage) {
    console.log("Error: " + errorMessage);
}

Monday, 26 December 2016

Save Site as Template Powershell Command

Save Site as Template Powershell Command


You can save your site as template even with the publishing feature using the following Powershell command

$Web=Get-SPWeb http://Server/Site
$Web.SaveAsTemplate("Template Name","Template Title","Template Description",1)

In the forth parameter of SaveAsTemplate(), if you want to save the specified site as template along with data use 1, otherwise use 0.
After running above commands, the newly created template will be available in site collection "Solutions" gallery

Friday, 16 December 2016

SharePoint: How to check which Site Template was used to create a site just using a web browser

SharePoint: How to check which Site Template was used to create a site just using a web browser

I recently needed to check which site template was used to create a site on a production system so I did not have the option to use SharePoint Manager or write some code or PowerShell to open the site and check the site template.

The solution is simply to browse to any page on the site, view the source HTML of the page, then search for “SiteTemplateID” where you will be taken straight to a line of JavaScript embedded into the page such as the following where the site template ID including configuration is assigned to a JavaScript variable:

var g_wsaSiteTemplateId = ‘STS#1’;


Nice and easy when you know how :-) 

SharePoint 2013 Site Template ID List for PowerShell

 

SharePoint 2013 Site Template ID
Template ID
Title
GLOBAL#0 Global template
STS#0 Team Site
STS#1 Blank Site
STS#2 Document Workspace
MPS#0 Basic Meeting Workspace
MPS#1 Blank Meeting Workspace
MPS#2 Decision Meeting Workspace
MPS#3 Social Meeting Workspace
MPS#4 Multipage Meeting Workspace
CENTRALADMIN#0 Central Admin Site
WIKI#0 Wiki Site
BLOG#0 Blog
SGS#0 Group Work Site
TENANTADMIN#0 Tenant Admin Site
APP#0 App Template
APPCATALOG#0 App Catalog Site
ACCSRV#0 Access Services Site
ACCSRV#1 Assets Web Database
ACCSRV#3 Charitable Contributions Web Database
ACCSRV#4 Contacts Web Database
ACCSRV#5 Projects Web Database
ACCSRV#6 Issues Web Database
ACCSVC#0 Access Services Site Internal
ACCSVC#1 Access Services Site
BDR#0 Document Center
DEV#0 Developer Site
DOCMARKETPLACESITE#0 Academic Library
EDISC#0 eDiscovery Center
EDISC#1 eDiscovery Case
OFFILE#0 (obsolete) Records Center
OFFILE#1 Records Center
OSRV#0 Shared Services Administration Site
PPSMASite#0 PerformancePoint
BICenterSite#0 Business Intelligence Center
SPS#0 SharePoint Portal Server Site
SPSPERS#0 SharePoint Portal Server Personal Space
SPSPERS#2 Storage And Social SharePoint Portal Server Personal Space
SPSPERS#3 Storage Only SharePoint Portal Server Personal Space
SPSPERS#4 Social Only SharePoint Portal Server Personal Space
SPSPERS#5 Empty SharePoint Portal Server Personal Space
SPSMSITE#0 Personalization Site
SPSTOC#0 Contents area Template
SPSTOPIC#0 Topic area template
SPSNEWS#0 News Site
CMSPUBLISHING#0 Publishing Site
BLANKINTERNET#0 Publishing Site
BLANKINTERNET#1 Press Releases Site
BLANKINTERNET#2 Publishing Site with Workflow
SPSNHOME#0 News Site
SPSSITES#0 Site Directory
SPSCOMMU#0 Community area template
SPSREPORTCENTER#0 Report Center
SPSPORTAL#0 Collaboration Portal
SRCHCEN#0 Enterprise Search Center
PROFILES#0 Profiles
BLANKINTERNETCONTAINER#0 Publishing Portal
SPSMSITEHOST#0 My Site Host
ENTERWIKI#0 Enterprise Wiki
PROJECTSITE#0 Project Site
PRODUCTCATALOG#0 Product Catalog
COMMUNITY#0 Community Site
COMMUNITYPORTAL#0 Community Portal
SRCHCENTERLITE#0 Basic Search Center
SRCHCENTERLITE#1 Basic Search Center
SRCHCENTERFAST#0 FAST Search Center
visprus#0 Visio Process Repository