Wednesday 21 November 2012

Creating a WCF web service and calling JSON objects from JQUERY – SharePoint 2010 C#

WCF or ASMX?

First off, why create a WCF web service in SharePoint instead of the old ASMX web service? Did some reading on this and would recommend these blog posts on the subject:
http://dotnetarchitecthouston.com/post/WCF-versus-ASMX-services.aspx
http://www.bishoylabib.com/2009/08/comparing-asmx-and-wcf.html

Creating a WCF web service in Visual Studio 2010

1. Start off by creating a new SharePoint project in visual studio

2. Call it WCFService (or name of your choice)
3. Create a new “Mapped folder” by right clicking on the project and select “Add”
4. Point to the ISAPI folder (Usually: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI)
5. Create a folder called WCFService (or name of your choice)
6. Create a folder called “WCFObjects” (or name of your choice)
7. Add a class called “Staff” in the newly created folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WCFService
{
public class Staff
{
public string name { get; set; }
public string country { get; set; }
}
}


8. Create an Interface class called “IService.cs” with following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;


namespace WCFService
{
[ServiceContract(Namespace = "WCFService.Service")]
public interface IService
{
[WebInvoke(UriTemplate = "/returnStaff", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
List<Staff> returnStaff(string staffName, string staffCountry);
}
}

9. Now we need to create the /returnStaff method defined in the interface
10. Create a class called “Service.cs” with following code in it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
namespace WCFService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service:IService
{
public List returnStaff(string staffName, string staffCountry)
{
//create staff list
List staffList = new List();
Staff staff = new Staff();
staff.name = staffName;
staff.country = staffCountry;
//add staff to list
staffList.Add(staff);
//return list
return staffList;
}
}
}

11. Now that we have the logic for the web service, the actual Service.svc can be created
12. Add a “Service.svc” file in the ISAPI\WCFService folder with following code in it:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$"%>
<%@ServiceHost Debug="true" Language="C#" CodeBehind="Service.cs" Service="WCFService.Service, WCFService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=KEY TOKEN"
Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


13. Put your token id from the assembly instead of “KEY TOKEN”
14. Your solution should now look like this:

15. Deploy your solution
16. Try to go to “http://yourservername/_vti_bin/WCFService/Service.svc to check if your service is working
17. You will get “Endpoint not found” as a return message from your service

Calling web service from client side JQUERY (ASPX) in a Web Part

1. Create a new SharePoint project called “WebParts”
2.  Create a new visual web part called “StaffViewer” (http://weblogs.asp.net/sreejukg/archive/2011/03/26/create-a-visual-web-part-using-visual-studio-2010.aspx)
3. Add following code to the StaffViewerUserControl.ascx to create input boxes and tables to view data:
<table id="tblInput">
<tr>
<td>
Name:
</td>
<td>
<input type="text" id="name" />
</td>
</tr>
<tr>
<td>
Country:
</td>
<td>
<input type="text" id="country" />
</td>
<td>
<button id="btnCallService" type="button" onclick="getStaff()">
Call web service</button>
</td>
</tr>
</table>
<table id="tblStaff">
</table>

4. Add a JQUERY function called “getStaff” which calls the WCF web service

function getStaff() {
//input parameters
var name = $('#name').val();
var country = $('#country').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
//url to web service
url: "/_vti_bin/WCFService/Service.svc/returnStaff",
//input parameters (JSON)
data: JSON.stringify({ staffName: name, staffCountry: country }),
success: function (data) {
var staff = data;
//iterate through data
$.each(staff, function (index, person) {
//view data
$('#tblStaff').append('
Name: ' + person.name + '| Country: ' + person.country + '
');
});
}
});
};

5. Note the  ”JSON.stringify({ staffName: name, staffCountry: country })” which passes through parameters as in JSON format
6. Add a .click event to the button

$(function () {
$("btnCallService").click(function () {
getStaff();
});
});

7. Your solution should now look like this:

8. Deploy the solution
9. Activate the “Web Part” feature
10. Add the Web Part to your page

11. Type a name and country, then click “Call web service”
12. The service is now called, JSON array returned to user control and the result is displayed on the page