Sharepoint and REST - WebClient - Update Data to List

Problem Definition

Update data in SharePoint list using REST API and WebClient based on Item id. 

In this code write up we are updating Item Id# 5, please check the 'get example' or see snapshot before update in results section to see details about item# 5.

Prerequisites

In order to effectively deal with the data in the SharePoint List I will recommend using Newtonsoft.JSON that makes dealing with List data a lot easier.

In order to get JSON plugin go to NuGet and search for JSON.NET or NEWTONSOFT


SharePointAndRest_WebClient.cs

class dealing with SharePoint Data fetch:





Code Help

/// <summary>
/// Implement Sharepoint Functionality using WebClient
/// </summary>
    public class SharePointAndRest_WebClient : IDisposable
    {
        private readonly WebClient webClient;
        public Uri WebUri { get; private set; }

        /// <summary>
        /// Intialize webclient and set it up for use with sharepoint using Default Credentials
        /// </summary>
        /// <param name="webUri">Basic url to sharepoint site</param>
        public SharePointAndRest_WebClient(Uri webUri)
        {
            webClient = new WebClient();
            webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
            webClient.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
            webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0");
            webClient.UseDefaultCredentials = true;
            WebUri = webUri;
        }
        /// <summary>
        /// Provides form data digest
        /// </summary>
        /// <returns></returns>
        private string GetFormDigest()
        {
            var endpointUri = new Uri(WebUri, "_api/contextinfo");
            var result = webClient.UploadString(endpointUri, "POST");
            JToken t = JToken.Parse(result);
            return t["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
        }
        /// <summary>
        /// Update Data in Sharepoint List
        /// </summary>
        /// <param name="listTitle">List Title</param>
        /// <param name="payload">Data Payload</param>
        /// <param name="id">Item Id to update</param>
        public void UpdateItem(string listTitle, object payload,int id)
        {
            var formDigestValue = GetFormDigest();
            webClient.Headers.Add("X-RequestDigest", formDigestValue);
            //Following code is required to perform the update
            webClient.Headers.Add("X-HTTP-Method", "MERGE");
            webClient.Headers.Add("IF-MATCH", "*");
            var endpointUri = new Uri(WebUri, string.Format("_api/web/lists/getbytitle('{0}')/items({1})", listTitle,id));
            var payloadString = JsonConvert.SerializeObject(payload);
            webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
            webClient.UploadString(endpointUri, "POST", payloadString);
        }
        /// <summary>
        /// Get all the items from the specified list and send response back in the form of JToken
        /// </summary>
        /// <param name="listTitle"></param>
        /// <returns></returns>
        public JToken GetListItems(string listTitle)
        {
            var endpointUri = new Uri(WebUri, string.Format("_api/web/lists/getbytitle('{0}')/items", listTitle));
            var result = webClient.DownloadString(endpointUri);
            var t = JToken.Parse(result);
            return t["d"]["results"];
        }

        /// <summary>
        /// IDisposable Implementation
        /// </summary>
        public void Dispose()
        {
            webClient.Dispose();
            GC.SuppressFinalize(this);
            GC.Collect();
        }
    }

SharePointAndRest.cs

Method calling SharePointAndRest_WebClient Class:

Code Help

 /// <summary>
        /// This method supplied the data and calls the execution of Insert
        /// </summary>
        public static void SharepointAndRest_WebClient_Update()
        {
            var webUri = new Uri(@"http://<your server>/<site>/");

            using (var client = new SharePointAndRest_WebClient(webUri))
            {
                var testEntry = new
                {
                    __metadata = new { type = "SP.Data.MessageTestListItem" },
                    Title = "TestEntry1",
                    FirstName = "Byte1",
                    LastName = "Rodeo1",
                    EmailAddress = "test@test6789.com",
                    PhoneNumber = "(XXX) XXX-XXXX",
                    AlternatePhoneNumber = "(YYY) YYY-YYYY"
                };
                client.UpdateItem("MessageTest", testEntry,5);
            }
        }

        /// <summary>
        /// This method gets the data from sharepoint list and prints it on console
        /// </summary>
        public static void SharepointAndRest_WebClient_Get()
        {
            var webUri = new Uri(@"http://<your server>/<site>/");
            Console.Write(("Id").PadRight(3));
            Console.Write(("Title").PadRight(10));
            Console.Write(("First Name").PadRight(12));
            Console.Write(("Last Name").PadRight(12));
            Console.Write(("Phone#").PadRight(15));
            Console.Write(("Email").PadRight(10));
            Console.WriteLine(" ");

            using (var client = new SharePointAndRest_WebClient(webUri))
            {
                var x = client.GetListItems("MessageTest");
                foreach (var item in x)
                {
                    Console.Write(((string)item["Id"]).PadRight(3));
                    Console.Write(((string)item["Title"]).PadRight(10));
                    Console.Write(((string)item["FirstName"] ?? string.Empty).PadRight(12));
                    Console.Write(((string)item["LastName"] ?? string.Empty).PadRight(12));
                    Console.Write(((string)item["PhoneNumber"] ?? string.Empty).PadRight(15));
                    Console.Write(((string)item["EmailAddress"] ?? string.Empty).PadRight(10));
                    Console.WriteLine(" ");
                }
            }
        }

Result

Data Before Update


Data After Update

Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)