SharePoint List Rest Api to get data of Person or Group Field

In below url EvaluatEmail is person/group fiels in the list called testABC

var userId = -1;		
var requestUrl = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl+"/_api/web/lists/getbytitle('testABC')/items("+id+")?$select=EvaluatEmail/Name,EvaluatEmail/EMail&$expand=EvaluatEmail";
		var userEmail='';
		$.ajax({
			url: requestUrl,
			method: "GET",
			async: false,
			headers: { "Accept": "application/json; odata=verbose" },
		success: function (data) {					
			if(data.d.EvaluatEmail.results!=null){
				var len=data.d.EvaluatEmail.results.length;
				for(var i=0;i<len;i++){
				var item= data.d.EvaluatEmail.results[i]
				if(userEmail!=''){
					userEmail+= ','+item.EMail;
				}else{
					userEmail += item.EMail;
				 }
			}
		   }											
		},
		error: function (error) {
				console.log(error);					
				}
			});

Thus, you can retrieve the details of the user. However, not all properties are retuned (this is on SharePoint online ) as stated here. It says “The Query to the field <fieldname> is not successful” for few fields.

I was successful with the following.

  • Title
  • Name
  • EMail
  • MobilePhone
  • SipAddress
  • Department
  • JobTitle
  • FirstName
  • LastName
  • WorkPhone
  • UserName
  • Office
  • ID
  • Modified
  • Created

Mainly, one of my key details, “Picture URL” is missing. This really gave me a hiccup since it is the only one missing for my requirement and I didn’t want to make another user profile REST call to retrieve the URL. Anyhow, I figured out the option.

Get Data from SharePoint List using Rest Api with Filter

Code to Use rest api with simple filter

var paramID=$(this).attr("data-parameter-id");
 var obj = $(this).attr('id');
 var requestUrl = url+"/_api/web/lists/GetByTitle('test')/items?$filter=ParameterID eq "+paramID;
 var userEmail='';
 $.ajax({
         url: requestUrl,
         method: "GET",
         async: false,
         headers: { "Accept": "application/json; odata=verbose" },
         success: function (data) {                                          
                 var dt =data;                                           
         },
         error: function (error) {
                     console.log(error);                                         
                 }
     });

Code to use rest api with multiple Filter

var paramID=$(this).attr("data-parameter-id");
 var obj = $(this).attr('id');
 var requestUrl = url+"/_api/web/lists/GetByTitle('test')/items?$filter=ID eq 1 or ID eq 2";
 var userEmail='';
 $.ajax({
         url: requestUrl,
         method: "GET",
         async: false,
         headers: { "Accept": "application/json; odata=verbose" },
         success: function (data) {                                          
                 var dt =data;                                           
         },
         error: function (error) {
                     console.log(error);                                         
                 }
     });

Code to use rest api for lookup columns

url+”/_api/web/lists/GetByTitle(List Name)/items?$filter=Lookup List/LookupColumn eq Value

In below url Category is lookup list and ID is the Lookup List Column name

var requestUrl = url+"/_api/web/lists/GetByTitle('test')/items?$filter=Category/ID eq 1";
  var userEmail='';
  $.ajax({
          url: requestUrl,
          method: "GET",
          async: false,
          headers: { "Accept": "application/json; odata=verbose" },
          success: function (data) {                                          
                  var dt =data;                                           
          },
          error: function (error) {
                      console.log(error);                                         
                  }
      });

Get Item from list using ID you can use below rest api

var requestUrl = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl+"/_api/web/lists/getbytitle('testABC')/items("+id+")

How To Identify And Attach Correct W3WP Process In Visual Studio While Debugging

In most of the time, being a developer, we will be attaching to the W3WP Process. But when we try to attach the process using the Visual Studio, we will be seeing many w3wp processes running. We will be in a dilemma to which we need to attach and at-last, as usual, we will be attaching to all the w3wp processes.

This happens because, the Attach to Process popup doesn’t show the Application Pool details.

To identify the Process for our Application Pool, Open the command prompt as administrator.

Navigate to the folder C:\Windows\System32\inetsrv\. Enter the command “appcmd.exe list wp”. This will list all the worker process associated with the Application Pools.

clip_image004

We know our Application Pool name. Note down the ID corresponding to the Application Pool.

Now coming back to visual studio and click “Attach to Process”. Attach the process with a specific ID which we noted. That’s it. Now we are done with “Attach to Process”. Happy debugging.

Download Deployed Solutions (WSP) from Central Admin with PowerShell in SharePoint 2013

Using power shell run this below script.

  1. $FolderPath = “c:\Solutions”  
  2. foreach ($solution in Get-SPSolution)  
  3. {  
  4.    $id = $Solution.SolutionID  
  5.    $title = $Solution.Name  
  6.    $filename = $Solution.SolutionFile.Name  
  7.    $solution.SolutionFile.SaveAs(“$FolderPath\$filename”)  
  8. }  

Display SharePoint List Attachment using AngularJS javascript

Below Script will help to read attachment from SharePoint and will display in html.

Below is the JavaScript code to read attachments

function (ItemId){
var param=$scope.refenerencedocId;

$http( 
{ method: "GET", 
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('drafts')/items("+ItemId+")?$select=Title,ID,Attachments,AttachmentFiles&$expand=AttachmentFiles", 								
headers: { "accept": "application/json;odata=verbose" } 
} 
).success(function (data, status, headers, config) { 
$scope.details1 = data.d;
}).error(function (data, status, headers, config) { 
}); 
}

Below is the html to display file name as a link

<tr>
	<td>Reference Document</td>
	<td>
          <h4 ng-repeat="x in details1.AttachmentFiles.results ">
	<a href={{x.ServerRelativeUrl}} title={{x.FileName}}>{{x.FileName}}</a>
	  </h4>
	</td>
</tr>

ParseXML using JavaScript

This solution will help you to parse XML using JAVAScript and display in Table.

Below is the XML File Sample :

<draftComments>
	<Articles>
		<articlenbr>2</articlenbr>
		<articleComments>dsgdsgds</articleComments>
	</Articles>
	<Articles>
		<articlenbr>3</articlenbr>
		<articleComments>sdgsdg</articleComments>
	</Articles>
	<documentid>1</documentid>
	<username>sdgsdg</username>
	<useremail>sgdsgsd@fsd.ffjf</useremail>
	<userphone>7643743</userphone>
	<genlcomments>hdhhdh</genlcomments>
	<usercompany>dhdh</usercompany>
	<userposition>hdhdh</userposition>
</draftComments>

Java Script to Convert XML in to HTML

function JQuery1(xml){
	var xmlDoc;
            if (window.DOMParser) {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(xml, "text/xml");
            }
            else //For IE
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(xml);
            }
 
            var customers = xmlDoc.getElementsByTagName("Articles");
 
            for (var i = 0; i < customers.length; i++) {
                //Get the reference of the Table's TBODY element.
                var tBody = document.getElementById("tblCustomers").getElementsByTagName("TBODY")[0];
 
                //Add Row.
                row = tBody.insertRow(-1);
 
                //Add CustomerId cell.
                cell = row.insertCell(-1);
 
                //Access the Node by its Index.
                cell.innerHTML = customers[i].childNodes[0].textContent;
 
                //Add Name cell.
                var cell = row.insertCell(-1);
 
                //Acess the Node by its Tag Name.
                cell.innerHTML = customers[i].getElementsByTagName("articleComments")[0].textContent;
 
                
            }
			document.getElementById("submittorName").innerHTML=xmlDoc.getElementsByTagName("username")[0].textContent;
			document.getElementById("submittorEmail").innerHTML=xmlDoc.getElementsByTagName("useremail")[0].textContent;
			document.getElementById("submittorPhone").innerHTML=xmlDoc.getElementsByTagName("userphone")[0].textContent;
			document.getElementById("submittorComments").innerHTML=xmlDoc.getElementsByTagName("genlcomments")[0].textContent;
			document.getElementById("submittorCompany").innerHTML=xmlDoc.getElementsByTagName("usercompany")[0].textContent;
			document.getElementById("submittorPosition").innerHTML=xmlDoc.getElementsByTagName("userposition")[0].textContent;
			
}

Output will be as below

Get Data from two sharepoint Lists using angular JS

Solution to get data from one SharePoint list and use it to get data from another list. Below is the solution for that.

  1. To get Data from First List using ID from URL
<script>	
	var urlParams = getUrlParameter('ID');
	var DocID;
	var spApp = angular.module("spApp", []);

//Function to get Query String from Parameter 
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

spApp.controller("viewItemsController", function ($scope, $http) { 
						 
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('draftcomments')/items(" + urlParams + ")";
$http({ method: "GET", 
url: url, 
headers: { "accept": "application/json;odata=verbose" } 
} 
).success(function (data, status, headers, config) { 
$scope.details = data.d;
test=data.d.requestXML;								DocID=data.d.refenerencedocId;								
								//Function to decode XML
								JQuery1(test);
								
								//Function To get data from another list by passing ID getting from first List
								$scope.GetDocument(data.d.refenerencedocId);
}).error(function (data, status, headers, config) { 
}); 
$scope.GetDocument=function (docId){
var param=$scope.refenerencedocId;
var url1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Legaldrafts')/items(1)?$select=Title,ID,Attachments,AttachmentFiles&$expand=AttachmentFiles";
$http( 
{ method: "GET", 
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Legaldrafts')/items("+docId+")?$select=Title,ID,Attachments,AttachmentFiles&$expand=AttachmentFiles", 							
headers: { "accept": "application/json;odata=verbose" } 
}).success(function (data, status, headers, config) { 
$scope.details1 = data.d;
}).error(function (data, status, headers, config) { 
}); 
}
});

CRUD operations using Rest & Angular on SharePoint List

Here We will see how to do crud operations on sharepoint list using Rest API and Angular JS

This Solution will have below features:

  • Create, Read, Update & Delete operations using Angular & REST
  • One page solution for all operation
  • Responsive design using bootstrap
  • Confirmation message before deleting an item
  • Save button disabled if required fields are empty
  • Sorting on each column
  • Single Search box to instantaneously search on multiple columns. (Title & Location)
  • The list that holds the items:

    I find adding ng-app in masterpage is easier to work with and don’t have create it again & again. There might be better way of doing, I’m new to Angular so let me if you have any suggestions.

    Add reference to Angular.min in masterpage (make sure to add reference at top of masterpage instead at the end.), and add ng-app to div with id contentBox, this way everything will be under one ng-app.

    <div id="contentBox" ng-app="CourseListApp">
    Create a List and add your columns as required. Here I’m adding Location column to demonstrate. If you add your columns make sure to update the js accordingly. Here is the js for the solution Continue reading

    Use A Confirm Dialog while Opening External Links

    Redirect Confirm is a jQuery plugin that displays a confirmation dialog to notify users when they are opening an external links of your website. The plugin uses Bootstrap’s modal component for the animated confirm dialog box.

    How to use it:
    1. Load jQuery library and Bootstrap’s CSS and JavaScript files in the html page.


    Insert bootstrap.min.css in head and below Java Script

    //code.jquery.com/jquery-1.11.3.min.js
    /path/to/bootstrap.min.js

    2. Make sure you load the jQuery Redirect Confirm after jQuery library.

    http://redirect.confirm.js

    3. Call the plugin with default option. By default, All the links of your webpage will be affected by the plugin.

    jQuery(document.body).RedirectConfirm();


    4. Apply the plugin to links within a specified container.

    jQuery(document.body).RedirectConfirm({
    selector: "a",
    });

    5. You can also specify the ‘Exculding’ links using ‘data-rc-exclude’ attribute.

    jQuery(document.body).RedirectConfirm({
    selector: "a",
    excluding: 'data-rc-exclude'
    });

    6. Override the ‘target’ attribute. By default, the links will be opened in a new tab.

    jQuery(document.body).RedirectConfirm({
    selector: "a",
    excluding: 'data-rc-exclude',
    targetUrl: '_blank'
    });

    7. Customize the confirm dialog.

    view source

    jQuery(document.body).RedirectConfirm({
    selector: "a",
    excluding: 'data-rc-exclude',
    targetUrl: '_blank',
    title: 'Exiting our website',
    message: 'You are now leaving our website. We are not responsible for any external Web sites.',
    returnlbl: 'Return',
    continuelbl: 'Continue',
    });

    Convert HTML to Word Document using JavaScript

    HTML Code to Convert in Word Document

    HTML to Word Document

    HTML to Word Doc Conversion using JS

    Testing for converting HTML to Word document HTML to Word Conversion, TEst or Save as word document are
    This Java script is userful to convert html in to word document using java script without using plugin

    JAVA Script for HTML to Word Document conversion

    function exportHTML(){
    var header = “”+
    “Export HTML to Word Document with JavaScript”;
    var footer = “”;

    var sourceHTML = header+document.getElementsByClassName(“news_content”)[0].innerHTML+footer;

    var source = ‘data:application/vnd.ms-word;charset=utf-8,’ + encodeURIComponent(sourceHTML);
    var fileDownload = document.createElement(“a”);
    document.body.appendChild(fileDownload);
    fileDownload.href = source;
    fileDownload.download = ‘document.doc’;
    fileDownload.click();
    document.body.removeChild(fileDownload);
    }