|
This is a very very basic bare-bones tutorial on writing to and reading from an MSMQ queue.
The example methods are both using a private local queue and use the default XMLFormatter.
First create the private queue: -Open the Computer Management Console -Navigate to Message Queuing under Services and Applications -Expand Message Queueing, right-click on Private Queues and create a new private queue.
If you don't see the Message Queueing option under Services and Applications, you don't have MSMQ installed on the machine. To install it, choose Add/Remove Windows Components and check Message Queueing and proceed with the installation. To write to a queue: 1. Specifiy the path to the queue - for a local private queue, the path should be in the form ".\private$\<queue name>" - replace <queue name> with the actual queue name e.g. ".\private$\testqueue"
2. Create a message of the type you wish in a Message object. 3. Create the queue object, supplying the path to it as a parameter. 4. Call the Send method on the queue, supplying the Message object created as a parameter.
The code should look something like the method below:
public string InsertInQueue()
{ string msg = "Test Queue Object"; //message contents
string queuepath = ".\\private$\\testqueue"; //path to queue
MessageQueue myQueue = new MessageQueue(queuepath); //create queue object
Message myMsg = new Message(msg); //form Message object
try
{
myQueue.Send(myMsg); //write message to queue
return "Success";
}
catch(Exception ex)
{
return ex.Message;
}
}
To read a message from a queue:
1. Specifiy the path to the queue 2. Create the queue object, supplying the path to it as a paramater. 3. Specify the formatter, either on the queue or by creating separate formatter object. 4. Read the message from the queue, by calling the Receive method on the queue. 5. Convert the message body as appropriate and return the value.
Sample code is shown below demonstrating how to read from a queue:
public string ReadFromQueue()
{
string queuepath = ".\\private$\\testqueue"; //specify queue path
MessageQueue myQueue = new MessageQueue(queuepath); //create queue
//specify typenames - this is needed by the formatter, to enable it to read the message contents string[] typenames = {"System.String"};
//The line below specifies the formatter on the queue //myQueue.Formatter = new XmlMessageFormatter(typenames);
//read message from queue Message myMsg = myQueue.Receive( new TimeSpan(0, 0, 5));
XmlMessageFormatter fmt = new XmlMessageFormatter(typenames);
//The line below is valid if the formatter is specified on the queue, as shown above //return myMsg.Body.ToString();
//Since we've selected to specify a separate formatter, we need to read the contents //of the message using the formatter return fmt.Read(myMsg).ToString();
}
PS: You must reference System.Messaging for all this to work.
|