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

Advertisements

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

Visual Studio 2012 project templates for SharePoint 2013…!


With the new release of SharePoint 2013 Preview now seems like all SharePoint enthusiastic developers are spending a lot time on investigating the features and capabilities of new version. With the same interest I started to write some Apps for SharePoint 2013 but before start couldn’t find the correct templates in Visual Studio 2012 (RC). So this is how to enable those templates on VS 2012.

Navigate to Microsoft Office Apps web site (http://msdn.microsoft.com/en-US/office/apps/fp123627) and go to the Tools section and download the tools from there.

The direct link to download the tools pack is (http://go.microsoft.com/fwlink/?LinkID=257068)

After successful installation of the tool pack, you will see the new templates in VS 2012.

image

image

Happy Coding SharePoint 2013 Smile

How to deploy a Application Page to Central Administration…!


I had a requirement to create a settings page to configure few operations globally in SharePoint. So I was looking into creating a settings page in Central Administration. I have pointed out below the basic steps to do that.

Step 01:
Create an empty SharePoint project.

Step 02:
Add a mapped folder to Central Admin application pages.

image

image

Step 03:
Select the Admin mapped folder and add a new application page to the project.

Continue reading

Customize SharePoint Search Results Paging…!!!


Recently I had a requirement to customize the OOB SharePoint search results paging control (SearchPagingWebPart). So below is the problem definition and the solutions I came across. (the link to the downloadable source code for the solution is attached at the end of the post)

OOB paging control gives you several options to specify and define the paging behavior.

image

Most important properties for me are the first two ones.

1) Maximum page links before current
2) Maximum page links after current

So with the above configuration paging will look like this:

image

Its fare enough so the current page is 1 and there are no pages to be displayed as previous links. so it will display only 3 after links.

When you navigate to a page in the middle it will look like this:

image

So its now displaying 4 before links with page numbers and 3 after links.

Continue reading

SharePoint List Lookup Column…!


One of my friend came to me with a question on how to create a SharePoint List Lookup column. He had gone through several approaches (Programmatically and Declaratively) and he was asking for a recommended best practice way. I remembered a bit how I did that before but was not so sure the exact steps. Then I put my hands on and was trying to do a POC and had to spend some time on it. So thought its valuable to blog it so I will have a reference back for my self. Smile

Scenario for my POC was a typical one, Department and Employee Lists. So I want a lookup field inside the Employee list so I can pick Department from a lookup column.

Step 01: Create a list that will contain data for the lookup list. In my case it will be department list and below are the properties of it

List Name = “Departments”

List URL = “Lists/Departments”

Field name that I want to lookup = “Title” Continue reading

Populate cascading dropdown using JSON and jQuery…!


I got a requirement to populate two dropdowns with Country and Province/State data for a SharePoint 2007 project (data retrieved from SharePoint lists). So the first dropdown will contain the Country names. Second dropdown should populate details depending on the selected country on first dropdown. In my scenario, if the country is USA then populate the states from USA, and if its Canada, populate the provinces from Canada, if any other country keep the dropdown disabled.

I simple added two asp dropdown controls and bound data respectively of the first dropdown selected index change event. But the issue was for better user experience we had to avoid that post back.

Was reading about how to implement this and because of the reason, possible data for the province/state dropdown is small I went for a jQuery + JSON solution. I could have used a update panel and provided a Ajax solution. But with SharePoint 2007 integrating Ajax is a bit messy and also only because of dropdown data loading for it was a overhead doing that. Continue reading