Message Exchange Pattern in WCF

What is WCF?

WCF is a Microsoft platform for building distributed and interoperable applications and it keeps data in XML and JSON format that can be understood by any language. WCF service can communicate in XML and JSON message formats with the client. 

Message Exchange Pattern in WCF

We know that WCF keeps data in XML or JSON format. When a client sends a request to a service and the service sends a response to the client then the request and response is in XML or JSON format, in other words, the message exchange is in the format of XML or JSON between the client and the service.
Now I want to explain why we need the Message Exchange Pattern:
  1. When we want the calling of the function to not take more time
  2. We just want to call the function and not want wait for the response.
  3. When we want that function call is not blocking and at the same time we want something out of the function (response) for our application. 
  4. When we want a two-way communication mechanism.
In WCF there are the following 3 types of Message Exchange Pattern:
  1. Request/Response
  2. One way
  3. Duplex

1. Request/Response

This is the default Message Exchange Pattern. In this pattern the client sends a request to the server and it waits for the response until the server does not stop processing, for example if the client a sends a request to get the name of all users then the service will proceed with it and the client must wait for a response when the service sends a result then the client is free. if we use the void keyword then it will also take more time. The one property to set the pattern of request/response is IsOneWay=false and all the WCF bindings except MSMQ based binding supports the request/response.
Request Response 
By using this diagram it can be easily understood that when the client sends a request it must wait for a response until the WCF process is not finished.
Now I will explain the request/response with the following example.
Step 1: Open Visual Studio 2010.
Step 2: Now go to "New Project" > "WCF" > "WCF Service Application" and add the name of the service.
WCF Service Application 
Step 3: Now after declaring the method inside in the interface here the OperationContract attribute is present in the Message Exchange Pattern and the IsOneWay=false setting shows the Request-Reply Message pattern setting.
  1. // specifies the request-reply message pattern  
  2. [OperationContract(IsOneWay=false)]  
  3. //declare the method which return type is string  
  4. string RequestReplyPattern(); 
Now to implement the code in the .cs file.
  1. public string RequestReplyPattern()  
  2. {  
  3.     //using the namespace using System.Threading for sleep the thread in 2 minute  
  4.     Thread.Sleep(2000);  
  5.     //return the date and time  
  6.    return "current time of Service is" + DateTime.Now.ToString();  

And then after running the service.
Step 4: Now add the new item from right click on Solution Explorer and "Add" > "New Item" > "Web Form".
Web Form 
Now get the controls on Web Form for a Button and 2 labels.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Message_Contract.WebForm1" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">  
  4. <html xmlns="">  
  5.     <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9. <form id="form1" runat="server">  
  10. <div>  
  11.     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />  
  12.     <br />  
  13.     <asp:Label ID="lblPagedate" runat="server"></asp:Label>  
  14.     <br />  
  15. <br />  
  16.      <asp:Label ID="lblServicedate" runat="server"></asp:Label>  
  17.     </div>  
  18.   </form>  
  19. </body>  
  20. </html> 
Now we need to add the reference of the service so to do that click on Add Service Reference and then a window will open and in it click on Discover and then the service will be shown and add the service.
add the service 
Code Behind
  1. //On the button click   
  2. protected void Button1_Click(object sender, EventArgs e)  
  3. {  
  4.     // Before service is call the time will show  
  5.     lblPagedate.Text = "Page date is " + DateTime.Now.ToString();  
  6.     ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();  
  7.     //service is calling and in label, time is show after service will call  
  8.     lblServicedate.Text = sc.RequestReplyPattern();  

Now from the output the client sends a request from a button to the WCF service and it waits 2 minutes and then it returns the result so for that the client must wait for a response until the WCF service processing is done. If there is an exception then the client also must wait for the response.
The advantages of request/response message pattern is:
  1. Supports all the bindings except MSMQ-based binding
  2. If an exception occurs in the service then it immediately informs the client and developer so the developer can easily get the faults in the service.
The disadvantages of the request/response pattern is:
  1. The client must wait more time since there is so much processing before the service can send the TimeoutException to the client

2. One way

In the previous pattern the client must wait if the return type is void then also so for that in this pattern if the client sends a request to the service then it has no need to wait for the response. This mode is used when we don't want to show any type of error to the client because when we use the Message Exchange Pattern then it doesn't give any message to the client. We can set these patterns using IsOneWay = true in the service, the exception will be thrown if IsOneWay = true is declared in the output parameter, reference parameter or return value. When we use these modes and if the service is busy with the other service and client sends the request then it can keep the request in the Queue and then the client can do his other work, the client is unblocked and we can set the Queue limit of the request.
One way 
The diagram shows that only the client can send the message to the service.
Now I am explaining one-way messages with the following example.
Step 3: The remaining steps are the same and declares the method in the interface and sets the property of OneWay:
  1. //Specify the Oneway message exchanging pattern  
  2. [OperationContract(IsOneWay = true)]  
  3. void OneWayMessage(); 
And now implement the method in the .cs file of the service. 
  1. public void OneWayMessage()  
  2. {  
  3.     //using the namespace using System.Threading for sleep the thread in 2 minute  
  4.     Thread.Sleep(2000);  

Step 4: Now in the web form use this code in the code behind:
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     //Time show before the service is calling  
  4.     lblPagedate.Text = "on the load time the time is " + DateTime.Now.ToString();  
  5.     ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();  
  6.     sc.OneWayMessage();  
  7.     //after service is calling that time show  
  8.     lblServicedate.Text = "After Calling the service the time is " + DateTime.Now.ToString();  

file of service 
Now the output shows that both times are the same but we specify a 2 minute wait in the service. It happens only because the client sends a request to the server it does not wait for the WCF service processing and it gives the response back if an error occurs then the service also doesn't report to the client. 
The following are the advantages of OneWay:
  1. Clients are unaware of any exceptions of the service.
  2. It takes less time for the process
  3. the client is not blocked after a request, the client can do his other work. 
  4. This pattern is doing work like asynchronous
The following are the disadvantages of OneWay:
  1. If the request exceeds the limit of the queue then it can be blocked by the client.
  2. The client cannot know whether or not the request is reached successfully

3. Duplex

The duplex pattern implements both of the OneWay and Request/Response message patterns. The client and the service both initiate this pattern. This pattern is more complex than other patterns because the additional communication is added. This mode is used when we want to send the notification to the client about his request being reached successfully or not. It doesn't support all bindings.
As shown in the diagram the client sends a request to the service and it processes the request and gives the response but if the user wants to do his other work then it can also do that and the service provides the notification. For the setting of the Duplex pattern we need to use concurrent mode.
  1. [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Reentrant)]  
  2. And for synchronizaion in client machine   
  3. [CallbackBehavior(UseSynchronizationContext=false)]  
  4. Or   
  5. IsOneWay=true  
For a better understanding of the Duplex pattern I will explain with the following example.
Before proceeding we need to see my previous articles and follow the procedure for self hosting that plays an important role in the Duplex Message Exchange Pattern.
In the interface declare the following method.
  1. //associate service contract with service contract using call back attribute  
  2. [ServiceContract(CallbackContract=typeof(IService1CallBack))]  
  3. public interface IService1  
  4. {  
  5.     [OperationContract]  
  6.     void hello();  
  7. }  
  8. public interface IService1CallBack  
  9. {  
  10.     [OperationContract]  
  11.     void helloback(string name);  

And now implement the method in the .cs of the service:
  1. //from this setting it allows the call back from the service  
  2. [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Reentrant)]  
  3. public class Service1 : IService1  
  4. {  
  5.    public void hello()  
  6.    {  
  7.       Thread.Sleep(50);  
  8.       string name="Divya";  
  9.       //to feed the information in the client side so for associate  
  10.       OperationContext.Current.GetCallbackChannel<IService1CallBack>().helloback(name);  
  11.    }  

And now for hosting code in the Console Application:
  1. static void Main(string[] args)  
  2. {  
  3.     //herre the name of the service which we need to host  
  4.     using (ServiceHost host = new ServiceHost(typeof(Duplex_Message_Exchange.Service1)))  
  5.     {  
  6.         //read the WCF service  
  7.         host.Open();  
  8.         Console.WriteLine(DateTime.Now.ToString());  
  9.         host.Close();  
  10.         Console.ReadLine();  
  11.     }  

And now for testing, create a client to get a new project of a Windows Forms application and here add the reference of the service. For that go to References and Add Service Reference.
Service Reference 
And now get 2 controls, a button and a TextBox. And here write the code of code behind:
  1. [CallbackBehavior(UseSynchronizationContext=false)]  
  2. public partial class Form1 : Form, Duplex_Message_Exchange.IService1CallBack  
  3. {  
  4.     public Form1()  
  5.     {  
  6.         InitializeComponent();  
  7.     }  
  8.     private void button1_Click(object sender, EventArgs e)  
  9.     {  
  10.         // and need to create the instance of class, the class is Form1  
  11.         InstanceContext instance=new InstanceContext(this);  
  12.         //we need to create a instance of proxy class  
  13.         Duplex_Message_Exchange.IService1CallBack client = new Duplex_Message_Exchange.IService1CallBack(instance);  
  14.         client.hello();  
  15.     }  
  16.     //this method will be recived the name of the person which service is return  
  17.     void helloback(string name)  
  18.     {  
  19.        textBox1.Text = name.ToString();  
  20.     }
  21. }
Advantages of duplex exchange message pattern.
  1. The user can get the notification of the service without wait. 
  2. The blocking of the client's work is less 
Disadvantages of the duplex exchange message pattern.
  1. It is more complex.
  2. It doesn't support all bindings.