Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 19875 |  Welcome, Guest!   Register  Login
Home > Articles > C# > Sending and receiving message in MSMQ using C#

Sending and receiving message in MSMQ using C#

1 vote(s)
Rating: 5 out of 5
Article posted by SheoNarayan on 1/10/2011 | Views: 42517 | Category: C# | Level: Intermediate | Points: 250 red flag


This article describes how to send and receiving messages in MSMQ using C#.

Download


 Download source code for Sending and receiving message in MSMQ using C#


Introduction

MSMQ stands for Microsoft Message Queuing is one of the most reliable way to sending and receiving messages from one system to another system; both system can be located at different geographical locations. The benefit of MSMQ is that the receiving application doesn't have to run at the time of sending the message. Messages are stored in the queue of the system (Microsoft Operating System) and once the receiving application runs, it starts peeking the messages one by one.


Picture - 1

I have written hundreds of .NET How to's solution (ebook + source code + video) series based on real time project problems, click here to get it.

Namespace to use

To work with MSMQ, you will need to use following namespace.

using System.Messaging;

Creating a Queue in the system

Creating a queue in the system is an easy task. Go to My Computer and right click, select Manage and explore the nodes as displayed in the picture below.

Picture - 2

Right click the Private Queues and select New > Priovate Queue and create a queue. Alternatively, this can be done using C# code as well. My code snippet below does that automatically (ie. if queue doesn't exists, it creates otherwise use the existing one).

Writing the Queue name

The queue name should be written in specific format in order to access them programatically.

const string queueName = @".\private$\TestQueue";

In the above code, you can see that the name starts with "." and then private followed by $ symbol and then the actual queue name is written.

Now, let's send a message to the MSMQ using C#

Below code receive a queue name and sends an object to the queue as message. In this case I am using Person class that has two properties, FirstName and LastName as displayed below.

// create a class

public class Person

{

public string FirstName { get; set; }

public string LastName { get; set; }

}

Now, lets see the actual SendMessageToQueue method. Below method, first checks for the existence of the queue, if it doesn't exists then create one else use it. Next, under the try block, it creates the instance of the Person object and sets its values. Using Send method of the MessageQueue object, it sends the message to the queue. Next couple of lines are catch block that execute in case any error occur.

private static void SendMessageToQueue(string queueName)

{

// check if queue exists, if not create it

MessageQueue msMq = null;

if (!MessageQueue.Exists(queueName))

{

msMq = MessageQueue.Create(queueName);

}

else

{

msMq = new MessageQueue(queueName);

}

try

{

// msMq.Send("Sending data to MSMQ at " + DateTime.Now.ToString());

Person p = new Person()

{

FirstName = "ITFunda",

LastName=".Com"

};

msMq.Send(p);

}

catch (MessageQueueException ee)

{

Console.Write(ee.ToString());

}

catch (Exception eee)

{

Console.Write(eee.ToString());

}

finally

{

msMq.Close();

}

Console.WriteLine("Message sent ......");

}

Look at the above picture - 2, you will see that there is a message displayed at the right side panel.

Receiving messages from MSMQ using C#

To receive a message from queue, we need to first instantiate the queue using MessageQueue. You will need to make sure that the queue exists, otherwise you shall get an error. Under the try block I have used XmlMessageFormatter object to specify the format of the message I have in the queue. The next line unboxed the body of the message to the Person object and writes its property on the console (you can see the first image above). Following lines are catch blocks that execute if any error occur.

private static void ReceiveMessageFromQueue(string queueName)

{

 

MessageQueue msMq = msMq = new MessageQueue(queueName);

 

try

{

// msMq.Formatter = new XmlMessageFormatter(new Type[] {typeof(string)});

msMq.Formatter = new XmlMessageFormatter(new Type[] { typeof(Person) });

var message = (Person)msMq.Receive().Body;

Console.WriteLine("FirstName: " + message.FirstName + ", LastName: " + message.LastName);

// Console.WriteLine(message.Body.ToString());

}

catch (MessageQueueException ee)

{

Console.Write(ee.ToString());

}

catch (Exception eee)

{

Console.Write(eee.ToString());

}

finally

{

msMq.Close();

}

Console.WriteLine("Message received ......");

}

Sending and Receiving string/plain text to the MSMQ

Sending and receiving string to the MSMQ has been also covered in the above code snippet, you need to uncomment the corresponding lines of code from above two methods and comment the lines that is sending and receiving the Person object.

The complete source code for console application that creates, sends and receives data in MSMQ is attached with this article. Feel free to download and use it.

Reference

  • http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.aspx

Conclusion

By writing few lines of code, we can communicate with the Microsoft Messaging Queue. MSMQ supports transactional communication as well so that in case you are sending multiple message related with one another and one message fails, all should rollback. Apart from this, you have ability to send and receive asynchronous messages as well.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: Karthikanbarasan | Posted on: 13 Jan 2011 08:52:13 AM | Points: 25

Nice article to start with MSMQ

>> Write Response - Respond to this post and get points
Related Posts

This is a very simple article and some people may really find it not worth to be termed as article. One of my junior was working for a full day on this. Just wanted to ensure that other people do not face the same problem. In this article we will try to understand how we can simulate the On Error Resume Next feature of VB.NET in C#. We all understand that it’s a bad thing to handle errors, but sometimes some process should continue irrespective there is error or not.

This article describes about most of the Value Types variables, its uses and how to use them.

In this example i am explaining how to create AutoComplete TextBox or ComboBox in winforms using C#

In this post you will learn how to write custom namespaces and nested namespaces in C#.

Here I am just explaining how can we call the Extension Methods. And using extension methods how to sort the objects and primitive data types.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/20/2013 10:24:13 AM