Infopulse - Expert Software Engineering, Infrastructure Management Services
Send message Request a call
Send message Please fill in this quick form and we will send you a free quote shortly.
* Required fields
Request a call Please fill in this quick form and we will call you back shortly.
* Required fields
Subscribe to Infopulse Newsletter Please fill in this quick form to be among the first to receive our updates.
* Required fields
Send an email to Bogdan Tanygin Please fill in this quick form to contact our expert directly.
* Required fields
Read the rest of the Case Study Don't miss the most interesting part of the story!
Submit this quick form to see the rest and to freely access all case studies on our website.
* Required fields

Working with SharePoint Foundation REST Interface Using OData and jQuery

SharePoint Foundation REST Interface is a service that appeared in Microsoft SharePoint 2010.

The main concept of this web service is that all SharePoint lists and elements are presented as HTTP resources with remote access through URL. It’s a potential RESTful service. It has a conventional functionality: read, write, edit and delete. Data output can be represented both in XML and in JSON. The web service supports Open Data Protocol that will be described below. All this provides for high flexibility and its compatibility with any applications that can send HTTP requests.

I have learnt SharePoint Foundation REST Interface rather recently and immediately understood that it’s handy. I regretted not knowing it before. Of course, it’s not a panacea for all cases but it sometimes makes life much easier.

Use this link to access SharePoint Foundation REST Interface:

  
  http://{server_name}/_vti_bin/listdata.svc

It can be used right after Microsoft SharePoint Foundation 2010 is installed without requiring any additional configuration.

Having opened this link, you’ll see XML with all available lists and libraries in SharePoint both conventional and administrator-created, e.g. user list is accessible through URL:

  
  http://{server_name}/_vti_bin/listdata.svc/UserInformationList

Open Data Protocol

Open Data Protocol is an open web protocol for data requesting and updating. This protocol allows working with resources by using HTTP commands as requests and receiving responses in JSON or XML formats.

With the users list received from the web service, you will notice that it retrieves users as well as groups. They differ in the ContentType value. ContentType of users has the Person value. Now, to filter users only, we can use the web service’s ability to work with OData. Add the $filter variable to the URI:

  
  http://{server_name}/_vti_bin/listdata.svc/UserInformationList?$filter=ContentType eq 'Person'

As the result, we get the list of all users.

The web part also utilizes a dynamic name lookup at typing. That is why the search and sort should be done by user name. Let’s choose a more complicated filter:

  
  http://{server_name}/_vti_bin/listdata.svc/UserInformationList?$filter=((ContentType eq 'Person') 
  and (substringof(Name,'{query}')))&$orderby=Name

Now, the selection contains only those users whose name contains a substring {query}.

As you will see, the web service returns a lot of information that is not always necessary. That is why the size of the end file can be reduced by selecting the required fields. To do this just add the $select variable:

  
  http://{server_name}/_vti_bin/listdata.svc/UserInformationList?$filter=((ContentType eq 'Person') 
  and (substringof(Name,'{query}')))&$orderby=Name&$select=Id,Name,ContentType

Now the end file contains only the three selected fields.

So, the flexibility was rightfully mentioned as the request with OData parameters can be of any complexity. In this way, with little effort you can obtain data from any SharePoint sheet or library, either news, a list of documents or any other thing.

As was said at the very beginning, SharePoint Foundation REST Interface allows not only getting data but also adding, editing and deleting it. For the “how’s” and many other capabilities of Open Data Protocol, please check this link.

No C#, use jQuery

Let’s consider a particular example of the web service and build a small web part on it.

The web part will schematically look as follows:

At the beginning

At the beginning

Start typing the user name

Type the user name

The user is selected

User is selected

As said above, no programming will be done on the server. Everything is done on the client side and with the help of jQuery and $.ajax(). Of course, we cannot do without a studio-created and deployed project, but a special programmer will not be required as it can be done by any web designer.

Create a web-part project and add all required files to it:

Create the web part

Create the web part

This is how the project structure looks with all file added

Project structure

Now, you need to connect css and JavaScript files to ascx control. Open EmployeesWebPartUserControl.ascx and enter the following code:

  
  // connect css for jQuery Autocomplete

// connect the css file with the description of styles for the web part elements 

// connect javascripts

Paste the HTML code of the web part in the same file:

<div>

<input type=”search” name=”wpuser_search” id=”wpuser_search” placeholder=”Search as you type…” />

</div>

<div>

<div>

        <div id="wpuser_image"><img src="" /></div>

<div>

            <div id="wpuser_name"></div>

<div id=”wpuser_position”></div>

            <div id="wpuser_departament"></div>

<div id=”wpuser_status”></div>

        </div>

</div>

    <div>

<div>Ask me about:</div>

        <div id="wpuser_asklist"></div>

<ul>

            <li id="wpuser_phone"><span>Mobile:</span> <a href=""></a></li>

<li id=”wpuser_email”><span>Email:</span> <a href=””></a></li>

        </ul>

</div>

</div>

It is, so to speak, a template of the web part. jQuery will be used to fill in the empty divs with values received from $.ajax().

So, with the preparation done, we can start writing the code.

The way to retrieve the list of users is simple and clear:

// URL of the web service with required parameters
var serviceUrl = "/_vti_bin/listdata.svc/UserInformationList?$filter=ContentType 
eq 'Person'&$orderby=Name";
// request is sent
$.ajax({
    'type': 'GET',
    'url': serviceUrl,
    'dataType': 'json',
    'success': function(data){ userSearch(data['d']['results']); }
});

Do not forget to add this parameter:

'dataType': 'json'

Without it, the web service will return an XML instead of a JSON.

In fact, I have shuffled and used the ready-made plug-in — jQuery Autocomplete

This plug-in can have values represented not only by a ready-made array of elements but also it can process the service URL returned by JSON. Unfortunately, I’ve failed to make it work directly with the SharePoint web service. The plug-in returned some error when it was analyzing the retrieved data and I was too lazy to sort out the problem. Besides, it seemed better to retrieve the whole list of users and not wait for the service to response to every letter typed. Neither frequent requests to the server are necessary. So, the solution looked as follows:

function userSearch(data){
    $field = $("#wpuser_search");	// field with automatic look-up
    $field.autocomplete(data, {
         formatItem: function (item) { return item.Name },
         matchContains: true
    });
    $field.result(function (event, data, formatted) { userShowInfo(data); });
}

The field with automatic look-up of user name is ready. Now, the rest of the user information remains to be revealed:

function showUserInfo(data) {
    // name
    $("#wpuser_name").text(data.Name);
    // email
    $("#wpuser_email a").text(data.WorkEMail).attr('href', 'mailto:' + data.WorkEMail);
    // phone
    $("#wpuser_phone a").text(data.MobilePhone).attr('href', 'callto:' + data.MobilePhone);
    // departament
    $("#wpuser_departament").text(data.Department);
    // picture
    $("#wpuser_image img").attr('src', data.Picture.split(", ")[0]);
    // position
    $("#wpuser_position").text(data.Title);
    // ask me abolut list
    $("#wpuser_asklist").text(data.AskMeAbout);
}

The function will fill in the template with the data from the web service.

That’s it. As I promised, no server side was used in the process of programming. I have simplified the code to make it as short and as clear as possible. It is also worth mentioning that one should take into account the path to the site collection and to the sub-site with the web-part page. It is necessary to form the path to the web service with the same collection and the same sub-site.

I hope that the introduction to SharePoint Foundation REST Interface was pleasant, and now you will be able to use it correctly in your projects. Good luck!

The complete project can be downloaded from SVN.

Additional references:

As a Microsoft Gold Certified Partner, Infopulse offers a variety of SharePoint-based consulting services and solutions, such as portals and collaboration solutions, document management systems, dashboards and Business Intelligence reports, SharePoint branding, integration, migration, and customization, to name a few. Learn more >

Share this blog article:

Comments are closed.

Subscribe to our Newsletter