Calling a WCF Service using jquery in SharePoint (anweshi deverasetty)

Source: Internet
Author: User

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.

  1. Create a class library with the nameDatabasemanager.
  2. Add a class calledProductsmanager.
  3. 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 ;}}
  4. 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.

    1. Click on file, add, new project.
    2. 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.
    3. When the project is created, add a reference to the previusly created databasemanager class library.
    4. Rename the iservice1.cs file to iproductsservice.
    5. Rename the service1.svc file to productsservice.
    6. Add a strong name to this Assembly.

Now, we will configure the Web. config entries as well as the attributes for the services.

  1. 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.
  2. 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 " %>
  3. Add the following two using statements to the productservice. CS file.
    UsingMicrosoft. Sharepoint. Client. Services;UsingSystem. servicemodel. activation;
  4. Add the following attributes to the class declaration in the productservice. CS file.
    [Basichttpbindingservicemetadataexchangeendpoint] [Aspnetcompatibilityrequirements(Requirementsmode =Aspnetcompatibilityrequirementsmode. Allowed)]
  5. 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 () ;}
        
  6. 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.

  1. 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 ;}
  2. 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}) ;}
  3. 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)}) ;}
  4. 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  > 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.