Update Application Pool Password using PowerShell Script

By using below script we can update Passwod of Specific User for all his assigned Application Pool

PowerShell Script:


Import-Module WebAdministration
$applicationPools = Get-ChildItem IIS:\AppPools | where { $_.processModel.userName -eq "SPServer\administrator" }
 
foreach($pool in $applicationPools)
{
    $pool.processModel.userName = "SPServer\administrator"
    $pool.processModel.password = "sp#123@admin"
    $pool.processModel.identityType = 3
    $pool | Set-Item
}
 
Write-Host "Password Sucessfully Updated." -ForegroundColor Magenta 
Write-Host "" 

How to Setup App Domain on SharePoint Server 2016

To setup and configure APP Domain On SharePoint Server use below steps.

Open DNS Manager on Server

Find DNS and Open it

Select Forward Lookup Zone

Right Click on Forward Lookup Zone and Click on New Zone

It will start New Zone Wizard

Click on Next

Select Primary Zone

Click On Next

Select Second Option running all DNS server in this domain option

Click Next

Enter Zone Name

Click Next

Select Dynamic Update option Allow Only Secure Update

Click Next

Finish New Wizard.

Click on Finish

It will created newly assigned Forward Lookup Zone: sharepointapps.com

Right Click on sharepointapps.com and click on New Alias (CNAME)

Add New Resource Record

Here Add Alias Name “*” and set Fully Qualified Domain Name (FQDN) by browse file selection and select existing server (same as parent folder) option.

Click OK

Now Lookup Forward Zone is configured here.

Next Step is to Configure SharePoint Service: App Management Service Application

Navigate to SharePoint Central Administration

Click on Application Management -> Manage Service Applications

Create App Management Service

Click New and Select App Management Service

It will create App Management Service as shown in image

Once Application is created run below command to setup

Run the SharePoint 2016 Management Shell as an administrator

Start the SPAdminV4 and SPTimerV4 service applications


net start SPAdminV4
net start SPTimerV4

Also Set the domain used to host apps to the new zone created above


Set-SPAppDomain "sharepointapps.com"

Start the AppManagementServiceInstance and SPSubscriptionSettingsServiceInstance service instances:



Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"} | Start-SPServiceInstance





Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"}


Create the SharePoint Subscription Service:

Note that I have used my server “SPS2012” here for SPManagedAccount you can use your own server.


$account = Get-SPManagedAccount "SPS2012"
$appPoolSubSvc = New-SPServiceApplicationPool -Name SettingsServiceAppPool -Account $account
$appPoolAppSvc = New-SPServiceApplicationPool -Name AppServiceAppPool -Account $account
$appSubSvc = New-SPSubscriptionSettingsServiceApplication –ApplicationPool $appPoolSubSvc –Name SettingsServiceApp –DatabaseName SettingsServiceDB
$proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy –ServiceApplication $appSubSvc
$appAppSvc = New-SPAppManagementServiceApplication -ApplicationPool $appPoolAppSvc -Name AppServiceApp -DatabaseName AppServiceDB
$proxyAppSvc = New-SPAppManagementServiceApplicationProxy -ServiceApplication $appAppSvc


Set the name for the site subscription:



Set-SPAppSiteSubscriptionName -Name "app" -Confirm:$false


Here App Domain Service for SharePoint is configured successfully.

Now you can use App Service for your developer site or any other site collection.

SharePoint Custom Form Language Translation with Multilingual Site

You may use below steps to achieve language translation for custom form which is used in SharePoint multilingual site.

Create List named as: Translations


Above list contains information of translation for different language. I have used language pack Hindi for
Language Code: 1081 for SharePoint Site.

Columns detail for Translation list:
Title: Label code text. You can compare text by Title column to assign value +
TextToDisplay : English Language Text
TextToDisplay2: Hindi Or Other Language Text

Assign Language Translation Value to form control as shown in below code

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.min.css">
    <link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css">
    <script type="text/javascript" src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>
    <title>Responsive Test</title>
</head>

<body>
    <script type="text/javascript">
        $(document).ready(function () {
            LaunchResponsivePage();
            if (_spPageContextInfo.currentLanguage == 1033) {
                alert("User Selected Language :English == Language Code" + _spPageContextInfo.currentLanguage);
            } else {
                alert("User Selected Language : Hindi == Language Code" + _spPageContextInfo.currentLanguage);
            }
            /********************************GEt Value from Translation List and Set Value to Controls Code Start ****************************************/
            var listName = "Translations";
            var url = _spPageContextInfo.webAbsoluteUrl;
            var condition = "$select=Title,TextToDisplay,TextToDisplay2'";
            getListItems(listName, url, condition, function (data) {
                var items = data.d.results;
                for (var i = 0; i < items.length; i++) {
                        
                    	if (_spPageContextInfo.currentLanguage == 1033) 
						{						
							if (items[i].Title == "Name")	{ $('#lname').html(items[i].TextToDisplay);}
							if (items[i].Title == "City")	{ $('#lcity').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Choose a programming language")	{ $('#lchooseprogram').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Send me promotional emails from Microsoft")	{ $('#lpromotional').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Male")	{ $('#lmale').html(items[i].TextToDisplay);}			 
							if (items[i].Title == "Female")	{ $('#lfemale').html(items[i].TextToDisplay);}			 
						}
						else 
						{					
							if (items[i].Title == "Name")	{ $('#lname').html(items[i].TextToDisplay2);}
							if (items[i].Title == "City")	{ $('#lcity').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Choose a programming language")	{ $('#lchooseprogram').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Send me promotional emails from Microsoft")	{ $('#lpromotional').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Male")	{ $('#lmale').html(items[i].TextToDisplay2);}			 
							if (items[i].Title == "Female")	{ $('#lfemale').html(items[i].TextToDisplay2);}			 
						}			

                }
            }, function (data) {
                alert("Ooops, an error occured. Please try again");
            });
            /********************************GEt Value from Translation List and Set Value to Controls Code End ****************************************/
        });
    </script>
    <div id="ResponsiveTestDiv">
        <div class="ms-Grid">
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-fontSize-xl"> SharePoint Language Translation Form </div>
                </div>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-TextField">
                        <label id="lname" class="ms-Label is-required">Name</label>
                        <input id="txtName" class="ms-TextField-field is-required" type="text" value="" placeholder=""> </div>
                </div>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-TextField">
                        <label id="lcity" class="ms-Label">City</label>
                        <input id="txtCity" class="ms-TextField-field" type="text" value="" placeholder=""> </div>
                </div>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm12">
                    <div class="ms-Dropdown" tabindex="0">
                        <label class="ms-Label" id="lchooseprogram">Choose a programming language</label>
                        <i class="ms-Dropdown-caretDown ms-Icon ms-Icon--ChevronDown"></i>
                        <select id="dropdownProg" class="ms-Dropdown-select">
                            <option>Choose a programming language</option>
                            <option>Javascript</option>
                            <option>C#</option>
                            <option>F#</option>
                            <option>Python</option>
                            <option>Other</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="ms-ChoiceFieldGroup" id="choicefieldgroup" role="radiogroup">
                <div class="ms-ChoiceFieldGroup-title">
                    <label class="ms-Label is-required" id="lgender">Gender</label>
                </div>
                <ul class="ms-ChoiceFieldGroup-list">
                    <li class="ms-RadioButton">
                        <input tabindex="-1" type="radio" class="ms-RadioButton-input">
                        <label role="radio" class="ms-RadioButton-field" tabindex="0" aria-checked="false" name="choicefieldgroup">
                            <span class="ms-Label">Option 1</span>
                        </label>
                    </li>
                    <li class="ms-RadioButton">
                        <input tabindex="-1" type="radio" class="ms-RadioButton-input">
                        <label role="radio" class="ms-RadioButton-field" tabindex="0" aria-checked="false" name="choicefieldgroup">
                            <span class="ms-Label">Option 2</span>
                        </label>
                    </li>
                </ul>
            </div>
            <div class="ms-CheckBox">
                <input tabindex="-1" type="checkbox" class="ms-CheckBox-input">
                <label role="checkbox" class="ms-CheckBox-field" tabindex="0" name="checkboxa">
                    <span class="ms-Label" id="lpromotional">Send me promotional emails from Microsoft</span>
                </label>
            </div>
            <div class="ms-Grid-row">
                <div class="ms-Grid-col ms-u-sm6">
                    <button type="button" id="buttonSave" class="ms-Button ms-Button--primary">
                        <span class="ms-Button-label">Save</span>
                    </button>
                    <button id="buttonCancel" type="button" class="ms-Button">
                        <span class="ms-Button-label">Cancel</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    function LaunchResponsivePage() {
        MakeResponsive();
        InitializeComponents();
        AddEventHandlers();
    }
    // READ operation  
    // listName: The name of the list you want to get items from  
    // siteurl: The url of the site that the list is in.  
    // success: The function to execute if the call is sucesfull  
    // failure: The function to execute if the call fails  
    function getListItems(listName, siteurl, condition, success, failure) {
        $.ajax({
            url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?" + condition,
            method: "GET",
            async: false,
            headers: {
                "Accept": "application/json; odata=verbose"
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    }
    function MakeResponsive() {
        $("#s4-ribbonrow").hide(); //hide the ribbon row
        $("#s4-workspace").children().hide(); //hide all elements in workspace
        var div = $("#ResponsiveTestDiv"); //move the div to make it visible
        $("#s4-workspace").append(div); //add the div after s4-workspace
    }

    function InitializeComponents() {
        var TextFieldElements = document.querySelectorAll(".ms-TextField");
        for (var i = 0; i < TextFieldElements.length; i++) {
            new fabric['TextField'](TextFieldElements[i]);
        }
        var ChoiceFieldGroupElements = document.querySelectorAll(".ms-ChoiceFieldGroup");
        for (var i = 0; i < ChoiceFieldGroupElements.length; i++) {
            new fabric['ChoiceFieldGroup'](ChoiceFieldGroupElements[i]);
        }
        var CheckBoxElements = document.querySelectorAll(".ms-CheckBox");
        for (var i = 0; i < CheckBoxElements.length; i++) {
            new fabric['CheckBox'](CheckBoxElements[i]);
        }
        var DropdownHTMLElements = document.querySelectorAll('.ms-Dropdown');
        for (var i = 0; i < DropdownHTMLElements.length; ++i) {
            var Dropdown = new fabric['Dropdown'](DropdownHTMLElements[i]);
        }
    }

    function AddEventHandlers() {
        $("#buttonSave").click(function () {
            var output = "Hello " + $("#txtName").val();
            alert(output);
            return false;
        });
        $("#buttonCancel").click(function () {
            alert("Cancelled");
            return false
        });
    }
</script>

</html>

Once we implement above code to form it will appear as below for Hindi and English language site.

Form in Hindi Language Site

Form in English Language Site

SharePoint Client Side People Picker using jQuery and Save Operation

In this post we will learn how to use Client Side People Picker Control and how to save its value to SharePoint List.

I have created Basic form which accept 3 parameters i.e. Username, Joining Date and Manager.

Note that here Client Side People Picker allows selection of multiple people and format of jQuery Datepicker control is dd/mm/yyyy.

Form:

List :
I just kept list name “Controls” for demo.
Also here default Title column is going to hold Username’s information.

Use below code to perform Add Operation using Form on List “Controls”

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Bootstrap Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <!-- Bootstrap Calendar, jQuery and CSS Link Start -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">      
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>      
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
      <!-- Bootstrap Calendar, jQuery and CSS Link End -->
      
      <!-- SharePoint Specific Javascript Start -->
      <script src="/_layouts/15/sp.runtime.js"></script>  
      <script src="/_layouts/15/sp.js"></script>  
      <script src="/_layouts/15/1033/strings.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/sp.core.js"></script> 
      <!-- SharePoint Specific Javascript End -->

      <script>
         $(document).ready(function () {         
            /*** Initialize ClientSide People Picker ***/
            initializePeoplePicker('peoplepicker', true, 'People Only', 44);  
         
            /*** Initialize BootStrap Calendar ***/
             var date_input = $('input[name="date"]'); //our date input has the name "date"
             var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
             var options = {
                 format: 'dd/mm/yyyy',
                 container: container,
                 todayHighlight: true,
                 autoclose: true,
             };
             date_input.datepicker(options);


             $("#s4-ribbonrow").hide(); //hide the ribbon row
            $("#s4-workspace").children().hide(); //hide all elements in workspace
            var div = $("#ResponsiveDiv"); //move the div to make it visible
            $("#s4-workspace").append(div); //add the div after s4-workspace
         
            /*** Initialize ClientSide People Picker ***/
            function initializePeoplePicker(peoplePickerElementId, AllowMultipleValues, PeopleorGroup, GroupID) {  
            // Create a schema to store picker properties, and set the properties.  
                var schema = {};  
                schema['SearchPrincipalSource'] = 15;  
                schema['ResolvePrincipalSource'] = 15;  
                schema['MaximumEntitySuggestions'] = 50;  
                schema['Width'] = '280px';  
                schema['AllowMultipleValues'] = AllowMultipleValues;  
                if (PeopleorGroup == 'PeopleOnly') schema['PrincipalAccountType'] = 'User';  
                else schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
                if (GroupID > 0) {  
                    schema['SharePointGroupID'] = GroupID  
                }  
                // 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);  
            }  
         
         })
      </script>
   </head>
   <body>
      <div class="container" style="width:300px;margin-left:0px" id="ResponsiveDiv">
         <h2>Input Form</h2>
         <div class="form-group">
            <label for="usr">Name:</label>
            <input type="text"  class="form-control input-sm" placeholder="Enter Username" id="usr">
         </div>
         <div class="form-group">
            <!-- Date input -->
            <label class="control-label" for="date">Joining Date</label>
            <input class="form-control" id="date" name="date" placeholder="DD/MM/YYYY" type="text" />
         </div>
         <div class="form-group">
            <!-- Date input -->
            <label class="control-label" for="Manager">Manager</label>
            <div id='peoplepicker'  /></div>
         </div>
         <div class="form-group">
            <!-- Date input -->
            <label class="control-label" for="date"></label>
            <button type="button" class="btn btn-default" onclick="return Save()">Save</button>
         </div>         
      </div>
   </body>
</html>
<script>
   function Save() {
   
       alert("Save Event Starts");
       
       /*** SharePoint List Name  ***/
       var listName = "Controls";
   
       /*** SharePoint Simple Date Format from DD-MM-YYYY TO MM-DD-YYYY ***/
       var dtBirth =  DateFormat($("#date").val());
   
       alert("Updted Date Format " + dtBirth);
   
       var peoplePickerId = 'peoplepicker';
       var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerId + '_TopSpan'];
   
       //Get Selected UserInfo From PeoplePicker 
       var selectedUsers = peoplePicker.GetAllUserInfo();        
   
      /*************************************************************************************Get User Id **********************************************************/
      //After Selection of peoplePicker Use we will extract each user's email Id. By Using Email Id we will get each user's Userid i.e. Id
      //Once we receive id We are going to make an array of Id which will help us to pass user Id i.e. People Picker Column Value 

    
      var str ="";      
      var myObj;
      myObj = { "results":[ ]};

      for(var a=0;a<selectedUsers.length;a++)
      {
        /*Get UserEmail Id From  Selected Users in People Picket */
        var useremail  = selectedUsers[a].EntityData.Email;
    
        /*Get User Email Id in Comma Seperated String. This is for reference purpose only  */
        str += GetUserIDByEmail(useremail) + ",";
       
        /*Get User Id and ADD it into Arrasy so that we can pass this information in Perople Picker Value*/    
        myObj.results.push(GetUserIDByEmail(useremail));
      }
       
       /* Remove Last , (comma) sign from selected userid */
       var selectedPeoplePickerID = str.substring(0, str.length-1);

       alert("USERID "+ selectedPeoplePickerID);       

       /*************************************************************************************Get User Id **********************************************************/
   
       /* Pass Selected  User Id in JSON MagaerId Parameter*/
       var itemProperties = {
           'Title': $("#usr").val(),
           'JoiningDate':dtBirth,
           'ManagerId':myObj
       };
   
       /******************************  Create List Item With Given Paramters Start ****************************************************************************************/
       CreateListItemWithDetails(listName, _spPageContextInfo.webAbsoluteUrl, itemProperties, function () {
           alert("New Item has been created successfully.");
       }, function () {
           alert("Ooops, an error occured. Please try again.");
       });
       /******************************  Create List Item With Given Paramters End****************************************************************************************/

        /******************************  Create List Item Function Start  ****************************************************************************************/
   
       function CreateListItemWithDetails(listName, webUrl, itemProperties, success, failure) {
           var itemType = GetItemTypeForListName(listName);
           itemProperties["__metadata"] = {
               "type": itemType
           };
           $.ajax({
               url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName +
                   "')/items",
               type: "POST",
               contentType: "application/json;odata=verbose",
               data: JSON.stringify(itemProperties),
               headers: {
                   "Accept": "application/json;odata=verbose",
                   "X-RequestDigest": $("#__REQUESTDIGEST").val()
               },
               success: function (data) {
                   success(data);
               },
               error: function (data) {
                   failure(data);
               }
           });
       }
       // Get List Item Type metadata
       function GetItemTypeForListName(name) {
           return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
       }

       /******************************  Create List Item Function End  ****************************************************************************************/
   
       /******************************  Simple Date Format Function to convert from DD-MM-YYYY TO MM-DD-YYYY Start *************************************************/
       function DateFormat(date) {
           var tmp = date.split('/');
           var date = tmp[1] + '/' + tmp[0] + '/' + tmp[2];
           return date;
       }    
       /******************************  Simple Date Format Function to convert from DD-MM-YYYY TO MM-DD-YYYY End *************************************************/
   
       /****************************** Get UserID  using Email Code Start ************************************** *************************************************/
        function GetUserIDByEmail(useremail) {
          var res ;
          $.ajax({
              url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/SiteUsers?$filter=Email%20eq%20%27" + useremail +"%27" ,   
              async: false,
              type: "GET",        
              headers: { "Accept": "application/json; odata=verbose" },
              success: function (data) {            
                        $("#sample").empty();  
                  for (var i = 0; i < data.d.results.length; i++)   
                  {  
                      var item = data.d.results[i];  
                      $("#sample").append(item.Id + "\t" + item.Title + "<br/>");  				
                      res=item.Id;			
                  }  			
                    return res;			
              },
              error: function (data) {
                  failure(data);
              }
              });
      
          return res;
        }
        /****************************** Get UserID  using Email Code End ************************************** *************************************************/
   
   
   }
</script>

After Implementation of Code we are able to perform Add Item Operation with Single and multiple Person using People Picker Control.

With Multiple Person/Manager:

List Item Value After Save Operation

How to format SharePoint Date to DD-MM-YYYY Format using Moment.js

It’s easy to format SharePoint Date in JavaScript Date Format e.g. mm/dd/yyyy OR dd/mm/yyyy

Use below code to format Date

Add Moment.js Reference

  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

Apply Date Format as per shown code


    //Get SharePoint Date Column Value 
    var itemBirthDate = items[i].BirthDate;   
    //Convert SharePoint Date to Javascript Date 
    var dateObj = new Date(itemBirthDate);
    //Convet JavaScript Date Object to Moment JS
    var momentObj = moment(dateObj);
    //Apply Moment.Js Formatter to your desire date format
    var formattedDate = momentObj.format('DD-MM-YYYY');   
    $("#divContent").append("Username : " + itemTitle + "  BirthDate :  " + formattedDate +" <br/>  ");      

Sample Code to retrieve item and Date Format

function GetData() {

	var listName = "Controls";
	var siteurl = _spPageContextInfo.webAbsoluteUrl;
	var condition = "$select=Title,BirthDate";

	getListItems(listName, siteurl, condition, function (data) {

		var items = data.d.results;

		for (var i = 0; i < items.length; i++) {
			var itemTitle = items[i].Title;
			//Get SharePoint Date Column Value 
			var itemBirthDate = items[i].BirthDate;
			//Convert SharePoint Date to Javascript Date 
			var dateObj = new Date(itemBirthDate);
			//Convet JavaScript Date Object to Moment JS
			var momentObj = moment(dateObj);
			//Apply Moment.Js Formatter to your desire date format
			var formattedDate = momentObj.format('DD-MM-YYYY');
			$("#divContent").append("Username : " + itemTitle + "  BirthDate :  " + formattedDate + " <br/>  ");
		}
	}, function (data) {
		alert("Ooops, an error occured. Please try again");
	});
}

function getListItems(listName, siteurl, condition, success, failure) {
	$.ajax({
		url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?" + condition,
		method: "GET",
		async: false,
		headers: {
			"Accept": "application/json; odata=verbose"
		},
		success: function (data) {
			success(data);
		},
		error: function (data) {
			failure(data);
		}
	});
}

SharePoint Get GUID Of List and Columns

While developing SharePoint solution code we require GUID of List and Columns Id.We can easily get this using below format

Custom List:

Note that this list has 2 columns
1.Title
2.Target
To view GUID for this list Navigate to list settings.

Once we Navigate to List settings we are able to see below URL. Copy Full URL from browser

https://onsps.sharepoint.com/_layouts/15/listedit.aspx?List=%7B2CB2E87A-04CD-445A-9201-4F41FD8EF9A1%7D 

Replace the following characters as follows:
%7B to {
%2D to –
%7D to }

Once you replace above encoded character then list GUID will available which is {2CB2E87A-04CD-445A-9201-4F41FD8EF9A1}

To View all Columns and files inside this list change or append URL as below

https://onsps.sharepoint.com/_vti_bin/owssvr.dll?Cmd=ExportList&List=2CB2E87A-04CD-445A-9201-4F41FD8EF9A1

When we type above url it will open or download xml file which file has all information regarding list and its columns with GUID.

Here SourceID indicates GUID for List and ID indicates Column ID.

SharePoint: CRUD Operation using SPServices

Fill Drop Down List:

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

/* ----------- Bind Dorp Down List - Country Begin -------------*/
var SPSiteURL = "https://yourSharepointsiteURL/Site";
 
        $().SPServices({
            webURL: SPSiteURL,
            operation: "GetListItems",
            async: false,
            listName: "Country",
            CAMLQuery: "<Query><OrderBy><FieldRef Name='Title'/></OrderBy><Where><Eq><FieldRef Name='Active'/><Value Type='Boolean'>1</Value></Eq></Where></Query>",
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>",
            completefunc: function(xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function() {
                    var DataTextField = $(this).attr("ows_Title");
                    var DataValueField = $(this).attr("ows_ID");
                    listItem = "<option value=" + DataValueField + ">" + DataTextField + "</option>"
                    $("#ddlCountry").append(listItem);
                });
            }
        });
/* ----------- Bind Dorp Down List - Country End -------------*/
</script>

Above Code will get items from Country DropDownList where Active = True

Save:
Bind Save Button Event & Code to Save Data.

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

//Submit Button Click Event
    $("#btnSubmit").click(function() {
        return SaveEmployeeInfo();
    });

/* ----------- Save Employee Info Form Code Begin -------------*/
function SaveEmployeeInfo()

{
    console.log("Save Process Begin");
    //alert("Save Event");

    var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    console.log("City = " + City);   

    console.log("Save Process Begin");

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get Item CreationInfo 
    var itemCreateInfo = new SP.ListItemCreationInformation();

    //Add Item Object
    this.oListItem = oList.addItem(itemCreateInfo);

    //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);
	

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onSaveQuerySucceeded), Function.createDelegate(this, this.onSaveQueryFailed));

    return false;
}

function onSaveQuerySucceeded() {

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

function onSaveQueryFailed(sender, args) {

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

</script>

Update: Bind Update Button Event & Code to Update Data

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


/* ----------- Update Employee Info By EmpID Code Start-------------*/
function UpdateEmployeeInfo() {
    
	//alert("Update Operation Begin");
	
    var EmpID = getParameterByName('EmpID');
	
	var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
	console.log("City = " + City);  
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get List Item By ID 	
    this.oListItem = oList.getItemById(EmpID);

   //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryAuditUpdateSucceeded), Function.createDelegate(this, this.onQueryAuditUpdatedFailed));

    return false;


}

function onQueryAuditUpdateSucceeded() {

    console.log('Item Updated Successfully');
}

function onQueryAuditUpdatedFailed(sender, args) {

    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
/* ----------- Update Employee Info By EmpID Code End-------------*/

</script>


Retrieve Employee Data : Code to Retrieve Data

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

/* ----------- Retrieve Employee Data Code Starts -------------*/
function GetemployeeData(EmpID) {
    $().SPServices({
        webURL: SPARPSiteURL,
        operation: "GetListItems",
        async: false,
        listName: "EmployeeInfo",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>" + EmpID + "</Value></Eq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='EmployeeName' /><FieldRef Name='City' /><FieldRef Name='Agreement' /><FieldRef Name='Hobbies' /><FieldRef Name='BirthDate' /></ViewFields>",

        completefunc: function(xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function() {

                console.log("ows_Title " + $(this).attr("ows_Title"));
                console.log("ID " + $(this).attr("ows_ID"));
                console.log("EmployeeName " + $(this).attr("ows_EmployeeName"));
                console.log("City " + $(this).attr("ows_City"));
                console.log("Agreement " + $(this).attr("ows_Agreement"));
                console.log("Hobbies " + $(this).attr("ows_Hobbies"));
                console.log("BirthDate " + $(this).attr("ows_BirthDate"));
              
                var City = $(this).attr("ows_City");
                $("#ddlCity").find("option:contains('" + City + "')").each(function() {
                    if ($(this).text() == City) {
                        $(this).attr("selected", "selected");
                    }
                });


                $("#txtEmployeeName").val($(this).attr("ows_EmployeeName"));

                var date = new Date($(this).attr("ows_BirthDate"));
                if (!date) {
                    var currentMonth = date.getMonth() + 1;
                    if (currentMonth < 10) {
                        currentMonth = '0' + currentMonth;
                    }
                    var currentDate = date.getDate();
                    if (currentDate < 10) {
                        currentDate = '0' + currentDate;
                    }
                    var PrePlanStartDate = (currentDate) + '/' + currentDate + '/' + date.getFullYear();
                    $("#txtBirthDatee").val(PrePlanStartDate);
                }

                if ($(this).attr("ows_Agreement") == 1) {
                    $('#chkAgreement').attr('checked', 'checked');
                };

                //---------Hobbies Check Box List
                console.log("Hobbies Value " + $(this).attr("ows_Hobbies"));
                var Hobbies = $(this).attr("ows_Hobbies");

                var arrayTeam = Hobbies.split(',');
                //console.log("Array Value" + arrayTeam);

                for (var i = 0; i < arrayTeam.length; i++) {
                    var chkValue = arrayTeam[i];
                    $("#chkHobbies input:checkbox").each(
                        function() {
                            if ($(this).attr("id") == chkValue) {
                                $(this).prop("checked", true);
                            }
                        }
                    );
                }

            });
        }
    });
}
/* ----------- Retrieve Employee Data Code Ends -------------*/
</script>

SharePoint SPServices Check User Group

To check Logged in user group using SPServices use below code.

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

$(document).ready(function() {
    CheckUserGroup();
});

/* ----------- Check User Group Code Begin -------------*/
function CheckUserGroup(itemid) {
        $().SPServices({

            operation: "GetGroupCollectionFromUser",

            userLoginName: $().SPServices.SPGetCurrentUser(),

            async: false,

            completefunc: function(xData, Status) {

                if ($(xData.responseXML).find("Group[Name = 'Administrator']").length == 1) {

                    alert("Logged In User Group :: Administrator ");

                    /* ----------- Enable Disable Control Start -------------*/

                    //$("#divEmployee :input").prop("disabled", true);

                    //$("#btnSubmit").removeAttr('disabled');

                    /* ----------- Enable Disable Control End -------------*/

                } else {

                    alert("Logged In User is OutSide Of Adnministrator Group");
                }

            }

        });
    }
/* ----------- Check User Group Code End -------------*/
</script>

SharePoint Date Conversion to Javascript MM/DD/YYYY Format

To covert SharePoint Date to JavaScript Date Format MM/DD/YYYY use below code.


<script language="javascript" type="text/javascript">
/* ----------- SharePoint Date To JavaScript Date Format Code Start -------------*/
function convertSPDate(d) {
/*
* A function to convert a standard SharePoint
* date/time field (YYYY-MM-DD HH:MM:SS) to a
* javascript Date() object
*
* Author: Ben Tedder (www.bentedder.com)convertSPDate
*/
// split apart the date and time
var xDate = d.split(" ")[0];
var xTime = d.split(" ")[1];

// split apart the hour, minute, & second
var xTimeParts = xTime.split(":");
var xHour = xTimeParts[0];
var xMin = xTimeParts[1];
var xSec = xTimeParts[2];

// split apart the year, month, & day
var xDateParts = xDate.split("-");
var xYear = xDateParts[0];
var xMonth = xDateParts[1]-1;
var xDay = xDateParts[2];

var dDate = new Date(xYear, xMonth, xDay, xHour, xMin, xSec);
return dDate;
}
/* ----------- SharePoint Date To JavaScript Date Format Code End -------------*/

</script>

We also require moment.js to format it in MM/DD/YYYY Format


var DOB = new convertSPDate($(this).attr("ows_DOB"));
$("#txtDOB").val(moment(DOB).format('L'));

Moment JS Reference URL:
http://momentjs.com/
http://momentjs.com/downloads/moment.min.js

Active Directory Setup For SharePoint Development Environment

To configure Active Directory Domain Service on Windows Server follow below steps:

Navigate to Server Manager

Click On Add roles and features.

It will start Add Roles and Features Wizard.

Click on Next

Select Installation Type as shown in Image

Click on Next

Select Option as shown in Image

Click on Next

Select Active Directory Domain Service

When you click on it, it will prompt you to add features for Active Directory Domain Service

Click on Add Features

Now Active Directory Domain Service is checked or selected.

Click on Next

On Features Tab Click on Next

On AD DS tab click on Next

On Confirm Installation selection section click on Install.

Next step will show us Installation Progress

Once the installation succeeds click on Close

After Successful installation, you can see in Dashboard Notification Message to promote this server for a domain controller.

Click on it.

It will Start “Active Directory Domain Service Configuration Wizard”

Click on Add New Forest. Enter Root Domain name

Clock on Next

Enter Password and Confirm Password

Click on Next

It will show DNS Options

Click on Next

Additional Options will check Domain Name

Click on Next

Select Path

Click on Next

Review Option.Review Entered information

Click on Next

Check Prerequisites.Click On Install.It will start installation process.

Once installation is complete restart server.