Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Thursday, March 28, 2019

Creating a new task in SharePoint list using CSOM/Rest API


var fieldUserValues = new Array();
      fieldUserValues.push(userId);              //userid is ID of user

$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Project Tasks')/Items",
type: 'POST',
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "POST"
},
data: JSON.stringify({
__metadata: {
type: "SP.Data.Project_x0020_TasksListItem"
},
Title: taskName,             
StartDate: taskStartDate,
DueDate: taskDueDate,
PercentComplete: percentageComplete, //percentage complete should be integer
AssignedToId: { "results": fieldUserValues }
}),
success: function(data) {
alert('Item created successfully!');
},
error: function(error) {
alert(JSON.stringify(error));
}
 });

Wednesday, July 13, 2016

Retrieving all list items from a list which has crossed threshold limit in O365/sharepoint online using REST


To retrieve list item from a list which has already crossed the threshold limit i.e. 5000 items in 0365
this can only be done if we have indexed the list previously, i mean we can only query a list which has indexed column which has been created while list creation, in office 365 we cannot increase the threshold limit more than 5000 but we have an option to do that in on perm for up to 20000 items

increasing a threshold limit is not suggested by Microsoft, this will effect the performance, the only option to do this is to pull up data from a large list(more than 5000) in batches, you can batch data up to 4999 in once rest call and need to run untill the total count of the list completes

in the below code "ArchivedList" object will store all the items from a list in batch basis
use the script editor webpart to check this code.

<script src="https://yoursharepointsite/SiteAssets/Java%20Script%20Files/jquery-1.10.2.js"></script>  
<script type="text/javascript">
var ArchivedList = [];
var ListTest=[];
var i=0;
$(document).ready(
       function () {

           var spHostUrl = "https://yoursharepointsite";
           //Build absolute path to the layouts root with the spHostUrl
           var layoutsRoot = spHostUrl + '/_layouts/15/';
           $.getScript(layoutsRoot + "SP.Runtime.js", function () {
               $.getScript(layoutsRoot + "SP.js", getListData);
           }
           ); 
       }
     );
function getDataFromUrl(endpoint) {
     return jQuery.ajax({
         url: endpoint,
         method: "GET",
         headers: {
             "Accept": "application/json; odata=verbose",
             "Content-Type": "application/json; odata=verbose"
         }
     });
}
function getLargeList(nextUrl) {
     var dfd = new $.Deferred();
     if (nextUrl == undefined) {
         dfd.resolve();
         return;
     }
     getDataFromUrl(nextUrl).done(function (listItems) {
         var items = listItems.d.results;
          ListTest=items;
          ArchivedList=ArchivedList.concat(ListTest);
         var next = listItems.d.__next;
   
         $.when(getLargeList(next)).done(function (){
             dfd.resolve();
         });
     });
     return dfd.promise();
}
function getListData() {
     var documentLibName = 'Archived';
     
     https://yoursharepointsite/_api/web/lists/getbytitle(documentLibName)/items?$select=Title,No_Days,Current_x0020_State,Form_x0020_Type,Modified,ContentType/Name,ContentType/Id&$expand=ContentType&$filter=(Modified ge '"+strtDate +"' and Modified le '"+endDate+"') and startswith(ContentTypeId,'0x0120') &$top=200
     var listServiceUrl1= _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Archived')/Items?$Select=Title,No_Days,Current_x0020_State,Form_x0020_Type,Modified,ContentType/Name,ContentType/Id&$expand=ContentType&$filter=startswith(ContentTypeId,'0x0120')&$top=200";
     
     
     
     var listServiceUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + documentLibName + "')/Items?$Select=Title,No_Days,Current_x0020_State,Form_x0020_Type,Modified,ContentType/Name,ContentType/Id&$expand=ContentType&$top=200";
     $.when(getLargeList(listServiceUrl)).done(function () {
            alert(ArchivedList.length);
 });
 }

</script> 

Thursday, December 18, 2014

CRUD operations in SharePoint 2013 using REST and C#.Net

Below is CRUD operations on a SharePoint list using Rest and C#
to get this working replace site with your site name
here i am using ContactList for CRUD operations


using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
namespace REST
{
    class Program
    {
        static string sharepointUrl = "http://Site/_api/web/Lists/getByTitle('ContactList')/items";
       public static Stream postStream;
       public static string results;
       public static string newFormDigest;

        static void Main(string[] args)
        {
            GetItems();
            PostItems();
            UpdateItems();
            DeleteItem();

         
        }

        private static void DeleteItem()
        {
             //184 in the below url is Item ID of a list
            Uri uri = new Uri("http://Site/_api/web/lists/GetByTitle('ContactList')/items(184)");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.ContentType = "application/json;odata=verbose";
            request.Headers["X-RequestDigest"] = RequestDigestValue(out postStream, out results, out newFormDigest);
            request.Headers["X-HTTP-Method"] = "DELETE";
            request.Headers["IF-MATCH"] = "*";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept = "application/json;odata=verbose";
            request.Method = "POST";
            request.ContentLength = 0;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
        }

        private static void UpdateItems()
        {
         
            Uri uri = new Uri("http://Site/_api/web/lists/GetByTitle('ContactList')/items(185)");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.ContentType = "application/json;odata=verbose";
            request.Headers["X-RequestDigest"] = RequestDigestValue(out postStream, out results, out newFormDigest);
            request.Headers["X-HTTP-Method"] = "MERGE";
            request.Headers["IF-MATCH"] = "*";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept = "application/json;odata=verbose";
            request.Method = "POST";
            string stringData = "{'__metadata':{'type':'SP.Data.ContactListListItem'}, 'Title':'Jaffa','Street':'Mystreet','City':'Chennai'}";
           // string stringData = "{ '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }";
            request.ContentLength = stringData.Length;
            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(stringData);
            writer.Flush();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
        }
        public Uri WebUri { get; private set; }
        private static void PostItems()
        {
            // 1st request to get the context information

         
            newFormDigest= RequestDigestValue(out postStream, out results, out newFormDigest);

            Uri webUri = new Uri("http://Site/");
       
            var digestRequest = new Uri(webUri, string.Format("/_api/web/lists/getbytitle('{0}')/items", "ContactList"));
            HttpWebRequest spNewRequest = (HttpWebRequest)HttpWebRequest.Create(digestRequest);
            CredentialCache credNewCache = new CredentialCache();

            //credNewCache.Add(new Uri(digestRequest), "NTLM", CredentialCache.DefaultNetworkCredentials);
            credNewCache.Add(digestRequest, "NTLM", CredentialCache.DefaultNetworkCredentials);
            spNewRequest.Credentials = credNewCache;
            spNewRequest.Method = "POST";
            spNewRequest.Accept = "application/json;odata=verbose";
            spNewRequest.ContentType = "application/json;odata=verbose";
            spNewRequest.Headers.Add("X-RequestDigest", newFormDigest);
            string listPostBody = "{'__metadata':{'type':'SP.Data.ContactListListItem'}, 'Title':'MyTitle','Street':'MystreetName','City':'Delhi'}";
   


            // For Content Length

            byte[] postByte = Encoding.UTF8.GetBytes(listPostBody);
            spNewRequest.ContentLength = postByte.Length;
            Stream postStreamBody = spNewRequest.GetRequestStream();
            postStreamBody.Write(postByte, 0, postByte.Length);
            postStreamBody.Close();
            HttpWebResponse webResponse = (HttpWebResponse)spNewRequest.GetResponse();
            results = GetHTTPResponse(webResponse, out postStream, out results);

        }

        private static string RequestDigestValue(out Stream postStream, out string results, out string newFormDigest)
        {
            string formdigestRequest = "http://Site/_api/contextinfo";
            CredentialCache credCache = new CredentialCache();
            credCache.Add(new Uri(formdigestRequest), "NTLM", CredentialCache.DefaultNetworkCredentials);
            HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(formdigestRequest);

            spRequest.Credentials = credCache;
            spRequest.Method = "POST";
            spRequest.Accept = "application/json;odata=verbose";
            spRequest.ContentLength = 0;


            HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();
            results = GetHTTPResponse(endpointResponse, out postStream, out results);



            // Get the FormDigest Value

            var startTag = "FormDigestValue";
            var endTag = "LibraryVersion";
            var startTagIndex = results.IndexOf(startTag) + 1;
            var endTagIndex = results.IndexOf(endTag, startTagIndex);
            newFormDigest = null;
            if ((startTagIndex >= 0) && (endTagIndex > startTagIndex))
            {

                newFormDigest = results.Substring(startTagIndex + startTag.Length + 2, endTagIndex - startTagIndex - startTag.Length - 5);

            }
            return newFormDigest;
        }
        private static String GetHTTPResponse(HttpWebResponse endpointResponse, out  Stream postStream, out  string results)
        {
            postStream = endpointResponse.GetResponseStream();
            StreamReader postReader = new StreamReader(postStream);
            results = postReader.ReadToEnd();
            postReader.Close();
            postStream.Close();
            return results;
        }
        private static void GetItems()
        {
           //Replace "Site" with your site name
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create("http://Site/_api/web/Lists/getByTitle('ContactList')/items");

            endpointRequest.Method = "GET";
            endpointRequest.Accept = "application/json;odata=verbose";
            NetworkCredential cred = new System.Net.NetworkCredential("UserName", "Password", "Domain");
            endpointRequest.Credentials = cred;
            HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            try
            {
                WebResponse webResponse = endpointRequest.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();
                JObject jobj = JObject.Parse(response);
                JArray jarr = (JArray)jobj["d"]["results"];

                foreach (JObject j in jarr)
                {
                    //City and County are column names in a list
                    Console.WriteLine(j["City"] + "  " + j["County"]);

                }

                responseReader.Close();
                Console.ReadLine();

            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message); Console.ReadLine();
            }
        }
    }

}

SharePoint - Cannot convert a primitive value to the expected type 'Edm.Double'. See the inner exception for more details If y...

Ad