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 "" 

SharePoint Framework SPFX On SharePoint Server 2016

To use SharePoint Framework SPFX on SharePoint Server 2016 we need to install SharePoint 2016 Feature Pack 2.

SharePoint 2016 Feature Pack 2 supports SharePoint Framework client-side web parts hosted in classic SharePoint pages.

SharePoint 2016 Feature Pack 2 supports SharePoint Framework client-side web parts hosted on classic SharePoint pages built by using the SharePoint Framework v1.1.0. This means that when you are targeting the SharePoint 2016 platform, you need to use the SharePoint Framework v1.1.0 due to the server-side version dependencies.

Install following prerequisite to develop SharePoint Framework SPFX.

  • Nodejs (Download Link: https://nodejs.org/en/) Make sure you install node version 6.11.2
  • Gulp Version 3.9.1
  • Yeoman Template Generator 2.0.2
  • NPM Version 3.10.10
  • SharePoint Framework Yeoman Generator Version 1.0.2
  • Visual Studio Code or any other editor (Visual Studio Code: https://code.visualstudio.com)

Please make sure that you install Microsoft Template Generator Version 1.0.2 any other version will not work for SharePoint 2016 On Premise.

My Environment:

Installation of Yeoman Template Generator

Installed Package Version

Package Installation Command


npm install -g yo gulp


	npm install npm@3.10.10


npm install -g @microsoft/generator-sharepoint@1.0.2

Create New SPFX Solution using command


yo @microsoft/sharepoint

Give Solution Name, Web Part Name and other required information as shown in Image

Once Solution is created it will appear as shown below

Now let’s make changes in created solution. You can open it using command


code .

Once you enter command it will open in Visual Studio Code Editor.

We are going to update HTML Code in file: HelloSpfxWebPart.ts

You can reach HelloSpfxWebPart.ts file from solution location SPFX\src\webparts\helloSpfx\HelloSpfxWebPart.ts

I have added my name”Nilesh Rathod” in html text/tag.

You can make changes as per your requirement.

Now next task is to test SPFX Solution/WebPart on SharePoint Server environment.

Before that we are going to run command “gulp trust-dev-cert” so that when we run our SPFX webpart on local machine it will not give Certificate Error


gulp trust-dev-cert

After that you can add command “gulp serve” to run this SPFX Solution/WebPart on local environment.

When you run gulp serve command it will open browser with URL: https://localhost:4321/temp/workbench.html which contains modern UI for SharePoint Web Part.

Here you can insert web part as shown in image

Once you add Web Part on Page, it will appear as per our updated changes.

Now we are able to Create and Run Web Part on SharePoint Server 2016 environment.

Next step is to deploy it on SharePoint Server Environment.

Deployment of SPFX WebPart on SharePoint Server 2016

Now when we are going to deploy WebPart on SharePoint Server we also needs to keep on mind that we need to add its related js file or configuration file which is required to run that SPFX application.

When we build our WebPart it will create its configuration file which are required on server to run it without any dependency.

While working with SharePoint Framework WebPart we can assign that location name from where it can read files when we are going to deploy it on any server.

That configuration is called CDN Path which is available in Configuration -> write-manifests.json file.

I have created Document Library named MySPFXFiles on my site location http://sps2012:4444/MySPFXFiles where I can add all required files which will be my CDN Address for SPFX Web Part.

You can set your own document library on your application and can use it as CDN Address.

We can set CDN Path as shown in image

After adding CDN Path let’s ship solution by running command



gulp bundle --ship


This builds the minified assets required to upload to the CDN provider. The –ship indicates the build tool to build for distribution. You should also notice that the output of the build tools indicate the Build Target is SHIP.

Next run command


gulp package-solution --ship

This creates the updated client-side solution package in the sharepoint\solution folder.

Once we run above command it will prepare 2 locations which we needs to consideration for actual deployment on server.

  • One location is “SPFX\sharepoint\solution” where our actual app package file “spfx-soln.sppkg” is generated.
  • Another location is “SPFX\temp\deploy” where all other mandatory file to run SPFX WebPart is generated.

Note that we can easily check or configure “temp\deploy” folder location in solution copy-assets.json file which is location at SPFX\config\copy-assets.json.

Now let’s copy all files on required file from temp\deploy folder to SharePoint Serve.

Open Solution in Folder. You can open it from command prompt also using command

explorer .

Navigate to Temp Deploy Folder Location: SPFX\temp\deploy

Here SharePoint 2016 will not allow to copy JSON file to SharePoint as it is blocked by environment. To enable it please check my post for Allow JSON to SharePoint 2016.

Copy all files and upload into SharePoint CDN Location which we already mentioned in above steps.

In my case it is : http://sps2012:4444/MySPFXFiles

I have copied all files on CDN address as shown in above Image.

Once all required file is copied next step is to deploy app on SharePoint App Catalog

If you are not aware How to Configure SharePoint App Catalog or How to setup App Domain on SharePoint Server you may refer to my post.

SharePoint Server 2016 Configure APP Domain

and

SharePoint Server App Catalog Configuration

Navigate to SPFX\sharepoint\solution location

Now Upload App File spfx-soln.sppkg on SharePoint App Catalog

When you upload package it will ask us to deploy application. You can click on Deploy button and trust application. You may also check your given CDN address is also available on application.

Once you click Deploy, SPFX Solution will deploy on SharePoint Server 2016 you can also check is Deployed Column value as shown in below Image

Once Application is deployed in App Catalog Site it will available in your desired site under Your Application -> Application From your Organization

Click on that app and it will install on server. You can see Installed application as shown in below image

Now you can add SPFX WebPart on any page.

I have created page named SPFXAPP.aspx Edit Page and Click on Insert Web Part Link . You may find SPFX WebPart in “Under Development” section.

Add HelloSPFX WebPart on Page and it will appear as shown in below Image.

Check In and Publish Page.

Hence we learn How to Create SPFX Solution on SharePoint Server 2016 Environment and Deployment Of SharePoint Framework WebPart or Solution on SharePoint Server 2016.

How to Allow JSON File Format on SharePoint 2016 on Premise

While working with SharePoint Framework Web Part I found that it requires JSON file to publish or add on CDN File address location on SharePoint Server.

SharePoint 2016 or any other on premises version by default block JSON file type. There are few other file types which are also blocked on SharePoint Server.

You may get its detail information on Microsoft Site.

https://support.office.com/en-us/article/Types-of-files-that-cannot-be-added-to-a-list-or-library-30BE234D-E551-4C2A-8DE8-F8546FFBF5B3#ID0EAABAAA=2016

To allow blocked file type on SharePoint Server follow below steps.

Navigate to: SharePoint Central Administration

Click on Manage Web Application

Select your desired site on which you want to allow JSON File.

From Ribbon Select or Click on Blocked File Types.

It will open Blocked File Types Modal Dialog Box.

Remove JSON extension from that list and press OK button.

After performing above steps, Now you can upload JSON file on SharePoint Server 2016.

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 2010 List View Search as you type in Textbox

Title: SharePoint Content Query Search
We can search from existing list using textbox search using jQuery and List view.
Follow below steps to search in list using Textbox.
1.Add Textbox using Content Editor Web Part on Page.
2.Create List View which you want to appear on Page.

Once above things available on Page use below JavaScript Code which is responsible to search from list view using textbox.


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

$(document).ready(function() {

    // SharePoint List View Table 
    var list = $("table.ms-listviewtable");
    // Table row of the items in list.
    var listItems = $("table.ms-listviewtable tr:not(.ms-viewheadertr)");
    // Our filter input.
    var input = $("input#filterInput");

    input.keyup(function() // On key presses
        {
            listItems.each(function() // for each items in list
                {
                    var text = $(this).text().toLowerCase(); 
                    console.log(text);
                    if (text.indexOf(input.val()) != -1) 
                    {
                        $(this).show(); 
                    } else {
                        $(this).hide(); 
                    }
                });
        });


});
</script>

After adding script, we are able to search from textbox’s key press event or as you type in textbox.

For this example, I have used Color List for demonstration and I am filtering list using color name.