Go to [region
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 processing ing 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 youWictor wilenFor pointing them out. The best practices for deployment and development using Visual Studio 2010 are available onHis 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 nameDatabasemanager.
-
- Add a class calledProductsmanager.
- Add function 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 nameSamplewcfservice. Make sure you choose. NET Framework 3.5 in this dialog.
- When the project is created, add a reference to the previusly 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.
UsingMicrosoft. Sharepoint. Client. Services;UsingSystem. 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.
/// /// gets the list of products /// ///
returns the list of products Public List
getproducts () {productsmanager =
New productsmanager ();
return productsmanager. getproducts () ;}
- Add a new contract for getproducts inIproductsservice. CSFile.
[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 shoshould be handled using the tools provided in Visual Studio 2010 or through the use of a redistributable solution package. wictor wilen covers this topic onHis 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 http: // 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 http: // 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 >