Wednesday, April 30, 2014

SharePoint 2010 - Using REST in client application

Hi guys,

today I want to show you, how you to get data from a SharePoint 2010 Server by using a REST client. 

Imagine we have a document library "How To" in a site collection "IT" on a SharePoint 2010 Server like this one:


We write a small console application to request all documents from this document library. The user can enter a search string and the results will be displayed after the input.

Ok, let's create a new solution in Visual Studio 2010:

I called the solution "REST-Solution".
Press "Ok" to create it.

After Visual Studio has created the solution, we have to add a service reference.

We have to enter the address to the service. In SharePoint 2010 we always find this service for each site in the "_vti_bin" folder. It's name is listdata.svc.
You can enter a different namespace in the text line. I called it ServiceReference1.


After adding the service reference to the project, we need to add 2 rows in the "using"-section:


Code Section: 
using REST_Solution.ServiceReference1;
using System.Net;
Note: In the first line, you have to use your solution name with the name of your service reference.

Then we can add our code.

Note:
The class name of the data context ("ctx" object) depends of the name of your Sharepoint site. In my case it is "IT", so the class name is "ITDataContext".
I think, the code is self-explanatory.

Code Section:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using REST_Solution.ServiceReference1;
using System.Net;
namespace REST_Solution
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create Uri
            Uri myUri = new Uri("http://testportal.grolman.de/sites/IT/_vti_bin/listdata.svc");
            // Create DataContext with Uri
            ITDataContext ctx = new ITDataContext(myUri);
            // Set Credentials
            ctx.Credentials = CredentialCache.DefaultCredentials;
            Console.WriteLine("Please enter search string:");
            // Get user input:
            string searchString = Console.ReadLine();
            // Create Query
            var linqQuery =
                from document in ctx.HowTo
                where document.Name.Contains(searchString)
                select document;
            // Results
            Console.WriteLine("Results:");
            foreach (HowToItem howtoItem in linqQuery)
            {
                Console.WriteLine("Document: " + howtoItem.Name + " / Version: " + howtoItem.Version);
            }
            // Stop here, wait for user input
            Console.ReadLine();
        }
    }
}
That's all. Start the program and you see it works fine:

All without using the client object model of SharePoint.

No comments:

Post a Comment