Sharepoint and REST - WebClient - Get List Data


Problem Definition

Get data from SharePoint list using REST API and WebClient.

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>
        /// 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 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




Also Look at

Sharepoint and REST - WebClient - Insert Data to List
Sharepoint and REST - WebClient - Update Data to List
Sharepoint and REST - WebClient - Delete Data from List

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)