Using .NET to Retrieve Information from SharePoint '13 for Web Apps

When you work in mobile app development or web development projects, it's really important to have an order in your process and have a good record of your workflows and having the right tool for the job it's really helpful to speed up the process.

Microsoft Share Point for Web and Mobile App Development with .NET

In .NET development for web apps, we all know how powerful Microsoft SharePoint is, and we have been part of its amazing workflows ad list interaction but, can we do more? Yes, we can.

I will show you how to retrieve information from SharePoint 2013 site from a simple .Net Application. What do we need?

  1. Microsoft Visual Studio 2012 +, VS2010 will do it but I like 2012 much more.
  2. SharePoint 2013 site with full access credentials (important! Otherwise, it won’t work).
  3. Some time to do it.

Getting Started

First of all, we need to understand how SharePoint works. It is actually pretty simple and  that is what amazes me more.

In SharePoint you can have lists, each list could have fields as stars in the sky, ok, I'm kidding 255 max, but its more than I can use.  If you need more than this, I’ll suggest start using SQL Server.

Each list is basically a table and SharePoint provides a beautiful and simple UI to interact with it. Also you can have any list working on a workflow, so you can collect data within a process.

SharePoint 2013 Site Lists

SharePoint 2013 site lists resized 600

Each list could store entries as stars in the sky.  This time, it is true, the only limit is your database size but it can grow easily. For this example, I’m going to use a simple one, one field only and only 8 entries.

Sharepoint entries

Let Get the Party Started with Visual Studio

Creating the VS Solution

If you are already dealing with these kind of situations, I’m pretty sure you already know how to create a new solution on Visual Studio, but just in case you forgot, this is a quick guide.

  1. Open Visual Studio
  2. File Menu (click)
  3. New Menu (click)
  4. Project (click)
  5. The tricky part is here… You need to choose a project type and it should be based on your needs, for this example, I’ll use MVC 4 web application using the .Net Framework 4 because I’m going to build a very simple REST API
  6. In my case, I’ll create it empty, I don’t need anything from the existing template.

Coding

The Model. First of all you need to create a model (class) that matches the List that you’re retrieving from SharePoint. It does not need to be exact as the List, but only needs to match your needs against the List. For this example, my class looks like this:

public class Allergies
{
     public int data_it { get; set; }
     public string data_modified { get; set; }
     public string allergy_name { get; set; }
}

Also I recommend that your class name matches the List name as it will make things easier in the future.

Connecting. Of course, we need to get connected to the SharePoint, but how? In previous versions, the authentication to SharePoint services was something pretty close to rocket science due to the fact that you need to implements certificates, encryption or at least a guard dog and a weird way to implement it.

In this version, SharePoint 2013 offers the OmAuth that makes the connection with it pretty simple and to make it much easier, you can download and implement the usage of two classes: ClientOmAuth.cs and MSOnlineHelper.cs, click here. You only need to add it to your solution and call the proper methods & functions.

I’ve created a function that returns a collection of my class, and inside it, I will first create the connection context using the MSOnlinHelper class.

Before doing anything, I’ll create a container for those objects.

List<Allergies> allergies = new List<Allergies>();
MsOnlineClaimsHelper claimsHelper = new MsOnlineClaimsHelper(@"https://your.SharePoint2013Site.com/YourLibrary/", "yourUserName@ofYourSite.onmicrosoft.com", "YourSuperSecret&SecurePasswordThatIsMaybe1234");
Pretty simple right? I will suggest, and this is only a suggestion, that you DO NOT, hardcode the user & password.

Then, you need to consume this connection context and create a new “Connected Context” as shown below.

using (ClientContext context = new ClientContext(@"https://your.SharePoint2013Site.com/YourLibrary/"))

If you use this with “using”, the object will be disposed and also it will disconnect by itself when is not used anymore.

Here is the code for the context:

The web request: Add a WebRequest event for this. You need to specify the SharePoint List name here.

 
 
context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;
                List allergiesList = context.Web.Lists.GetByTitle("Allergies");

Then, create the query and in this case, I’ll bring the whole list

 
 
                CamlQuery query = CamlQuery.CreateAllItemsQuery();
                ListItemCollection items = allergiesList.GetItems(query);

 

Load the query data. You will be able to debug just after this step.

                context.Load(items);
                context.ExecuteQuery();

The fun part is creating the objects. This is a standard parsing process so you can handle the data  you need.  All the available fields are located under li.FieldValues.  Here you can check the names that are available and also the values.

                foreach (ListItem li in items)
                {
                    allergies.Add(new Allergies()
                    {
                        data_id = Convert.ToInt32(li.FieldValues["ID"]),
                        data_modified = Convert.ToDateTime(li.FieldValues["Modified"]).ToUniversalTime().ToString("yyyyMMdd HH:mm"),
                        allergy_name = Convert.ToString(li.FieldValues.FirstOrDefault(f => f.Key == "Title").Value)
                    });
                }

 

Then, what to do? Its simple. You have a collection of everything on the SharePoint list do whatever you need. For this example, I’ll create a JSON response and this is the result:

JSON response

Just in case it was not clear at all, this is the whole code

public IEnumerable<Allergies> GetAllergies()
        {
            List<Allergies> allergies = new List<Allergies>();

 

            MsOnlineClaimsHelper claimsHelper = new MsOnlineClaimsHelper(@"https://your.SharePoint2013Site.com/YourLibrary/", "yourUserName@ofYourSite.onmicrosoft.com", "YourSuperSecret&SecurePasswordThatIsMaybe1234");
            using (ClientContext context = new ClientContext(@"https://your.SharePoint2013Site.com/YourLibrary/"))
            {
                context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;
                List allergiesList = context.Web.Lists.GetByTitle("Allergies");

 

                CamlQuery query = CamlQuery.CreateAllItemsQuery();
                ListItemCollection items = allergiesList.GetItems(query);

 

                context.Load(items);
                context.ExecuteQuery();

 

                foreach (ListItem li in items)
                {
                    allergies.Add(new Allergies()
                    {
                        data_id = Convert.ToInt32(li.FieldValues["ID"]),
                        data_modified = Convert.ToDateTime(li.FieldValues["Modified"]).ToUniversalTime().ToString("yyyyMMdd HH:mm"),
                        allergy_name = Convert.ToString(li.FieldValues.FirstOrDefault(f => f.Key == "Title").Value)
                    });
                }
            }

 

            return allergies;
        }

About the Author

Luis G. Hernandez ia s Software Engineer with a Masters Degree in Software Architecture on going with 10+ years working on Microsoft development technology including SQL Server, SharePoint and Business Intelligence, Microsoft Fan Boy, Microsoft Certified Professional.

Oscar Salas

Written by Oscar Salas

Oscar Salas is a B2B Digital Marketing Specialist with 5 years of experience, who has helped organizations to grow and expand through strategic brand development and marketing programs. Analytical thinker, cat lover, he enjoys to play the piano and listening to Led Zeppelin He's currently leading the iTexico Demand Gen strategies.

Explore iTexico, The Nearshore + Company 

Explore The Nearshore Services

Read More

Mobile Competency Center

Recent Posts