How to Create File On Same Folder For Azure Web Application

Many times we need to create file of folder in web application to store log or other file related information.

The application which is hosted on Azure like Web Jobs or Application has to use different syntax to create file or folder in same or another directory.

Use below code to upload file or folder on Azure Web Application

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("File Write Operation Start");

            /*Folder Name Which needs to be Crated on Azure */
            string FolderName = "MyapplicationLogs";

            /*File Name : Here For Demo Purpose to create multiple file I have added FileName in For Loop */
            string FileName;

            //File Content Which needs to be Added in text File
            string strLogText = "Log Information Found on " + DateTime.Now;

            //AZURE Application Root Folder Location + Folder Name Combination 
            //Here  Environment.GetEnvironmentVariable("HOME") gives is Azure Web Application Local Path
            //For e.g. Actial Path for File Creation on Azure will be : D:\home\site\wwwroot\DemoLogs\1Log.txt
            //where D:\home\site\wwwroot is Path for Azure Web Application
            string strFolderName = Environment.GetEnvironmentVariable("HOME") + @"\site\wwwroot\" + FolderName;

            //If the directory doesn't exist, create it.
            if (!Directory.Exists(strFolderName))
            {
                Directory.CreateDirectory(strFolderName);
            }

            for (int i=0;i<10;i++)
            {
                FileName = i + "Log.txt";

                string strLogFilePath = strFolderName.Trim() + @"\"+ FileName;

                //Once Directory Exists Create or Writre File 
                using (StreamWriter writer = new StreamWriter(strLogFilePath, true))
                {
                    writer.WriteLine(strLogText);
                }

                Console.WriteLine("File Created On Location " + strLogFilePath);
            }
            
            Console.WriteLine("File Write Operation End");
        }
    }
}

Advertisement

Azure WebJob To Create Azure File Share and File

Scenario: Client needs to upload files on daily basis as timer job to particular location (here Azure File Share). File contains auto generated name and individual content for each file. Below code includes example to create and upload file on Azure File Share and also Creation and configuration of Azure WebJob  to achieve requirement.

Steps :

  1. Create Console Application
  2. Configure Azure File Share Location
  3. Create or Configure Azure WebJob
  4. Deployment Of Console Application as Web Job
  5. Run Web Job and outcome of the application

Create New Project using Visual Studio

Select Console Application

Give your desired project name and location

It will create Console Application

Next Step is to add Azure Cloud Reference Files which is required to call Azure Objects in Code

Right Click on Project and Select Manage NuGet Packages

Installed Packages as shown in below image

Once above packages installed in application, you can see References in Solution Explorer as below

Add below code which Creates Azure File Object and Upload File on mentioned location

using Microsoft.WindowsAzure.Storage;
using System;
using System.Configuration;
using System.IO;
using System.Text;

namespace AzureFilesApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string strConnectionSting = ConfigurationManager.ConnectionStrings["AzureStorageAccount"].ConnectionString;

            Console.WriteLine(@"Connecting to Azure Storage Account");

            CloudStorageAccount sa = CloudStorageAccount.Parse(strConnectionSting);

            Console.WriteLine(@"Connected To Azure Storage Account");

            Console.WriteLine(@"Cheking Cloud Storage File Location");
            
            //Create Azure File Share   
            //this wull create File Service 'myfilesonazure' on Azure
            var share = sa.CreateCloudFileClient().GetShareReference("myfilesonazure");
            share.CreateIfNotExists();

            Console.WriteLine(@"Cloud Location Found On Azure");
            Console.WriteLine(@"Preparing Content For File");

            //Create Dyamicn File Name and File Content. 
            //Dynamic Content form Database or other Service will be availalbe here 
            string TempFileName = DateTime.Now.Second.ToString() + ".html";
            string content = @"<!DOCTYPE html><html><body><h2>HTML Forms</h2><form action='/action_page.php'>  First name:<br>  <input type='text' name='firstname' value='Nilesh'>  <br>  Last name:<br><input type='text' name='lastname' value='Rathod'><br><br>  <input type='submit' value='Submit'></form></body></html>";

            Console.WriteLine(@"File Content Completed");

            Console.WriteLine(@"Adding File On Cloud Location");

            //Create File in Root Folder and Upload its Content
            var rootDir = share.GetRootDirectoryReference();            
            var fileToCreate = rootDir.GetFileReference(TempFileName);
            fileToCreate.UploadText(content);

            Console.WriteLine(@"File Successfully Uploaded On Cloud Location");

        }

    }
}


Here console application is ready .Note that ‘AzureStorageAccount’ variable is connection string which is used in App.Config file which is connection string to your Azure Application

Code For App.Config File is as below

You can get your connection string from Azure Application

Navigate to Your Application and Select Access Key. It will display Connection String in another panel.

Once Console Application is ready you can run it and check its functionality to make sure that it is working with Azure File Share and provided Azure configuration.

If it works fine then next task is to schedule this console application as timer job or Web Job.

Meaning this Console Application needs to call on specific interval to generate file.
In this demo we are going to see 2 different scenarios to upload or publish solution on Azure.
1. Using Publishing Profile from Visual Studio
2. Manual Configuration of Web Job

Using Publishing Profile from Visual Studio

Using Visual Studio we can publish our console app as WebJob. It requires Publishing Profile of Azure to be downloaded and add into Visual Studio Publish Option.

To download Publishing Profile from Azure -> Navigate to your application and click on Get publish profile as shown in below Image.

Once you click on Get publish profile it will download Azure PublishSettings profile for Visual Studio which helps us to deploy application.

Right Click on Project and Select Publish As Azure WebJob and import downloaded profile to Visual Studio.

Import profile will automatically fetch all required information for Azure and Visual Studio and it will publish application.

Import the profile and click on Next it will display web Deploy Information.

Now Visual Studio is going to publish application on Azure. You can see its information in Visual Studio Output Configuration.

Once application is deployed on Azure we can see it from Azure WebJobs

Select that WebJob and Click on Run

It will execute WebJob. You can also check its Status from Status Column of the webjob.

Click on WebJob and You can get more detail information for the service

Click on WebJob Name you can get WebJob Run Details

Once WebJob is completed we can see generated file on Azure File Share.
Navigate to Azure File Share

Click on myfilesonazure File Share
You can see generated file on Azure File Share as below

Now we will see another method to add file on Azure
Manual Publishing from Visual Studio

Navigate to AzureFilesApp\AzureFilesApp\bin\Release
Select All Files from release folder and create Zip File of all files.

Navigate to WebJobs Click on Add. It will open popup as shown below.

Provide Name of Webjobs.In File Upload you need to select ZIP file which we created from release folder. Select WebJob Type . For Scheduled Trigger you need to provide CRON Expression.
For example below syntax is used for 2 min WebJob Time. Hence WebJob will trigger on every 2min

0 */2 * * * *

You can also Map your Azure File Share to your Local PC by running below script.

net use I: \\eradarsacronjob.file.core.windows.net\myfile
sonazure /u:AZURE\mycronjob 7BX9SSHn5HK8urK9KqfBP1sOsEDWyb7wBN3zJu6TFYE1v2
EMedCYlKwzs+MyuZdPZtamI71TxlKp/bIkCmDflg==

Mapped Folder will be available in your PC as shown below Image

From Mapped Folder you can easily upload or delete file to Azure File Share.

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);
		}
	});
}