Sharepoint and REST - WebClient - Delete Data from List

Problem Definition

Delete data from SharePoint list using REST API and WebClient based on Item id. 

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

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 and delete:





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>
        /// Delete Data from Sharepoint List based on Item ID
        /// </summary>
        /// <param name="listTitle">List Title</param>
        /// <param name="payload">Data Payload</param>
        /// <param name="id">Item Id to update</param>
        public void DeleteItem(string listTitle, int id)
        {
            var formDigestValue = GetFormDigest();
            webClient.Headers.Add("X-RequestDigest", formDigestValue);
            //Following code is required to perform the delete
            webClient.Headers.Add("X-HTTP-Method", "DELETE");
            webClient.Headers.Add("IF-MATCH", "*");
            var endpointUri = new Uri(WebUri, string.Format("_api/web/lists/getbytitle('{0}')/items({1})", listTitle, id));
            webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
            webClient.UploadString(endpointUri, "POST",String.Empty);
        }

        /// <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 supplies the id and calls the execution of Delete on that Id
/// </summary>
 public static void SharepointAndRest_WebClient_Delete()
{
            //var webUri = new Uri(@"http://<your server>/<site>/");
            using (var client = new SharePointAndRest_WebClient(webUri))
            {
                client.DeleteItem("MessageTest",2);
            }
        }
        /// <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 Delete(ID# 2)


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)