Wednesday, May 13, 2020

Get More than 5000 records from SharePoint list by rest API through recursive call



Get More than 5000 records from SharePoint list by rest API through recursive call
--------------------------------------------------------------------------------

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

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ECO_Documents')/items?$top=4999&$orderby=ID";
    var response = response || [];  // this variable is used for storing list items
   
    function GetListItems(){
        return $.ajax({
            url: url, 
            method: "GET", 
            headers: { 
                "Accept": "application/json; odata=verbose" 
            },
            success: function(data){
                response = response.concat(data.d.results);
                if (data.d.__next) {
                    url = data.d.__next;
                   // console.log(url);
                    GetListItems();
                }
            },
             error: function (error) {
            alert(JSON.stringify(error));
           }
        });
    }

Saturday, April 25, 2020

Autocomplete text box , content directly from AD, Name, Email etc


Autocomplete text box , content directly from AD, Name, Email etc
---------------------------------------------------------------------


[WebMethod]
        public static List<UserProperty> GetADUsers(string username)
        {
            List<UserProperty> lstADUsers = new List<UserProperty>();

            if (!string.IsNullOrEmpty(username))
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                {
                    UserPrincipal user = new UserPrincipal(context);
                    user.DisplayName = username + "*";
                    using (PrincipalSearcher srch = new PrincipalSearcher(user))
                    {
                        int i = 0;
                        foreach (var result in srch.FindAll())
                        {
                            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                            if (!String.IsNullOrEmpty((String)de.Properties["displayName"].Value))
                            {
                                i++;
                                UserProperty usp = new UserProperty();
                                usp.UserName = de.Properties["displayName"].Value.ToString();
                                if (de.Properties["mail"].Value != null)
                                    usp.Email = de.Properties["mail"].Value.ToString();

                                //if (de.Properties["EmployeeId"].Value != null)
                                //{
                                //    usp.EmpId = de.Properties["EmployeeId"].Value.ToString();
                                //}
                                //else
                                //    usp.EmpId = string.Empty;

                                lstADUsers.Add(usp);
                                if (i == 10) break;

                            }
                        }
                    }
                }
            }
            return lstADUsers;
        }

Wednesday, January 8, 2020

Auto Generate New Id in MS SQL in Procedure

USE [CIF_DB]
GO
/****** Object:  StoredProcedure [dbo].[GetRequestNo]    Script Date: 1/8/2020 6:11:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--EXEC GetRequestNo
ALTER PROCEDURE [dbo].[GetNewCIF_ID]
AS
BEGIN

DECLARE @RequestNo varchar(20),@maxCount bigint

select @maxCount =  count(*) from [dbo].[CIF_Requests]

if(@maxCount <> 0)
SET @RequestNo =  'TIF_'+RIGHT('000000' + CONVERT(nvarchar(20), @maxCount + 1), 6)
    else
 
    SET @RequestNo =  'TIF_'+RIGHT('000000' + CONVERT(nvarchar(20), 1), 6)


SELECT @RequestNo
 END



Wednesday, July 10, 2019

SharePoint online OOB small Calendar customisation




<style type="text/css">
.ms-acal-item{height: 10px !important;}
.ms-acal-sdiv,
.ms-acal-mdiv,
.ms-acal-ctrlitem,
.ms-acal-month-weeksel,
.ms-acal-title,
.ms-acal-month-top span{display: none;}
.ms-acal-summary-itemrow TD DIV{height: 14px !important;}
.ms-acal-vlink td{display: none;}
.ms-acal-sdiv {display: none}
.ms-acal-item {
    background-color: rgba(0, 188, 212, 0.5803921568627451) !important;
}
.ms-acal-month
{
background-color:white;
}

</style>
<script type="text/javascript" src="/sites/BIM_QA/SiteAssets/AGS/CalenderJs.js"></script>



           <div class="col-xs-12 no-padding">
<div class="upcoming_events">
<div class="right_title">UPCOMING EVENTS <span></span></div>


</div>
</div>





Wednesday, May 22, 2019

Add Attachment in SharePoint List item by REST API in SPO



var currentUser;
$(document).ready(function(){

   GetUserDetails();
 
    $("#designFile").change(function() {
    file = $(this)[0].files[0];
    fileArray.push(file);
  });
 
  $("#storyFile").change(function() {
    file = $(this)[0].files[0];
    fileArray.push(file);
  });

});

    function GetUserDetails() { 
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser"; 
    $.ajax({ 
        url: url, 
        headers: { 
            Accept: "application/json;odata=verbose" 
        }, 
        async: false, 
        success: function (data) { 
            var items = data.d.results; // Data will have user object     
            GetUser(data);
        }, 
        eror: function (data) { 
            alert("An error occurred. Please try again."); 
        } 
    }); 
    }
   
    function GetUser(data)
    {   
         var userName = data.d["Title"];
         var Email = data.d["Email"];
         $('#UserName').val(userName);
         $('#Email').val(Email );
         $('#UserName').attr('disabled','disabled');
         $('#Email').attr('disabled','disabled');
       
    } 
 
  function SaveValues()
  {
    var userName =  $('#UserName').val();
    var email =     $('#Email').val(); 
    var desc=       $('#desc').val(); 
    var userId =   _spPageContextInfo.userId;     

    var listName = "CE Dashboard Design Contest Page";

var itemProperties = {
    "__metadata": { "type": "SP.Data.CE_x0020_Dashboard_x0020_Design_x0020_Contest_x0020_PageListItem" },
    "Email": email,
    "Description":desc,
    "NameId":userId
   };

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_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) {
        console.log(JSON.stringify(data.d));
        UploadFiles(listName,data.d.ID);
    },
    error: function (data) {
        console.log(data.responseText);
    }
});
   
   
  }
 
  var ID = 1;  var fileArray = [];
 var listname = "UploadTEST";




function UploadFiles(listName,itemId)
{
  if (fileArray.length != 0)
  {
     for (i = 0; i < fileArray.length; i++){ 
           uploadFile(listName,itemId, fileArray[i])
     }
     alert('Your files submitted sucessfully !!');
     $('#desc').val('');
     location.reload();
  }
}
 
  function uploadFile(listname, ID, file) { 
        var getFileBuffer = function (file) { 
 
            var deferred = $.Deferred(); 
            var reader = new FileReader(); 
 
            reader.onload = function (e) { 
                deferred.resolve(e.target.result); 
            } 
            reader.onerror = function (e) { 
                deferred.reject(e.target.error); 
            } 
            reader.readAsArrayBuffer(file); 
            return deferred.promise(); 
        }; 
 
        getFileBuffer(file).then(function (buffer) { 
            $.ajax({ 
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + file.name + "')", 
                method: 'POST', 
                async: false, 
                data: buffer, 
                processData: false, 
                headers: { 
                    "Accept": "application/json; odata=verbose", 
                    "content-type": "application/json; odata=verbose", 
                    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value 
 
                }, success: onAttachmentSucess(file.name) 
 
            }); 
 
        }); 
        function onAttachmentSucess(name) {         
             
        } 
       
               
    }
   


 
  

Monday, October 29, 2018

Showing Excel to div export in SharePoint CEWP

 function ExportToTable() {
            $('#loading').show();
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
            if (regex.test($("#excelfile").val().toLowerCase())) {
                var xlsxflag = false;
                if ($("#excelfile").val().toLowerCase().indexOf(".xlsx") > 0) {
                    xlsxflag = true;
                }
                if (typeof (FileReader) != "undefined") {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var data = e.target.result;
                        if (xlsxflag) {
                            var workbook = XLSX.read(data, { type: 'binary' });
                        }
                        else {
                            var workbook = XLS.read(data, { type: 'binary' });
                        }
                        var sheet_name_list = workbook.SheetNames;
                        var cnt = 0;
                        sheet_name_list.forEach(function (y) {
                            if (xlsxflag) {
                                var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
                            }
                            else {
                                var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
                            }
                            if (exceljson.length > 0 && cnt == 0) {
                                BindTable(exceljson, '#exceltable');
                                exceljson.forEach(function (excelRow) {
                                    if (excelRow != null && Object.keys(excelRow).length > 0 && excelRow["Number"] != null && excelRow["Name"].toString() != "") {
                                        getEmployeeDetailsByEmployeeID(excelRow["Number"].toString().trim(), excelRow);
                                    }
                                });
                                cnt++;
                            }
                        });
                        $('#loading').hide();
                        $('#exceltable').show();
                    }
                    if (xlsxflag) {
                        reader.readAsArrayBuffer($("#excelfile")[0].files[0]);
                    }
                    else {
                        reader.readAsBinaryString($("#excelfile")[0].files[0]);
                    }
                }
                else {
                    $('#loading').hide();
                    alert("Sorry! Your browser does not support HTML5!");
                }
            }
            else {
                $('#loading').hide();
                alert("Please upload a valid Excel file!");
            }
        }
        function BindTable(jsondata, tableid) {
            var columns = BindTableHeader(jsondata, tableid);
            for (var i = 0; i < jsondata.length; i++) {
                var row$ = $('<tr/>');
                for (var colIndex = 0; colIndex < columns.length; colIndex++) {
                    var cellValue = jsondata[i][columns[colIndex]];
                    if (cellValue == null)
                        cellValue = "";
                    row$.append($('<td/>').html(cellValue));
                }
                $(tableid).append(row$);
            }
        }
        function BindTableHeader(jsondata, tableid) {
            var columnSet = [];
            var headerTr$ = $('<tr/>');
            for (var i = 0; i < jsondata.length; i++) {
                var rowHash = jsondata[i];
                for (var key in rowHash) {
                    if (rowHash.hasOwnProperty(key)) {
                        if ($.inArray(key, columnSet) == -1) {
                            columnSet.push(key);
                            headerTr$.append($('<th/>').html(key));
                        }
                    }
                }
            }
            $(tableid).append(headerTr$);
            return columnSet;
        }
        function getEmployeeDetailsByEmployeeID(EmployeeIDValue, excelRow) {
            var objHeaders = {
                type: "GET",
                headers: {
                    "accept": "application/json;odata=verbose"
                },
                async: false,
                mode: 'cors',
                cache: 'no-cache',
                credentials: 'include'
            }
            fetch(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('BIM%20search')/items?$filter=Number eq '" + EmployeeIDValue + "'&$select=ID,Name", objHeaders)
                .then(function (response) {
                    return response.json()
                })
            .then(function (json) {
                var results = json.d.results;
                if (results.length > 0) {
                    for (i in results) {
                        updateEmployeeDetailsListItem(results[i].ID, excelRow);
                    }
                }
                else {
                    createEmployeeDetailsListItem(excelRow);
                }
            })
            .catch(function (ex) {
                console.log("error");
            });
        }
        function updateEmployeeDetailsListItem(itemID, excelRow) {
       
       
        var recordID;
          /*  $.ajax
            ({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('BIM%20Search')/items(" + itemID + ")",
                type: "POST",
                data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.BIM%20searchListItem"
                    },
                    Name: excelRow["Name"]
                     }),
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "IF-MATCH": "*",
                    "X-HTTP-Method": "MERGE"
                },
                async: false,
                success: function (data, status, xhr) {
                    console.log("success");
                },
                error: function (xhr, status, error) {
                    console.log("errro");
                }
            }); */
           
           
      $().SPServices({
            operation: "UpdateListItems",
            async: false,
            batchCmd: "Update",
            listName: "BIM Search",
            ID:itemID,
            valuepairs: [["Name", "Test2"],["test", "Test2"]],
            completefunc: function (xData, Status) {
            alert("updated");
        }
    });           
 
 


           
           
           
           
           
        }
        function createEmployeeDetailsListItem(excelRow) {
          /*  $.ajax
                ({
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('BIM%20Search')/items",
                    type: "POST",
                    data: JSON.stringify
                    ({
                        __metadata:
                        {
                            type: "SP.Data.BIM%20searchListItem"
                        },
                        Name: excelRow["Name"]
                         }),
                    headers:
                    {
                        "Accept": "application/json;odata=verbose",
                        "Content-Type": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                        "X-HTTP-Method": "POST"
                    },
                    success: function (data, status, xhr) {
                        console.log("success");
                    },
                    error: function (xhr, status, error) {
                        console.log("error");
                    }
                }); */
               
               
                             
  /* $.ajax 
        ({ 
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('BIM%20Search')/items", 
        type: "POST", 
        cache: true,
        data: JSON.stringify 
        ({ 
            __metadata: 
            { 
                type: "SP.Data.TestListItem" 
            }, 
            Name: excelRow["Name"],
            Description:  excelRow["Description"]
        }), 
        headers: 
        { 
            "Accept": "application/json;odata=verbose", 
            "Content-Type": "application/json;odata=verbose", 
            "X-RequestDigest": $("#__REQUESTDIGEST").val(), 
            "X-HTTP-Method": "POST" 
        }, 
        success: function(data, status, xhr) 
        { 
            console.log("success");
        }, 
        error: function(xhr, status, error) 
        { 
             console.log("error"); 
        } 
    });       */     
   

if(excelRow["Business Owner"] !=""){
 alert(excelRow["Business Owner"]);

var name = excelRow["Business Owner"];

 $().SPServices({
     operation: "GetUserInfo",
     async: false,
     userLoginName: name,
     completefunc: function (xData, Status) {
         $(xData.responseXML).find("User").each(function() {
             userID = $(this).attr("ID");
             alert(userID);
         });
     }
 }); 
               
       }                       
                 $().SPServices({
            operation: "UpdateListItems",
            async: false,
            batchCmd: "New",
            listName: "BIM Search",
            valuepairs: [["Name", excelRow["Name"]],["Description",excelRow[" Description"]],["test",excelRow[" Description"]],["Number",excelRow["Number"]],["BusinessOwner", userID ]],
            completefunc: function (xData, Status) {
                           
               if(Status == "success"){           
                alert("Data Saved! and Please check your List");
               }
             
              else{
                  console.log("error to add new item number:"+excelRow["Number"])             
                   }             
               
               
            }
        });
               
               
               
               
               
               
               
               
               
        }

Tuesday, September 25, 2018

Upload File JS File

Upload File JS File
==================

'use strict';

jQuery(document).ready(function () {

    // Check for FileReader API (HTML5) support.
    if (!window.FileReader) {
        alert('This browser does not support the FileReader API.');
    }
});

// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {

    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '/UserShipment';

    // Get test values from the file input and text input page controls.
    var fileInput = jQuery('#getFile');
    var newName = jQuery('#displayName').val();

    // Get the server URL.
    var serverUrl = _spPageContextInfo.webAbsoluteUrl;

    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {

        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {

            // Get the list item that corresponds to the uploaded file.
            var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function (listItem, status, xhr) {

                // Change the display name and title of the list item.
                var changeItem = updateListItem(listItem.d.__metadata);
                changeItem.done(function (data, status, xhr) {
                    alert('file uploaded and updated');
                });
                changeItem.fail(onError);
            });
            getItem.fail(onError);
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);

    // Get the local file as an array buffer.
    function getFileBuffer() {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[0]);
        return deferred.promise();
    }

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer) {

        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        var fileName = parts[parts.length - 1];

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder, fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }

    // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
    function getListItem(fileListItemUri) {

        // Send the request and return the response.
        return jQuery.ajax({
            url: fileListItemUri,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" }
        });
    }

    // Change the display name and title of the list item.
    function updateListItem(itemMetadata) {

        // Define the list item changes. Use the FileLeafRef property to change the display name.
        // For simplicity, also use the name as the title.
        // The example gets the list item type from the item's metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
            itemMetadata.type, newName, newName);

        // Send the request and return the promise.
        // This call does not return response content from the server.
        return jQuery.ajax({
            url: itemMetadata.uri,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            }
        });
    }
}

// Display error messages.
function onError(error) {
    alert(error.responseText);
}