Consume WCF REST Service using jQuery


In a previous post I explained how to create a simple WCF Service in SharePoint.

https://kamilmka.wordpress.com/2012/08/24/restful-wcf-service-in-sharepoint/

In this post I’m going to explain how to consume the RESTfull WCF service using jQuery Ajax calls and interpret the JSON result.

WCF Services hosted in SharePoint does not support cross domain access by default. So in this example I’m going to develop a SharePoint Visual web part to consume the rest service. If you have a cross domain supporting service you can create a standalone app or a control using the same jQuery Ajax methods explained below.

1) Crate a Empty SharePoint Project.

2) Add a Visual web part to the project.

3) Make the jQuery script reference to the web part.

4) Add the below code to the user control file and deploy the solution. Add the web part to a web page and you can see the results.

  1.     <script type=”text/javascript”>
  2.         function GetLocationData() {
  3.             $.ajax({
  4.                 url: “/_vti_bin/Kamil.POC.WCFService/Service.svc/GetAllLocations”,
  5.                 success: function (result) {
  6.                     console.log(‘success’);
  7.                     PopulateMapLocations(result);
  8.                 },
  9.                 error: function (msg) {
  10.                     console.log(‘error’);
  11.                     console.log(msg);
  12.                     locationResults = null;
  13.                 }
  14.             });
  15.         }
  16.         function PopulateMapLocations(locationData) {
  17.             $.each(locationData, function () {
  18.                 console.log($(this)[0]);
  19.                 $(‘#locationResultsPlaceHolder’).append($(this)[0].Title);
  20.                 $(‘#locationResultsPlaceHolder’).append(‘<br>’);
  21.                 $(‘#locationResultsPlaceHolder’).append($(this)[0].Address);
  22.                 $(‘#locationResultsPlaceHolder’).append(‘<br><br>’);
  23.             });
  24.         }
  25.         $(document).ready(function () {
  26.             GetLocationData();
  27.         });
  28.     </script>

This script has a function named GetLocationData that will be calling the RESTfull WCF service. So from above you can see how simple to call the jQuery Ajax function to call the service. Only must provide option is url and in my sample I have provided the REST url for the GetLocations method as defined in WCF service. If service call get succeeded then I’m calling the PopulateMapLocations method with passing the result data. The result data is a JSON value location value collection. So we can iterate through the collection and retrieve any attribute same as the way we defined in the WCF service.

image
(Result view in browser)

In several places you can see I have used console.log() function. This is a very user friendly effective way of debugging scripts. I used to use alerts in the middle of the script but its very unfriendly when you are iterating through a loop. But this console.log option will log the passed parameter or the object to the browser console. And if you are using Google Chrome you can expand the object and see the result as well. So something very useful when developing and testing.

image
(Screen cap on how the Chrome browser console looks as per this sample)

Will have another post on how to display these consumed data in a Bing Map. Until then Happy Coding! Smile

RESTful WCF Service in SharePoint


Recently I had to write a Custom WCF Service in SharePoint 2010 to expose some map locations related data. Whenever we think about web services or WCF services what first pops up into mind is to update web config files with different configurations to define end points and all. Usually it was difficult to get it work at once.

But you may be surprised when I say you no need even to have a web.config file when you write a WCF service that hosted or resides inside SharePoint Smile Sounds interesting right? So these are the basic steps you need to follow to get it working.

Code sample for this post can be found here.

1) Create an Empty SharePoint project.

image

2) Add following two assembly references to the project.
System.ServiceModel
System.ServiceModel.Web

image

3) Add a Mapped folder to ISAPI folder.

image

4) Create a sub folder inside the mapped ISAPI folder that will hold the WCF service (this is for the best practices so that your service can be easily identified after it get deployed).

5) Add a new text file to the newly created folder with the required service name. (Service.txt)

6) Change the text file extension to svc (Service.svc). After the steps 4, 5 and 6 it should be looking like this.

image

7) Add an interface file to the project. (IService.cs)

  1.     [ServiceContract]
  2.     interface IService
  3.     {
  4.         [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = “GetAllLocations”)]
  5.         [OperationContract]
  6.         List<MapLocation> GetAllLocations();
  7.     }

Decorate the Interface using the ServiceContract attribute. Then decorate the web method that you are exposing through the service with the OperationContract method level attribute. Additional WebGet attribute will be used to define what type of a response result you should be giving out from this service. It can be Json format or XML. UriTemplate portion define the how you are going to call this method externally. For example in the service call url if you append the GetAllLocations like “…service.svc/GetAllLocations” then this particular method will be called. You can give a friendly and more descriptive url there even the underlying method name is totally different.

In this example I’m returning a list of Location data with a custom entity collection.

8) Add a class file to the project to hold the implementation of the interface.

  1.     [AspNetCompatibilityRequirementsAttribute(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  2.     internal class Service : IService
  3.     {
  4.         public List<MapLocation> GetAllLocations()
  5.         {
  6.             return MapLocation.All.ToList();
  7.         }
  8.     }

You need to add the AspNetCompatibilityRequirementsAttribute and set the value as Required or Allowed. If not you wont be able to get the result from this method call. Even the method call will be successful the result will be an error text something similar as below.

“The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the service type with RequirementsMode setting as ‘Allowed’ or ‘Required’”

9) Definition of the MapLocation entity and the implementation of the All property is below. Add a separate class file and copy the below implementation to it.

  1.     public class MapLocation
  2.     {
  3.         public static IEnumerable<MapLocation> All
  4.         {
  5.             get
  6.             {
  7.                 List<MapLocation> allLocations = new List<MapLocation>();
  8.                 allLocations.Add(new MapLocation() { ID = 1, Title = “Home”, Address = “No 2 Badulla Road Bandarawela”, Latitude = 8.319533, Longitude = 79.978409 });
  9.                 allLocations.Add(new MapLocation() { ID = 2, Title = “Rented House”, Address = “Attidiya Dehiwala”, Latitude = 8.392224, Longitude = 80.930786 });
  10.                 allLocations.Add(new MapLocation() { ID = 3, Title = “Shop”, Address = “Badulla Road Bandarawela”, Latitude = 8.5, Longitude = 81.930786 });
  11.                 allLocations.Add(new MapLocation() { ID = 4, Title = “My Office”, Address = “M&M Centre Rajagiriya”, Latitude = 7.560078, Longitude = 79.872429 });
  12.                 return allLocations;
  13.             }
  14.         }
  15.         public int ID { get; set; }
  16.         public string Title { get; set; }
  17.         public string Address { get; set; }
  18.         public double Latitude { get; set; }
  19.         public double Longitude { get; set; }
  20.     }

10) Final step of coding is to update the Service.svc file. So open up the file and add the below code in to it.

  1. <%@ ServiceHost Language=”C#” Debug=”true” Service=”Kamil.POC.WCFService.Service, Kamil.POC.WCFService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b87ecdf1ed188035″ Factory=”Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %>

In the above code Service attribute will define the implementation of your service. So please make sure you update the correct namespace and the assembly information. Factory attribute will define what type of service you going to expose. Is it a RESTful service or a SOAP service ect.

All the types you can specify in Factory attribute can be found below.

SOAP service – MultipleBaseAddressBasicHttpBindingServiceHostFactory
Basic HTTP binding must be used, which creates endpoints for a service based on the basic HTTP binding.

REST Service – MultipleBaseAddressWebServiceHostFactory
The service factory creates endpoints with Web bindings.

ADO.NET Data Service – MultipleBaseAddressDataServiceHostFactory
A data service host factory can be used.
So we are done with the coding and simple you can deploy the newly created WCF service to SharePoint using the deploy option in Visual Studio.
To test the service navigate to the below url in your browser.

http://<ServerName>:[Port]/_vti_bin/Kamil.POC.WCFService/Service.svc/GetAllLocations

This will return you a Json response. If you have any Json formatter extensions installed on your browser it will give you a nice hierarchical view of the result data.

image

In the next post I will explain how to create a simple web part and retrieve this data using jQuery Ajax methods.

Happy Coding! Smile