Calling WCF Service Using ScriptManager

In this article we will learn how to call a WCF service using the ScriptManager. There is often a need to call a web service using Ajax but it's very time consuming and requires a lot of something to script and to write so to avoid this we can also call a WCF service using the ScriptManager. So let us learn how to do the call step-by-step so beginners also can understand.
Requirements to understand this tutorial
If you are a beginner and you need to understand what a web service is, to learn about it refer to the following article of mine:
I hope you read it if you are unfamiliar with WCF services, so I will briefly define what a WCF service and ScriptManager are.
Windows Communication Foundation (WCF)
WCF is a library for applications of various platforms or the same platform to communicate over the various protocols such as TCP, HTTP, HTTPS and so on.
ScriptManager
When we use any Ajax control then there is a requirement to use the ScriptManager to handle the scripting on the client side; without the ScriptManager Ajax controls are not run but also ScriptManager is used to call a web service, to handle errors and so on. So let us demonstrate this concept with a web application.

Step 1
Create a WCF Service as in the following:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "ASP.NET Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as "CallingWCFServiceUsingScriptManager" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item". You will see the WCF service template then click on "Add".
Step 2
Add a web page to the new web application as in the following:
  1. Right-click on Solution Explorer - "Add New Item" - you see the Web Form  template then click on Add 
  2. Now drag and drop one ScriptManager, two text Boxes and one button on the Default.aspx Page. Then the source code of the Default.aspx page will look as follows: 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>    
    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title></title>    
        
</head>    
<body bgcolor="black">    
    <form id="form1" runat="server">    
     
    
    <br />    
    <h2 style="color: #808000; font-size: medium; font-weight: bolder;">    
        Article by vithal wadje</h2>    
    <br />    
    <br />    
    <br />    
    <table style="width: 73%; color: White;">    
        <tr>    
            <td>    
                Enter First Number    
            </td>    
            <td>    
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    
            </td>    
        </tr>    
        <tr>    
            <td>    
                Enter Second Number    
            </td>    
            <td>    
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>    
            </td>    
        </tr>    
        <tr>    
            <td>    
            </td>    
            <td>    
            </td>    
        </tr>    
        <tfoot>    
            <tr>    
                <td>    
                </td>    
                <td colspan="3">    
                    <input id="Savebtn" type="button" value="Calculate" onclick="GetDetails();" />    
                </td>    
            </tr>    
        </tfoot>    
    </table>    
    </form>    
</body>    
</html> 
Now  the Solution Explorer will look such as follows:
 
In the preceding Solution Explorer you have seen that a Service.svc file is added and out of that there is a Default.aspx page from which we will call the WCF service using the Script Manager and another is a .svc file that is a our WCF service.
Step 3
Create a method in the Service.svc file as in the following:
    public class Service  
       {  
          [OperationContract]  
           public int GetAddition(int a, int b)  
           {  
               //returning sum of given input numbers    
               return a + b;  
           }    
            
       } 
 Step 4
To allow calling a WCF service from JavaScript, jQuery or ScriptManager, we need to add the following line at the top of the class name. We also need to specify the namespace. The namespace may be any name that is used to uniquely identify the Service as in the following:
     [ServiceContract(Namespace = "AdditionService")]
     [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
After adding the preceding line, the Service class will look as follows:
[ServiceContract(Namespace = "AdditionService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service  
    {  
       [OperationContract]  
        public int GetAddition(int a, int b)  
        {  
            //returning sum of given input numbers    
            return a + b;  
        }    
         
    }  
Note: the namespace name in ServiceContract attribute that is used to call service from the script must be provided.
In the code above, I have Implemented one method named GetAddition that takes the two integer type parameters that are a,b and returns the sum of the two integer variables. 
 Step 5
Let us see the UI of the .aspx page:
 
In the preceding UI you saw that there are two textboxes that accept the two numbers and there is the calculate HTML button that calls the JavaScript function to call the web service using the script manager.
 
Step 6
Refer to the Service Path using the Script Manager as in the following
<asp:ScriptManager ID="ScriptManager1" runat="server">    
      <Services>    
          <asp:ServiceReference Path="~/Service.svc" />    
      </Services>    
  </asp:ScriptManager>
In the preceding source code, is a Services tag under the Script Manager control that allows setting of the WCF service reference. After adding the service reference the Web.config will look as follows:
    <system.serviceModel>  
        <behaviors>  
            <endpointBehaviors>  
                <behavior name="CallingWCFUsingScriptManager.Service1AspNetAjaxBehavior">  
                    <enableWebScript />  
                </behavior>  
            </endpointBehaviors>  
        </behaviors>  
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"  
            multipleSiteBindingsEnabled="true" />  
        <services>  
            <service name="CallingWCFUsingScriptManager.Service">  
                <endpoint address="" behaviorConfiguration="CallingWCFUsingScriptManager.Service1AspNetAjaxBehavior"  
                    binding="webHttpBinding" contract="CallingWCFUsingScriptManager.Service" />  
            </service>  
        </services>  
    </system.serviceModel> 
Step 7
Create a JavaScript function to call the service method as in the following:
 function GetDetails()   
       {  
           //reads the values to textboxes    
           var a = document.getElementById('TextBox1').value;  
           var b = document.getElementById('TextBox2').value;  
  
           //pass the value to  method    
          //Namespace + class Name + Method Name
         AdditionService.Service.GetAddition(a, b, SuccessCallback, OnfailureCallback);
  
       }    
In the code above, I have read the values of two textboxes and stored them in the a and b variables and then I am passing those variables to the WCF service method that takes the four parameters that are input parameters, SuccessCallback, OnfailureCallback and usercontext. I will briefly explain what they are.
  • OnSucess: returns the results after successfully executing the WCF services method, this parameter is optional.
  • Onfailed: If the WCF service method fails to execute then it returns the error details, it accepts the error object as a  parameter, this parameter is optional.
  • usercontext: This is used to provide some additional information, this parameter is optional.
I hope you understand about the parameter details, now similarly we will create methods for OnSucess and onfailed as.
OnSuccess 
    //returns output from service     
           function SuccessCallback(AddResult)   
           {  
               //displaying output on alertbox     
               alert(AddResult);  
      
      
           } 
 onfailed
    //returns the error after WCF  service failed to execute     
           function OnfailureCallback(error)   
           {  
               //displaying error on alert box    
               alert(error);  
      
           }   
Now after adding the preceding three functions under the <Head> tag of the default.aspx page the function will look as follows
<script type="text/javascript">  
  
      function GetDetails()   
      {  
          //reads the values to textboxes    
          var a = document.getElementById('TextBox1').value;  
          var b = document.getElementById('TextBox2').value;  
  
          //pass the value to  method    
           //Namespace + class Name + Method Name          AdditionService.Service.GetAddition(a, b, SuccessCallback, OnfailureCallback); 
  
      }  
      //returns output from service     
      function SuccessCallback(AddResult)   
      {  
          //displaying output on alertbox     
          alert(AddResult);  
  
  
      }  
      //returns the error after WCF  service failed to execute     
      function OnfailureCallback(error)   
      {  
          //displaying error on alert box    
          alert(error);  
  
      }    
  </script>
 Step 8
Now call the GetDetails() function on the Calculate HTML input button click. That calls the WCF service method without post back as in the following:
<input id="Savebtn" type="button" value="Calculate" onclick="GetDetails();" />  
Now click F5 to run the application. Enter some number into the two textboxes and click on the calculate button, it will show the following output:
 
 
In the preceding image the output is returned from the WCF service as 24. Now it's clear that we can also call the WCF service using the Script manager and we will avoid the time of writing JSON code to call the service.
Summary
From all the examples above we have seen how to call a WCF service using the script manager and how to reduce the code required to call a service using JSON. I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode