Tuesday 17 November 2015

Create folder in SharePoint List using JSOM

There is always a need to create folder in SharePoint list using client side script and hence I thought of posting the code.
Below code will create folder in SharePoint List using JSOM and function will be fired from SharePoint Hosted Apps and hence this will cover how to get AppContext and how to create folder.



 function AddFolderToSPList(folderName) {  
     var oWebsite;  
     var oList, oListItem;  
     var itemCreateInfo;  
     var clientContext = new SP.ClientContext('appWebUrl');  
     var appContextSite = new SP.AppContextSite(clientContext, 'targetSiteUrl');  
     oWebsite = appContextSite.get_web();  
     oList = oWebsite.get_lists().getByTitle('ListName');  
     itemCreateInfo = new SP.ListItemCreationInformation();  
     itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);  
     itemCreateInfo.set_folderUrl(targetSiteUrl + "/Lists/" + "ListName");  
     //if you want to add subfolder then add folder url like below commented line  
     //itemCreateInfo.set_folderUrl(targetSiteUrl + "/Lists/" + "ListName"+"/parentfolder");  
     oListItem = oList.addItem(itemCreateInfo);  
     oListItem.set_item('Title', folderName);  
     oListItem.update();  
     clientContext.load(oListItem);  
     clientContext.executeQueryAsync(  
       Function.createDelegate(this, successHandler()),  
       Function.createDelegate(this, errorHandler)  
     );  
   }  
   function successHandler() {  
     alert('success');  
   }  
   function errorHandler() {  
     alert("Request failed: message = " + arguments[1].get_message());  
   }  

Saturday 7 November 2015

SharePoint People Picker using “clientpeoplepicker.js” or client side scripting


 <script src="/_layouts/15/SP.RequestExecutor.js"></script>  
 <script src="/_layouts/15/clienttemplates.js"></script>  
 <script src="/_layouts/15/clientforms.js"></script>  
 <script src="/_layouts/15/clientpeoplepicker.js"></script>  
 <script src="/_layouts/15/autofill.js"></script>  
 <script src="/_layouts/15/js"></script>  
 <script src="/_layouts/15/runtime.js"></script>  
 <script src="/_layouts/15/sp.core.js"></script>  
 <script type="text/javascript">  
   $(document).ready(function () {  
     // Specify the unique ID of the DOM element where the  
     // picker will render.  
     initializePeoplePicker('peoplePickerDiv');  
   });  
   // Render and initialize the client-side People Picker.  
   function initializePeoplePicker(peoplePickerElementId) {  
     // Create a schema to store picker properties, and set the properties.  
     var schema = {};  
     schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
     schema['SearchPrincipalSource'] = 15;  
     schema['ResolvePrincipalSource'] = 15;  
     schema['AllowMultipleValues'] = false;  
     schema['MaximumEntitySuggestions'] = 50;  
     schema['Width'] = '280px';  
     // Render and initialize the picker.  
     // Pass the ID of the DOM element that contains the picker, an array of initial  
     // PickerEntity objects to set the picker value, and a schema that defines  
     // picker properties.  
     this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);  
     alert('init end')  
   }  
   // Query the picker for user information.  
   function getUserInfo() {  
     // Get the people picker object from the page.  
     var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;  
     // Get information about all users.  
     var users = peoplePicker.GetAllUserInfo();  
     var userInfo = '';  
     for (var i = 0; i < users.length; i++) {  
       var user = users[i];  
       for (var userProperty in user) {  
         userInfo += userProperty + ': ' + user[userProperty] + '<br>';  
       }  
     }  
     $('#resolvedUsers').html(userInfo);  
     // Get user keys.  
     var keys = peoplePicker.GetAllUserKeys();  
     $('#userKeys').html(keys);  
     // Get the first user's ID by using the login name.  
     getUserId(users[0].Key);  
   }  
   // Get the user ID.  
   function getUserId(loginName) {  
     var context = new SP.ClientContext.get_current();  
     this.user = context.get_web().ensureUser(loginName);  
     context.load(this.user);  
     context.executeQueryAsync(  
        Function.createDelegate(null, ensureUserSuccess),  
        Function.createDelegate(null, onFail)  
     );  
   }  
   function ensureUserSuccess() {  
     $('#userId').html(this.user.get_id());  
   }  
   function onFail(sender, args) {  
     alert('Query failed. Error: ' + args.get_message());  
   }  
 </script>  
 <div id="peoplePickerDiv"></div>  
 <div>  
   <br />  
   <input type="button" value="Get User Info" onclick="getUserInfo()" />  
   <br />  
   <h1>User info:</h1>  
   <p id="resolvedUsers"></p>  
   <h1>User keys:</h1>  
   <p id="userKeys"></p>  
   <h1>User ID:</h1>  
   <p id="userId"></p>  
 </div>  

Create Dynamic Array from SharePoint List Items to Draw Google Pie Chart

This blog will focus on how to create dynamic array which can easily understood by google chart 's api.
This one I did for one of project approximate 17-18 months back but now I am posting this ;)
Requirement was to show the PIE Chart of the clients data based on their status. For this we need to have Status Column and of type Choice which may hold the value like “Completed, In Progress, Completed” or Whatever status we want.
Then this site Column will be added to the actual list where the content will reside and based.
So let’s start with the actual coding for which I am always excited. Below file can be a .txt file or html file and later on will be added to content editor webpart to display the pie chart.


 <script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization',  
     'version':'1','packages':['corechart']}]}"></script>  
 <style>  
   table th {  
     background-color: #73d1f2;  
     height: 34px;  
     text-align: left;  
     padding-left: 2%;  
     font: bold 13px Arial, Helvetica, sans-serif !important;  
     color: #777 !important;  
   }  
   .ms-listviewtable a:hover {  
     color: #777 !important;  
   }  
 </style>  
 <script type="text/javascript">  
   var siteUrl;  
   var arrBarChart = new Array();  
   $(document).ready(function () {  
     siteUrl = _spPageContextInfo.webAbsoluteUrl;  
     GetStatusColumn();  
   });  
   /// This method will read the Status Site Column  
   function GetStatusColumn() {  
     $.ajax({  
       url: siteUrl + "/_api/web/fields?$filter=Title eq'StatusColumnName'",  
       method: "GET",  
       headers: {  
         "Accept": "application/json; odata=verbose",  
         "content-type": "application/json; odata=verbose"  
       },  
       success: function (data) {  
         /// here i am checking whether it has some data or not  
         if (data.d.results[0].Choices.results.length > 0) {  
           // here i will pass siteurl and values from the site column  
           GetListHoldingDate(siteUrl, data.d.results[0].Choices.results);  
         }  
         else {  
           $("#lblError").text("Status Site Column do not exists or do not have values in it, please contact Administrator");  
         }  
       },  
       error: function (jqxr, errorCode, errorThrown) {  
       }  
     });  
   }  
   // this method will read the actual list content and will array required for pie chart  
   function GetListHoldingDate(siteUrl, columnData) {  
     var uspURL = siteUrl + "/_api/web/lists/getbytitle('ListHoldingData')/items"  
     $.ajax({  
       url: uspURL,  
       method: "GET",  
       headers: {  
         "Accept": "application/json; odata=verbose",  
         "content-type": "application/json; odata=verbose"  
       },  
       success: function (data) {  
         //alert(data.body);  
         var rowsStatus = "";  
         var itemCount = data.d.results.length;  
         for (var i = 0; i < columnData.length; i++) {  
           //below code will filter the data from all items based on status  
           var arr = $.grep(data.d.results, function (a) {  
             return a.StatusColumnName == columnData[i];  
           })  
           var perc = (arr.length / itemCount) * 100;  
           perc = Math.round(perc * 100) / 100  
           arrBarChart.push([columnData[i], parseInt(perc)]);  
         }  
         drawChart();  
       },  
       error: function (jqxr, errorCode, errorThrown) {  
         if (jqxr.status == "404") {  
           $("#lblError").text("List holding content not found, Please contact administrator");  
         }  
         else {  
           $("#lblError").text(jqxr.responseText);  
         }  
       }  
     });  
   }  
   //this method will create pie chart using google api  
   function drawChart() {  
     var data = new google.visualization.DataTable();  
     data.addColumn('string', 'Status');  
     data.addColumn('number', 'Percentage');  
     data.addRows(arrBarChart);  
     // Set chart options  
     var options = {  
       'title': 'Status',  
       'width': 300,  
       'height': 300  
     };  
     // Instantiate and draw our chart, passing in some options.  
     var chart = new google.visualization.PieChart(document.getElementById('chart_div'));  
     chart.draw(data, options);  
   }  
 </script>  
 <table style="width: 100%!important">  
   <tr>  
     <td style="vertical-align: top">  
       <div id="chart_div"></div>  
     </td>  
   </tr>  
 </table>  
 <br />  
 <label id="lblError" style="color: red; font-weight: bold; font-size: small"></label>  

Friday 6 November 2015

SharePoint 2013 Crud Operations using REST API

Perform Crud Operations in SharePoint 2013 using REST API.
REST API - I must say one should really use it when it comes on performance factor in SharePoint 2013. This technology is really light-weighed and off-course easy to use. Every technology has its own merits and demerits and hence it is our/developers choice based on requirement/condition what to use and when to use.
If someone asks when we should use REST API, I will say use REST to perform all most every read operations. We can do Insert, Update and Delete Operations but one I have encountered an issue which i will write it in another blog.

here are some examples on REST API Crud Operations.

Below operations are done by me approximate 15 months back and its a humble request to readers to update me if some new methods or best approaches are available other than this.

1)     Read/Get:-


var uspURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items";  
 $.ajax({  
   url: uspURL,  
   type: "GET",  
   contentType: "application/json;odata=verbose",  
   headers: {  
     "Accept": "application/json;odata=verbose"  
   },  
   success: function (data) {  
     var oresults = data.d.results;  
   },  
   error: function (jqxr, errorCode, errorThrown) {  
     alert(jqxr.responseText);  
   }  
 });  

Some of the useful tips for get are mentioned below.
Description
URL
To filter Title column
spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items?$filter=Title eq’XYZ’";
To get Item by ItemID. In this case I assume that ItemID is ‘1’
spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items(1)";
or
spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items?$filter=ID eq’1’";
To filter on multiple column
spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items?$filter=(([Title] eq 'ABC') and ([SubTitle] eq 'XYZ'))";
To read site columns. Here Site column name is SiteColumn1
spPageContextInfo.webAbsoluteUrl + "_api/web/fields?$filter=Title eq'SiteColumn1'";
To filter Date Column. Here date column is CreatedDate and operator used is greaterthan
spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items?$filter=CreatedDate ge datetime'2014-01-01T00:00:00Z'";


2)     Insert/Add List Items:-
This insert operation will also add special field value like DateTime Field, Choice Column and HyperLink Column.


  var itemType = "SP.Data.ListNameListItem";  
   var arrChoiceColumn = [];  
   arrChoiceColumn.push('Choice1');  
   arrChoiceColumn.push('Choice2');  
   var vardata = {  
     '__metadata': { 'type': itemType },  
     'Title': 'TestTitle', 'ChoiceColumName': {  
       "__metadata": { "type": "Collection(Edm.String)" },  
       "results": arrChoiceColumn  
     },  
     'DateColumnName': new Date().toISOString(),  
     'HyperLinkColumnName': {  
       '__metadata': { 'type': 'SP.FieldUrlValue' },  
       'Description': 'Azam Khan', 'Url': 'http://khanaazam.blogspot.ae/'  
     }  
   };  
   var uspURL = webURL + "/_api/web/lists/getbytitle('ListName')/items";  
   $.ajax({  
     url: uspURL, type: "POST",  
     contentType: "application/json;odata=verbose",  
     data: JSON.stringify(vardata),  
     headers: {  
       "Accept": "application/json;odata=verbose",  
       "X-RequestDigest": $("#__REQUESTDIGEST").val()  
     }, success: function (data) {  
       // here add alert message        
     },  
     error: function (jqxr, errorCode, errorThrown) {  
       alert(jqxr.responseText);  
     }  
   });  


3)     Update List Items:-
     While updating any records using REST in SharePoint 2013 it is same as Add Operation with some changes which are mentioned below:-
a)     Since we are updating list item it is basic that first we need to get that item so for that I will use get Item By Id method and hence the URL will be


var url = spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ListName')/items(1)";

b)     Second change will be in header of Ajax Call


headers:  
   {  
     "Accept": "application/json;odata=verbose",  
     "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
     "X-HTTP-Method": "MERGE","If-Match": "*"    
   }  

c)     In Data we will pass the Column Name along with their value the way how we have passed in the Add Operation.


3)     Delete List Items:-
     For Delete operation we can use the everything similar to Update Query with the only difference in headers


headers:  
   {  
     "Accept": "application/json; odata=verbose",  
     "content-type": "application/json; odata=verbose",  
     "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
     "IF-MATCH": "*","X-HTTP-Method": "DELETE"  
   }