Microsoft Message Queuing(MSMQ) in Asp.net


Today i want to discuss a complex topic that is how to store the Offline data to the Centralized server.This Article will help the readers the importance of Message Queue and which scenarios the Message queue will used,How to install Msmq in your system,Create a Message queue and fetch the data from the Message Queue using Asp.net programing. I will illustrate detail description with snippet of code lines.

The Name Microsoft Message Queue itself suggests the messages are stored in Queue either in your computer or in another computer waiting patiently for you to fetch the data from them. You can use Microsoft message queuing to reliably send messages from one computer to another Computer.

In this Modern era every public and private sector is computerised.For example a bank that has got multiple branches. The Bank Branches will store all the transaction data in their branch local Database and as well as central database .So that all the information is located at centralised location.whatever be the reason the central server fails so they can not able to store the transaction data on the centralized server.Will the Bank Branch Manager order their employees to stop all the transactions for the day or even until the central server is online ? Or he manually insert the data in the centralised server when its status changed to online.

The Answer is no he require his application to tackle this type of problem in such a way that he wants to store the data in a temporary location whenever Central database server comes to online the temporary location stored data moves in to the Central database. Now above scenario is apt to our topic. Message queues are particularly used for these types of scenarios

How to install Message Queues

Message queue is a Microsoft windows component. So first of all you need to add this component in your computer to test whether your sending message reaches to your msmq.

The below steps you need to follow to install Microsoft Message queues in Windows xp operating system

1) click Add/Remove Windows components

2)see After Management and Monitoring tools there is a component called Message queuing which is unchecked make it checked and click next to install your computer.

3) After configuring to your computer test whether the component is successfully installed in your computer or Not.

4)for that Go to Administrative tools - click Computer Management- services and Applications - Message Queuing

5) If not installed please contact your system Administrator..


Microsoft message queuing has Mainly two types of queues

1)Public Queue

2)Private Queue

Public Queues are available to application on every server in a Domain

Private Queues are available only to application on the local server

So this is the brief Introduction of Queues.

First Sample Program with Public Queues Retrieving the list of queues

First we need to import the name space System.Messaging


Dgrdqueues.DataSource = MessageQueue.GetPublicQueues();



An array of public queues is retrived from the GetPublicQueues() method and assign to datagrid.

Creating a new Public queue

Creating a public Queue is very easy. The dll system. messaging will provides a function called Create() of the Message queue class.


If ! MessageQueue.Exists(“.\OrderQueue")
MessageQueue.Create(“.\OrdersQueue")


Note : .\OrdersQueue is stored on the Local Machine.instead of ‘.' you can use Local machine name .

Creating Private Queues :

The following code illustrates Creating the Private queue.



If(! MessageQueue.Exists(“. \ Private$\PrivateOrders"))
{
MessageQueue.Create(“. \ Private$\PrivateOrders")
}



Note you need to add special string Private $ when supplying the path of the queue.

Sending Messages to a Queue

The System. Messaging dll consist of a Method called send().With this you can send a simple message or even complex data I.e. instance of a Class

Sending simple message to the Message queue


MessageQueues mqmessages =new MessageQueues();
If (!MessageQueue.Exists(“.\myQueue")
{
mqmessages.Create(“.\myQueue ");
}
Mqmessages =new MessageQueue(“.\myqueue");
Mqmessages.send(“yourmessagebody",messagelabel)


Sending a Complex data to the Message queue

How a product order will store in Message queue.

When you want to send product orders to the Message queue First thing you need to encapsulate the Product class by get and set methods. .

Defining a class for products


Public class Products
{
Public string productname{get;set;}
Public int unitprice {get;set;}
Public int quantity{get;set;}
Public datetime Entrydate{get;set;}
Public list {get;set;}
}


Now the Next step is assigning the values for the Product class.I want assign all the data in list.


Messagequeue msmq =new Messagequeue(“.\ProductOrders");
Products ObjProducts =new Products();
List lstprod=null;
lstprod =new List();
ObjProducts.Prodcutname="Pen"
ObjProducts.unitprice=20
ObjProducts.quantity=5
ObjProducts.Entrydate =system,datetime.now();
Lstproduct.add(Objproducts);
Msmq.send(lstproducts,"product Order");
}


You can use a Transactional Queue The below code illustrates that


public void SendMessage()
{

// Connect to a queue on the local computer.
MessageQueue myQueue = new MessageQueue(".\\myQueue");

// Send a message to the queue.
if (myQueue.Transactional == true)
{
// Create a transaction.
MessageQueueTransaction myTransaction = new
MessageQueueTransaction();

// Begin the transaction.
myTransaction.Begin();

// Send the message.
myQueue.Send("My Message Data.", myTransaction);

// Commit the transaction.
myTransaction.Commit();
}
else
{
myQueue.Send("My Message Data.");
}

return;
}
}
}


Final part of this topic fetching the data from the Queue


public void ReceiveMessage()
{
// Connect to the a queue on the local computer.
MessageQueue myQueue = new MessageQueue(".\\myQueue");

// Set the formatter to indicate body contains an Order.
myQueue.Formatter = new XmlMessageFormatter(new Type[]
{typeof(MyProject.Order)});

try
{
// Receive and format the message.
Message myMessage = myQueue.Receive();
Order myOrder = (Order)myMessage.Body;

// Display message information.

}

catch (MessageQueueException)
{

}

// Handle invalid serialization format.
catch (InvalidOperationException e)
{

}

// Catch other exceptions as necessary.

return;
}
}
}



Important Note:

For receiving/retriving the data from MSMQ we can use enumerator,you can use foreach , for loop and cursors in asp.net.According to programmers wish he can use his own logic

snippets of code using Enumerator


Mqmessages =new Message(“.\ProductOrders");
MessageEnumarator enummessages =new MessageEnumerator();
if (enumesages.MoveNext)
{
product myProduct= (Product)myMessage.Body;


enumMessages.RemoveCurrent();
}



Points to Remember when using Message Queue

You can use any Data to store in MSMQ. But the Data should not exceed more than 4 Mb.

Use xmlmessageFormmater to deserialize the Message Body

The important thing is after you fetch the data from the queue make sure and ensure that you delete the Queue.

If your message successfully sent than you will get the Acknowledgement.

Use Message Queue Exceptions for identify/Predict the Exact Error.


Article by srirama
A Good advice from parent to a Child , Master to a Student , Scholar to an Ignorant is like a doctor prescribed pill it is bitter to take but when they take it will do all good for them --- Bhushan

Follow srirama or read 74 articles authored by srirama

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: