In this article we try to learn how to implement a MSMQ feature in a WCF service. The MSMQ feature allows us to create a program that can reliably send or receive messages over a wire without any loss of message. It makes use of a queue to store messages in the order in which they arrive. The queue is a First In First Out stack i.e. the message that arrived first will be the first that to be removed from the queue for processing by the server. MSMQ can be implemented in the manner that there are multiple clients sending a request to the server but because of overload, the server is busy processing previous client requests so in such cases MSMQ can be implemented to maintain a queue of requests from new clients and whenever the server becomes free it will take requests from the queue and process them one by one. By implementing MSMQ there are less chances of losing the message sent by the client.
The following diagram depicts that.
From the diagram above we can see there are multiple clients sending requests to the server, but if the server is busy then the requests are stored in the MSMQ queue and later when the server becomes free it proceeds to read and process messages one by one.
Now to get to our topic of how to implement MSMQ in a WCF service, well first of all to implement the MSMQ feature we need to install the MSMQ server, because it's an optional component in your operating system, like the way we install IIS, we can use the same way here. For installing MSMQ use the following procedure.
- Open the "Control Panel" -> "Programs and features"
- Select "Turn Windows Features On or Off" from the left hand pane of the "Programs and Features" window
- The Windows features dialog box will appear, from there select MSMQ Server (select all dependent checkboxes to install the full MSMQ server)
- Finally click on Ok to install it.
- After installing it you can verify it by clicking on "Administrative Tools" inside "Control Panel"
- Select "Computer Management" then expand "Services and Applications" and you will find Message Queuing with some sub folders inside it. Like the following:
Until now we have installed MSMQ but now to work with it we must create a Queue that will store our messages if the server is not available, the queue can be created either manually or programmatically. In our case we will try to create a queue programmatically. Queues are of three types they are either public, private or System. For more information about that kindly search it.
Ok now moving towards our program in this we have created a service contract that contains one operation contract with the name "SayYourWish" that accepts the name of the clients and their wishes. To maintain reliable messaging we have implemented the MSMQ feature in our service so that no client's wish is lost while transferring or due to server load or server unavailability.
Here is my Service Contract that I defined.
IWish.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.ServiceModel;
-
- namespace WishListComponent
- {
- [ServiceContract]
- public interface IWish
- {
-
-
- [OperationContract(IsOneWay = true)]
- void SayYourWish(string wisherName, string yourWish);
- }
- }
MyWish.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace WishListComponent
- {
- public class MyWish : IWish
- {
-
- public void SayYourWish(string wisherName, string yourWish)
- {
- Console.WriteLine("Client (Wisher): " + wisherName + " wish is :" + yourWish);
- }
- }
- }
ConsoleHost.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Messaging;
- using System.ServiceModel;
- using WishListComponent;
-
- namespace ConsoleHost
- {
- class Program
- {
- static void Main(string[] args)
- {
- using (ServiceHost host = new ServiceHost(typeof(MyWish)))
- {
-
-
- string myQueue = ".\\private$\\VishalQ";
-
- if (!MessageQueue.Exists(myQueue))
- {
-
-
-
- MessageQueue.Create(myQueue, false);
- }
-
- host.Open();
- Console.WriteLine("Server is up and running on port 32578");
- Console.WriteLine("Press any key to exit");
- Console.ReadKey();
- }
- }
- }
- }
App.Config file
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <system.serviceModel>
- <diagnostics performanceCounters="All" />
- <services>
- <service name="WishListComponent.MyWish" behaviorConfiguration="myBehavior">
-
-
- <endpoint name="wish" address="VishalQ" binding="netMsmqBinding"
- bindingConfiguration="myMSMQ" contract="WishListComponent.IWish"/>
- <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
- <host>
- <baseAddresses>
- <add baseAddress="net.msmq://localhost/private/"/>
-
- <add baseAddress="http://localhost:32578"/>
- </baseAddresses>
- </host>
- </service>
- </services>
- <bindings>
-
- <netMsmqBinding>
- <binding name="myMSMQ" exactlyOnce="false" >
- <!--
- If we donot set the security mode to none then the following error occurs.
- Binding validation failed because the binding's MsmqAuthenticationMode property is set to
- WindowsDomain but MSMQ is installed with Active Directory integration disabled.
- The channel factory or service host cannot be opened.
- -->
- <security mode="None"/>
- </binding>
- </netMsmqBinding>
- </bindings>
- <behaviors>
- <serviceBehaviors>
- <behavior name="myBehavior">
- <serviceMetadata httpGetEnabled="true"/>
-
- <serviceDebug includeExceptionDetailInFaults="true"/>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- </system.serviceModel>
- </configuration>
Note
-
We will be making use of Self Hosting for hosting the program.
-
Our Client would be a Console Client.
-
For implementing MSMQ we will be making use of netMsmqBinding.
-
You need to add the service reference to the ConsoleClient Application, for adding it go to the bin folder of your ConsoleHost application through windows Explorer, from there double-click on the ConsoleHost.exe file so that it displays the following output.
-
5. Right-click on the ConsoleClient and click "Add Service Reference", in the service reference dialog box paste the URL as http://localhost:32578?wsdl that we specified in the App.config file for the mex endpoint.
-
Specify the name for your service as WishServiceRef and click on "Add".
-
Your service will be added to your ConsoleClient Application.
ConsoleClient.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using ConsoleClient.WishServiceRef;
-
- namespace ConsoleClient
- {
- class Program
- {
- static void Main(string[] args)
- {
- string[] names = { "Vishal", "Rahul", "Mayur" };
- string[] wishes = { "Prizes", "Books", ".NET Softwares" };
-
- WishClient[] objArray = new WishClient[names.Length];
-
- for (int i = 0; i < objArray.Length; i++)
- {
- objArray[i] = new WishClient();
- objArray[i].SayYourWish(names[i], wishes[i]);
- }
- Console.WriteLine("All Wishes sent successfully");
- Console.ReadLine();
- }
- }
- }
Finally to Test the output. Do the following,
-
Close (to make the server unavailable) your ConsoleHost.exe if its already running
-
Run your ConsoleClient Program
-
It should display the following output:
-
Close the ConsoleClient output screen. And now check your queue.
-
Go to "Control Panel" -> "Administrative Tools" -> "Computer Management"
-
Go to "Message Queuing" inside "Services and Applications"
-
Go to your queue in this case "VishalQ" inside "Private Queues", expand it and select "Queue Messages"
-
On the right hand pane you will see all your messages are stored inside the queue.
-
The following diagram depicts that.
When we ran our ConsoleClient App at the time our Server i.e. the ConsoleHost was not running i.e. it was unavailable, now go to the bin folder of your ConsoleHost program through Windows Explorer and double-click the ConsoleHost.exe. You will find that the message from the queue will be removed and displayed on the ConsoleHost Screen like the following.
Hope you liked the article, in my future article we will try to implement Duplex or two-way communication between the client and the service using MSMQ in WCF.