Calling a WCF Service using jQuery in SharePoint (Anweshi Deverasetty)
This blog post explains how a WCF service can be called using jQuery in a SharePoint application. I won’t cover all of the implementation details. This post will highlight the relevant parts of configuring a WCF service to be accessible using jQuery in SharePoint.
[Update – 2/23/2011 – The original post contained some poor deployment practices and erroneous code. We apologize for the errors and want to give a big thank you to Wictor Wilen for pointing them out. The best practices for deployment and development using Visual Studio 2010 are available on his blog post . We are working to create a technical article that will show the best practices and Visual Studio 2010 tools.]
Creating a WCF Service
Let us start with the creation of Data Access Layer. This consists of the ProductsManager class and the associated methods.
Create a class library with the name DatabaseManager.
Add a class called ProductsManager.
Add function to ProductsManager called GetProducts. This will get the list of all Products from the database as given below. The code will look like the following:
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, we will create the WCF Service. This will serve the data to our page. Since this will be deployed to SharePoint, make sure the target framework is .NET Framework 3.5.
- Click on File, Add, New Project.
- In the Add New Project dialog, choose the WCF templates and choose the WCF Service Application template. Type the name SampleWCFService. Make sure you choose .NET Framework 3.5 in this dialog.
- When the project is created, add a reference to the previously created DatabaseManager class library.
- Rename the IService1.cs file to IProductsService.
- Rename the Service1.svc file to ProductsService.
- Add a strong name to this assembly.
Now, we will configure the Web.config entries as well as the attributes for the services.
Add a reference to Microsoft.SharePoint.Client.ServerRuntime.dll. If you don’t see this in the Add a Reference dialog, you will have to manually add it from the Windows\Assembly\GAC_MSIL\ directory. More information can be found on Microsoft Support.
Open ProductsService.cs using the View Markup option. Insert the following declaration. (Important: This has been broken into two lines for readability. Make sure this declaration is on one line in your file.)
<%@ 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"%>
Add the following two using statements to the ProductService.cs file.
using Microsoft.SharePoint.Client.Services; using System.ServiceModel.Activation;
Add the following attributes to the class declaration in the ProductService.cs file.
[BasicHttpBindingServiceMetadataExchangeEndpoint] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
Add the following method to ProductService.cs.
/// <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(); }
Add a new contract for GetProducts in the IProductsService.cs file.
[OperationContract] [WebGet(UriTemplate = "/GetProducts", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] List<Products> GetProducts();
Deploying WCF Service in SharePoint environment
[Update – 2/23/2011 - Our original post contained manual instructions for copying files to the front-end, and this is not a best practice. Deployment should be handled using the tools provided in Visual Studio 2010 or through the use of a redistributable solution package. Wictor Wilen covers this topic on his blog post . Please refer to his post for help with deploying the files using Visual Studio 2010.]
Testing WCF Service
In order to check whether the Service is up, navigate to https://siteurl/_layouts/ProductService.svc from your browser. You will see a message “No End Point” on the screen. Now, let’s try to access the method GetProducts by navigating to https://siteurl/_layouts/ProductService.svc/GetProducts from the browser again. It pops up the resultant file.
Accessing WCF Service using jQuery from a SharePoint site
Now, it’s 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.
Create a function object called Product to hold each product details.
function Product(ProductName, ProductDesc, Price, Quantity) { this.ProductName = ProductName; this.ProductDesc = ProductDesc; this.Price = Price; this.Quantity = Quantity; }
Call the WCF service using an AJAX call.
function CallWCFService(WCFServiceURL) { $.ajax({ type: "GET", url: WCFServiceURL, contentType: "application/json; charset=utf-8", dataType: 'json', processdata: true, success: function (msg) { WCFServiceSucceeded(msg); }, error: WCFServiceFailed }); }
Implement the successful call handler to populate the result set into a 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 by adding the following declaration to the page. Make sure you have included references to the jQuery files as well.
<script src="/Style Library/callwcfservice.js" type="text/javascript"></script>
Comments
- Anonymous
December 02, 2012
Better read here: www.wictorwilen.se/.../Calling-a-WCF-Service-using-jQuery-in-SharePoint-the-correct-way.aspx