Difference Between Web API and WCF REST Services

There are lots of talk on Web API and WCF REST regrading which one to use for REST Services . Many people are recommending Web API for REST service and they are saying stickily use Web API instead of WCF REST but personally I am not agree with it .The reasons are follows
  • We should not be stick on any particular technology i.e Web API or REST , It must  be decided  according to project requirement whether the Web API  or WCF REST is fit for  project requirement.
  • There are lots of technologies in market but first we need to analyze project scope and requirement and according to it we need to decide technology.
 Lets see the difference between the Web API and WCF REST services based on the features
Scenario or Requirement
Web API
WCF REST
Need support of MSMQ.
No
Yes
Need duplex communication
No
Yes
Need End to end message security
No
Yes
Need Distributed transaction.
No
Yes
One way messaging.
No
Yes
Need to handle Long pooling requests
No
Yes
Need support of REST service in existing WCF Service
No
Yes
Need same code to be supported on both SOAP and REST
No
Yes
Need REST in ASP.NET MVC
Yes preferred
Yes
Need only HTTP service
Yes
Yes but not recommended
Open source
Yes
No

The above is the some differences according to the our project scenario and requirement.
Note 
 Learn WCF and REST Service on compilemode.com
Summary 
I hope this article is useful for all readers , If you have any suggestion regarding this article then please contact me.

Creating WCF REST Service Step by Step

In this video tutorial we will learn how to create WCF REST,tutorial prepared focusing on beginners to make them understand about the WCF REST Service.So we will learn it as step by step
In this video tutorial we will learn
  • Create WCF Project.
  • Adding Service and operation contract.
  • what is WCF REST Service. 
  • Understanding WCF REST Template .
  • What is WebInvoke and WebGet .
  • What URI Template
  • Request and Response message format.
  • Configuring End Points .
 Before start
 You will need  a basic understanding of WCF service, please read my following articles .
 I hope you have refereed it, If you wants to learn even more then please refer WCF Section
Watch Video 


Don't Forget To  

Summary
I hope this video tutorial is useful for all readers. If you have any suggestion then please contact me.

CRUD Operations In WCF REST with JSON Data

 Sometime we need to work with Json data in WCF REST services to make data available on across different platforms .so let us learn in this article how to make CRUD  operations in WCF REST service and communicate using Json data .To Perform CRUD operations in WCF REST service we need to use following HTTP methods 
  • GET : Get the resource (Records) from particular source such as SQL database.
  • POST : Used to insert the records into the particular source such as SQL, Oracle database.
  • PUT : Used to modify the resource or records.
  • DELETE : used Delete the specific resource or record from particular source.
To work with specific message format in WCF REST service,we need to set Web Message Format to Json or XML in REST template .Now let's implement above methods to make CRUD operations in WCF REST Service Step by step .

Prerequisites
To understand WCF REST service, you need to at-least beginner knowledge on WCF ,if you are beginner in WCF then please refer my following articles of WCF.
  1. Introduction to WCF Services
  2. Introduction To WCF Endpoints 
  3. Creating WCF Service
I hope you have read above articles .
Step 1: Create WCF Service as.
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2015".
  2. "File" - "New Project" - "C#" - WCF Service Application as shown in below.

3 .Provide the project name such as "PayMentRESTService " or another as you wish and specify the  location.

4. Now delete the auto created Interface and svc file which we will create new one so beginners can understand it.


5. Now Add New WCF Service file and give name PayMentRESTService are as:
I hope you have followed the same steps and and learned how to add WCF Service. After adding Service file then the project solution explorer will be look like as follows


Step 2: Configure REST Service Template.

Now open the the IPaymentService.cs Interface file and write the following code for CRUD operation:
using System.ServiceModel;
using System.ServiceModel.Web;

namespace PayMentRESTService
{

    [ServiceContract]
    public interface IPayMentService
    {
        //To Insert or POST Records
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/AddPayee/{Name}/{City}", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        void AddPayee(string Name, string City);

        //To Get Records from database 
        [OperationContract]
        [WebInvoke(Method = "GET",UriTemplate = "/PayBill/{PayId}", BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
        string PayBill(string PayId);

        //To Update records
        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "/UpdateBillPayment/{PayId}/{TransId}", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        void UpdateBillPayment(string PayId,string TransId);

        //To delete records
        [OperationContract]
        [WebInvoke(Method = "DELETE", UriTemplate = "/RemovePayee/{Id}", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        void RemovePayee(string Id);

    }
}

Let's understand code including REST Template.
  • IPayMentService : REST Service interface name
  • Method  : HTTP methods types it can be GET,POST,PUT,DELETE and other
  • UriTemplate : To Define url structure that how can be serice method accessed at client.
  • BodyStyle : Allows to define message body style format such as Bare, Wrapped etc.
  • RequestFormat : Defines in which message format does request come from client such xml or json.
  • ResponseFormat : Defines what  message format does service return to the client as a part of response such xml or json.
I hope you have got some idea about REST Template ..
Step 3: Implement IPaymentService.cs interface methods into PaymentService.svc.cs file as.

public class PayMentService : IPayMentService
    {
        public void AddPayee(string Name, string City)
        {
           //write database related insert logic here.
        }
        public string PayBill(string PayId)
        {
            return "Transaction having PayId " + PayId + " is successful";
            //write database related data retrival logic here.
        }

        public void RemovePayee(string Id)
        {
            //write database related delete logic here.
        }

        public void UpdateBillPayment(string PayId, string TransId)
        {
            //write database related update logic here.
        }
    }
Now our REST Service Code is ready for CRUD operation with JSON Data ,let's  complete another few steps.
Step 4: Configure End Points and Service Behaviors in web.config file as:

End Points and Service Behaviors configuration is very important in WCF Service ,many people saying it much complicated to configure but trust me its much easier and simple with powerful intellisense. Lets open web.config file and find system.serviceModel tag and follow below steps

Configure service behaviors as:


Configure End points as:


While configuring Endpoints Tag automatically shows how to set and what contract because it shows list of contract files (Interfaces) i.e. service contract .I hope you got basic idea about the End points configuration . Soon I will post video on this. After configuring Endpoints and service behaviors the system.serviceModel tag section of web.config file will be look like as follows:
<system.serviceModel>
    <behaviors>
      <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>
    <services>
      <service name="PayMentRESTService.PayMentService" behaviorConfiguration="ServiceBehavior">

        <endpoint binding="webHttpBinding" contract="PayMentRESTService.IPayMentService" behaviorConfiguration="web">


        </endpoint>
      </service>

    </services>

    <serviceHostingEnvironment  multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

I hope you have done same configuration which i have done .

Step 5: Test REST Service.
Now our service is ready .lets test it using REST client of browser extension are as
POST ( To insert records)
REST Service URL will be

http://localhost:64858/PayMentService.svc/AddPayee/vithal Wadje/Latur


In the above url last two parameters are input parameters .now test with REST client as

Using GET


Using PUT


Using DELETE

Hope from preceding examples we have learned how to Implement CRUD operations in WCF REST  Service .
Note:
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • CRUD Stands for create,Read,update and delete
Summary
I hope this article is useful for all readers. If you have any suggestion then please contact me.




WCF REST Service with JSON Data

Many times there is need to get the output in different message format such as XML,JSON or custom message format to fulfill the software requirement. So in this article we will learn how create WCF REST Service which return JSON format output .

Prerequisites
To understand WCF REST service, you need to at-least beginner knowledge on WCF ,if you are beginner in WCF then please refer my following articles of WCF.
  1. Introduction to WCF Services
  2. Introduction To WCF Endpoints 
  3. Creating WCF Service
I hope you have read above articles , now let us start with WCF REST from definition

 What is WCF REST ?
REST stands for Representational state transfer which is technique to communicate on cross platform application and exchange the data in JSON or XML format with the help of GET,POST,PUT,DELETE methods of HTTP protocol.

To return JOSN  as output we need to set RequestFormat of WebMessageFormat to JSON in REST template which we will learn in next.

let us briefly understand about the HTTP methods which is most commonly used to create WCF REST service as:
  • GET : Get the resource (Records) from particular source such as SQL database.
  • POST : Used to insert the records into the particular source such as SQL, Oracle database.
  • PUT : Used to modify the resource or records.
  • DELETE : used Delete the specific resource or record from particular source.
I hope you understand basic about REST concept , Now let us start step by step to create WCF REST JSON Service.

Step 1: Create WCF Service.

To know how to create WCF service in depth please refer my article Creating WCF Service . So In this let see simple way to create WCF service:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2015".
  2. "File" - "New Project" - "C#" - WCF Service Application as shown in below.

 3 .Provide the project name such as "PayMentRESTService " or another as you wish and specify the  location.

4. Now delete the auto created Interface and svc file which we will create new one so beginners can understand it.

5. Now Add New WCF Service file and give name PayMentRESTService are as:
I hope you have followed the same steps and and learned how to add WCF Service. After adding Service file then the project solution explorer will be look like as follows


Step 2: Configure REST Service Template.

Now open the the IPaymentService.cs Interface file and write the following code:

using System.ServiceModel;
using System.ServiceModel.Web;

namespace PayMentRESTService
{

    [ServiceContract]
    public interface IPayMentService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",UriTemplate = "/PayBill/{PayId}", BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
        string PayBill(string PayId);
       
    }
}
Let us understand above REST Template using following diagram

I hope you have understood the basic REST Template from above image.In the above example we set WebMessageFormat is JSON , So it will return the JSON format output.

Step 3: Implement IPaymentService.cs interface methods into PaymentService.svc.cs file as.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace PayMentRESTService
{
    
    public class PayMentService : IPayMentService
    {
        public string PayBill(string PayId)
        {
            return "Transaction having PayId " + PayId + " was successful";
        }
    }
}

Now our REST Service Code is ready ,lest us complete another more steps.
 
Step 4: Configure End Points and Service Behaviors in web.config file as:

End Points and Service Behaviors configuration is very important in WCF Service ,many people saying it much complicated to configure but trust me its much easier and simple with powerful intellisense. Lets open web.config file and find system.serviceModel tag and follow below steps

Configure service behaviors as:


Configure End points as:


 
While configuring Endpoints Tag automatically shows how to set and what contract because it shows list of contract files (Interfaces) i.e. service contract .I hope you got basic idea about the End points configuration . Soon I will post video on this. After configuring Endpoints and service behaviors the system.serviceModel tag section of web.config file will be look like as follows:

<system.serviceModel>
    <behaviors>
      <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>
    <services>
      <service name="PayMentRESTService.PayMentService" behaviorConfiguration="ServiceBehavior">

        <endpoint binding="webHttpBinding" contract="PayMentRESTService.IPayMentService" behaviorConfiguration="web">


        </endpoint>
      </service>

    </services>

    <serviceHostingEnvironment  multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
I hope you have done same configuration which i have done .

Step 5: Test REST Service.

Now our service is ready .lets test it using REST client of Mozilla browser are as

Our REST Service URL will be http://localhost:64858/PayMentService.svc/PayBill/100

In the above Response of WCF REST service you have seen that status code is 200 OK. It means our service executed successfully .lets confirm by switching to Response Body tab of REST client as

From preceding output its clear that out service executed successfully and as per configuration its returned JSON output .Hope from preceding examples we have learned how to create WCF REST Service.
Note:
  • Configure the database connection in the web.config file depending on your database server location.
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary

I hope this article is useful for all readers. If you have any suggestion then please contact me.




How To Create WCF REST Service

I have read many forum post regarding WCF REST service creation and implantation but its much difficult to understand to beginners so to make it understandable, decided to write this article which shows step by step how create WCF REST Service.

Prerequisites
To understand WCF REST service, you need to at-least beginner knowledge on WCF ,if you are beginner in WCF then please refer my following articles of WCF.
  1. Introduction to WCF Services
  2. Introduction To WCF Endpoints 
  3. Creating WCF Service
I hope you have read above articles , now let us start with WCF REST from definition

What is WCF REST?

REST stands for Representational state transfer which is technique to communicate on cross platform application and exchange the data in JSON or XML format with the help of GET,POST,PUT,DELETE methods of HTTP protocol.

let us briefly understand about the HTTP methods which is most commonly used to create WCF REST service as:
  • GET : Get the resource (Records) from particular source such as SQL database.
  • POST : Used to insert the records into the particular source such as SQL, Oracle database.
  • PUT : Used to modify the resource or records.
  • DELETE : used Delete the specific resource or record from particular source.
I hope you understand basic about REST concept , Now let us start step by step to create WCF REST Service.

Step 1: Create WCF Service.

To know how to create WCF service in depth please refer my article Creating WCF Service . So In this let see simple way to create WCF service:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2015".
  2. "File" - "New Project" - "C#" - WCF Service Application as shown in below.

3 .Provide the project name such as "PayMentRESTService " or another as you wish and specify the  location.

4. Now delete the auto created Interface and svc file which we will create new one so beginners can understand it.


5. Now Add New WCF Service file and give name PayMentRESTService are as:

I hope you have followed the same steps and and learned how to add WCF Service. After adding Service file then the project solution explorer will be look like as follows


Step 2: Configure REST Service Template.

Now open the the IPaymentService.cs Interface file and write the following code:

using System.ServiceModel;
using System.ServiceModel.Web;

namespace PayMentRESTService
{

    [ServiceContract]
    public interface IPayMentService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",UriTemplate = "/PayBill/{PayId}", BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
        string PayBill(string PayId);
       
    }
}
Let us understand above REST Template using following diagram

I hope you have understood the basic REST Template from above image.

Step 3: Implement IPaymentService.cs interface methods into PaymentService.svc.cs file as.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace PayMentRESTService
{
    
    public class PayMentService : IPayMentService
    {
        public string PayBill(string PayId)
        {
            return "Transaction having PayId " + PayId + " was successful";
        }
    }
}

Now our REST Service Code is ready ,lest us complete another more steps.
 
Step 4: Configure End Points and Service Behaviors in web.config file as:

End Points and Service Behaviors configuration is very important in WCF Service ,many people saying it much complicated to configure but trust me its much easier and simple with powerful intellisense. Lets open web.config file and find system.serviceModel tag and follow below steps

Configure service behaviors as:


Configure End points as:


 
While configuring Endpoints Tag automatically shows how to set and what contract because it shows list of contract files (Interfaces) i.e. service contract .I hope you got basic idea about the End points configuration . Soon I will post video on this. After configuring Endpoints and service behaviors the system.serviceModel tag section of web.config file will be look like as follows:

<system.serviceModel>
    <behaviors>
      <serviceBehaviors >
        <behavior name="ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>
    <services>
      <service name="PayMentRESTService.PayMentService" behaviorConfiguration="ServiceBehavior">

        <endpoint binding="webHttpBinding" contract="PayMentRESTService.IPayMentService" behaviorConfiguration="web">


        </endpoint>
      </service>

    </services>

    <serviceHostingEnvironment  multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
I hope you have done same configuration which i have done .

Step 5: Test REST Service.

Now our service is ready .lets test it using REST client of Mozilla browser are as

Our REST Service URL will be http://localhost:64858/PayMentService.svc/PayBill/100

In the above Response of WCF REST service you have seen that status code is 200 OK. It means our service executed successfully .lets confirm by switching to Response Body tab of REST client as

From preceding output its clear that out service executed successfully and as per configuration its returned JSON output .Hope from preceding examples we have learned how to create WCF REST Service.
Note:
  • Configure the database connection in the web.config file depending on your database server location.
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary

I hope this article is useful for all readers. If you have any suggestion then please contact me.



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.

Ajax Enabled WCF Service

This article explains about the Ajax Enabled WCF service which creates an Ajax Enabled WCF service. Visual Studio provides by default a template for that. So let us learn step-by-step about the Ajax Enabled WCF service so beginners also can understand. 
Requirements to understand this tutorial  
If you are a beginner and need to understand what a WCF service is, refer to the following article of mine:
  1.  Introduction to WCF Service
  2. Creating WCF Service
  3. Endpoints in WCF Service
  4. Contracts in WCF Service
  5. Bindings in WCF Service
I hope you read it if you are unfamiliar with WCF services, so I will briefly define what a WCF service.
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.
Now the next requirement is for you to at least be aware of Ajax. If you are unfamiliar with Ajax then please refer to the following article of mine:
I hope you have read it. Now let us see about Ajax Enabled WCF Services.
What is Ajax Enabled Services?
An Ajax Enabled Service is a template in Visual Studio that provides a configuration by default to consume a WCF service using Ajax and jQuery. 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 WebSite" - "C#" - "ASP.NET Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as "AjaxEnabledWCFServiceApplication" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item". You will see the Ajax Enabled WCF service template as same as the following image,
ajax enable wcf service
Now click on "Add". The Solution Explorer will then look as in the following:
 
Step 2
Add a web page to the new web application as in the following:
  1. Right-click on Solution Explorer then select "Add New Item". You will see the Web Form  template then click on Add.
  2. Now drag and drop one Input Button, a Text Box to 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 runat="server">  
        <title></title>  
        <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
        
      
    </head>  
    <body bgcolor="black">  
        <form id="form1" runat="server">  
        <br />      
        <br />      
        <br />    
        <table style="color: White;">  
            <tr>  
                <td>  
                    Enter Number  
                </td>  
                <td>  
                    <input type="text" id="txtgetMulti" />  
                </td>  
            </tr>  
            <tr>  
                <td>  
                </td>  
                <td>  
                    <input id="btnGetMulti" type="button" value="Get Result" />  
                </td>  
            </tr>  
        </table>  
          
        </form>  
    </body>  
    </html> 
Step 3
Create a method in the Service.svc file as in the following:
    public class Service  
    {  
       
            [OperationContract]  
            [System.ServiceModel.Web.WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]  
            public int Multiplication(int Number)
            {  
                return Number*Number;  
      
            }  
    } 
 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 used to uniquely identify the service as in the following:
    [ServiceContract(Namespace = "Multiplication")]  
     [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)] 
After adding the preceding line, the Service class will look as follows:
    [ServiceContract(Namespace = "Multiplication")]  
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
    public class Service  
    {  
       
            [OperationContract]  
            [System.ServiceModel.Web.WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]  
            public int Multiplication(int Number)  
            {  
                return Number*Number;  
      
            }  
    } 
Step 5
Let us see the UI of the .aspx page:
In the preceding UI you saw that there is a TextBox that accepts integer type numbers and there is the Get Result HTML button that calls the jQuery function to call the WCF  Method.
 
Step 6
Refer to the jQuery library script Path file as in the following:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
 Now see the  the Web.config file configuration as follows:
    <system.serviceModel>  
        <behaviors>  
          <endpointBehaviors>  
            <behavior name="ServiceAspNetAjaxBehavior">  
              <enableWebScript/>  
            </behavior>  
          </endpointBehaviors>  
        </behaviors>  
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>  
        <services>  
          <service name="Service">  
            <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="Service"/>  
          </service>  
        </services>  
      </system.serviceModel> 
Step 7
Create a jQuery function to call the service method using JSON as in the following:
    $("#btnGetMulti").live("click", function () {  
                $.ajax({  
                    type: "POST",  
                    contentType: "application/json; charset=utf-8",  
                    url: 'Service.svc/GetMultiplication',  
                    data: '{"Number": "' + $("#txtgetMulti").val() + '"}',  
                    processData: true,  
                    dataType: "json",  
                    success: function (response) {  
                          
                        alert(response.d);  
                    },  
                    error: function (errormsg)   
                    {  
                        alert(errormsg.responseText);  
                    }  
                });  
            }); 
In the preceding function we are passing the input value to the server method using JSON and displaying the response in an alert box. The entire source code will look as follows:
 Default.aspx
    <%@ 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 runat="server">  
        <title></title>  
        <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>  
        <script type="text/javascript">  
            $("#btnGetMulti").live("click", function () {  
                $.ajax({  
                    type: "POST",  
                    contentType: "application/json; charset=utf-8",  
                    url: 'Service.svc/GetMultiplication',  
                    data: '{"Number": "' + $("#txtgetMulti").val() + '"}',  
                    processData: true,  
                    dataType: "json",  
                    success: function (response) {  
                          
                        alert(response.d);  
                    },  
                    error: function (errormsg)   
                    {  
                        alert(errormsg.responseText);  
                    }  
                });  
            });  
        </script>  
      
    </head>  
    <body bgcolor="black">  
        <form id="form1" runat="server">  
        <br />      
        <br />      
        <br />    
        <table style="color: White;">  
            <tr>  
                <td>  
                    Enter Number  
                </td>  
                <td>  
                    <input type="text" id="txtgetMulti" />  
                </td>  
            </tr>  
            <tr>  
                <td>  
                </td>  
                <td>  
                    <input id="btnGetMulti" type="button" value="Get Result" />  
                </td>  
            </tr>  
        </table>  
          
        </form>  
    </body>  
    </html> 
 Service.cs
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Runtime.Serialization;  
    using System.ServiceModel;  
    using System.ServiceModel.Activation;  
    using System.ServiceModel.Web;  
    using System.Text;  
      
    [ServiceContract(Namespace = "Multiplication")]  
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]  
    public class Service  
    {  
       
            [OperationContract]  
            [System.ServiceModel.Web.WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]  
            public int GetMultiplication(int  Number)  
            {  
                return Number*Number;  
      
            }  
    } 
Now click F5 to run the application. Enter a number into the TextBox and click on the Get Result button, it will show the following output:
 
 
In the preceding image the output is returned from the WCF service as 1000.
Notes
  • Don't forget to refer to the jQuery Script file Reference.
Summary
From all the examples above we have learned what an Ajax Enabled WCF service is and how 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. 

Contracts in WCF Service

Contracts are useful to built the WCF service application .Contracts defines what protocol (binding) does service use ,how communication will be done ,what message exchange format to use and much.
The following are the Contracts which are available in WCF
  • Service contracts
  • Data contracts
  • Message contracts
  • Fault Contract 
  • Operation contract
Service contracts
Service contracts nothing but the it defines the Interface for the service.It can be defined as follows
Syntax
   [ServiceContract]
    public interface IService1
    {

        // TODO: Add your service operations here
    }
 
Key Points 
  • Any WCF Service can have More than one service contract. 
  • It must to declare at least one service contract in a service.
  •  Service contract can be declared by using [ServiceContract] attribute. 
  • It allows defining operation contract under it to expose service outside the world. 
  • It maps the interface and methods of your service to a platform-independent description.
  •  It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern. 
Service contract attribute has following properties
  • CallbackContract 
  • ConfigurationName 
  • HasProtectionLevel 
  • Name 
  • Namespace 
  • ProtectionLevel
  • SessionMode
  • TypeId
Operation contract
Operation contract defines the method which is exposed to the client to exchange the information between client and server.Operation contract describes the what functionality to be given to the client such as Addition, subtraction etc
It can be defined as
   public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
  
    }
Operation contract attribute has following properties
CallbackContract :Gets or sets the type of callback contract when the contract is a duplex contract.
ConfigurationName :Gets or sets the name used to locate the service in an application configuration file.
HasProtectionLevel : Gets a value that indicates whether the member has a protection level assigned.
Name : Gets or sets the name for the <portType> element in Web Services Description Language (WSDL).
Namespace : Gets or sets the namespace of the <portType> element in Web Services Description Language (WSDL).
ProtectionLevel : Specifies whether the binding for the contract must support the value of the ProtectionLevel property.
SessionMode : Gets or sets whether sessions are allowed, not allowed or required.
TypeId: When implemented in a derived class, gets a unique identifier for this Attribute.
Data Contract
Data Contracts defines the data type for variables which are  are same as get set properties but difference is that data contract in WCF is used to serialize and deserialize the complex data.it defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through De-serialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
It can be defined as follows 
    [DataContract]
    public class Student
    {
        private string _Name;

        private string _City;


        [DataMember]
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
}
Fault Contract
Fault contract is used to handle the exception and know the cause of error which is occur in WCF service, basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handling are technology specific.
In order to support interoperability and client will also be interested only, what went wrong? Not on how and where cause the error.
The following is the syntax to raise the custom error in WCF
[ServiceContract]
    public interface IGetDetailsService
    {
        [OperationContract]
        [FaultContract(typeof(Student))]
        Student GetDetails(string Name);
    }

    [DataContract]
    public class Student
    {
        private string _Name;

        private string _City;

        [DataMember]
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        [DataMember]
        public string City
        {
            get { return _City; }
            set { _City = value; }
         }
}
Message contracts
Default SOAP message format is provided by the WCF run time for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
It can be defined as
[MessageContract]
public class Person
{
  [MessageHeader] public Operation Name;
  [MessageHeader] public string city;
  [MessageBodyMember] private Home Address;
  [MessageBodyMember] private Home Streat;
  [MessageBodyMember] public int age;
}
Note
Please refer my following articles for complete understanding
Summary
I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode