Calling WCF Service using JQuery in Sharepoint Applications

Introduction

This article explains about how a WCF Service can be called using JQuery in a Sharepoint Application. 

Creating a WCF Service

Deploying WCF Service in Sharepoint environment

Testing WCF Service

Accessing WCF Service using JQuery from a Sharepoint page

Contents of JS File

Creating a WCF Service

Let us start with the creation of Data Access Layer. Create a class library with name “DatabaseManager” with a class “ProductsManager”. The ProductsManager class has a function “GetProducts” which gets the list of all Products from the database as given below.

/// <summary> 
/// Gets all the Products from the Database
/// </summary>
/// <returns>Returns List of Products</returns>

public List<Products> GetProducts()
{

List<Products> productsList = new List<Products>();

Database DatabaseInstance = DatabaseFactory.CreateDatabase(ConnectionStringkey);  
DbCommand DatabaseCommand;

using (DatabaseCommand = DatabaseInstance.GetStoredProcCommand(SP_GetProducts))  
{                 
    using (IDataReader reader = DatabaseInstance.ExecuteReader(DatabaseCommand))  
    { 
               while (reader.Read()) 
               { 
                    Products products = new Products(); 
                    products.ProductName = reader[“ProductName”].ToString(); 
                    products.ProductDesc = reader[“ProductDesc”].ToString(); 
                    products.Price = reader[“Price”].ToString(); 
                    products.Quantity = reader[“Quantity”].ToString(); 
                    productsList.Add(products); 
                } 
            } 
          return productsList; 
       } 
   }

Add a strong name to this assembly.

Now, create a WCF Service with name “SampleWCFService” and add a reference to “DatabaseManager”. As we are going to deploy this Service in sharepoint 2010 application, change the target .Netframework to 3.5. Now rename the IService1 file to IProductsService and Service1 to ProductsService. Make sure it’s updated in all the places. Add a strong name to this assembly.

Follow the below steps to implement WCF Service

1. Add a reference to Microsoft.SharePoint.Client.ServerRuntime.dll and open ProductsService.cs using “View Map” option to add the Factory Attribute as given below. This will reduce the Web.config entries for configuring the WCF Service.

<%@ ServiceHost Language=”C#” Debug=”true” Service=”SampleWCFService.ProductService” CodeBehind=”ProductService.svc.cs” Factory=”Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”%>

2. Add the following highlighted attribute with a new method GetProducts in ProductsService.cs file

[BasicHttpBindingServiceMetadataExchangeEndpoint] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public class ProductService : IProductService 
{

       /// <summary>
       /// Gets the list of Products
       /// </summary>
       /// <returns>Returns the List of Products</returns>
       public List<Products> GetProducts()
       {
           ProductsManager productsManager = new ProductsManager();
           return productsManager.GetProducts();
       }

}

3. Add a new Contract GetProducts in IProductService.cs

[OperationContract] 
[WebGet(UriTemplate = “/GetProducts”, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] 
List<Products> GetProducts();

Deploying WCF Service in Sharepoint environment

Follow the blow steps to deploy the WCF Service

1. Deploy DatabaseManager and SampleWCFService dlls into GAC

2. Copy the SampleWCFService dll into the Virtual directory bin folder

3. Copy the ProductService.svc into Layouts folder.

Testing WCF Service

In order to check whether the Service is up, navigate to ProductService.SVC file ie., http://siteurl/_layouts/ProductService.svc from browser. You will see a message “No End Point” on the screen. Now let’s try to access the method GetProducts ie., http://siteurl/_layouts/ProductService.svc/GetProducts from the browser again. It pops up the resultant file. Following is what you see set in the file.

[{“Price”:”100″,”ProductDesc”:”This is product1″,”ProductName”:”Product1″,”Quantity”:”10″},

{“Price”:”200″,”ProductDesc”:”This is product2″,”ProductName”:”Product2″,”Quantity”:”5″},

{“Price”:”250″,”ProductDesc”:”This is product3″,”ProductName”:”Product3″,”Quantity”:”6″}]

Accessing WCF Service using JQuery from a Sharepoint site

Now, its time to access this WCF Service using JQuery.

Create a JS file with name “CallWCFService.Js” and use the following snippets to call the service.

1. Create a function object Product to hold each Product details.

//Function object for Product

function Product(ProductName,ProductDesc,Price,Quantity)

{

this.ProductName=ProductName;

this.ProductDesc=ProductDesc;

this.Price=Price;

this.Quantity=Quantity;

}

2. Call the WCF Service using an AJAX Call

function CallWCFService(WCFServiceURL) {

$.ajax({

type: “GET”,

url: WCFServiceURL,

contentType: “application/json; charset=utf-8”,

dataType: ‘{}’,

processdata: true,

success: function (msg) {

WCFServiceSucceeded(msg);

},

error: WCFServiceFailed

});

2. On successful call use the below code to populate the result set in to Products Array object

//On Successful WCF Service call

function WCFServiceSucceeded(result) {

var productsArray = new Array();

//Gets the Products

$.each(result, function (i, Product) {

productsArray[i]=Product;

});

//Print all the product details

$.each(productsArray,function(i,Product)

{

alert(Product.ProductName + ‘ ‘ + Product.ProductDesc + ‘ ‘ + Product.Price + ‘ ‘ + Product.Quantity)

});

}

Now, include this JS file into your sharepoint page as given below. Make sure you have included the JQuery.binray file.

<script src=”/Style Library/callwcfservice.js” type=”text/javascript”></script>

This is the way how a WCF Service can be called using JQuery from any Sharepoint page.

Contents of JS File

Please find the enclosed JS file for your reference.

CallWCFService.zip