The System.Messaging namespace provides classes that allow you to connect to message queues, send messages, and receive or peek messages from queues. When you send a message to the queue, objects are serialized by the message formatter into the body of the message. The System.Messaging namespace includes the following three formatters:
To create a custom message formatter, you must implement the IMessageFormatter interface, which is included in the System.Messaging namespace. This interface specifies the following three methods:
Class declarationIn this example, the formatter class is called MyFormatter, and is declared as follows:
public class MyFormatter : IMessageFormatter
//The constructor can remain empty.
Write methodThe Write method serializes objects into the body of the message when the message is sent to the queue. In this example, the formatter takes in a string and serializes it by using UTF8 encoding. The Write method is implemented as follows:
public void Write (System.Messaging.Message msg, object obj)
//Declare a buffer.
//Place the string into the buffer using UTF8 encoding.
buff = Encoding.UTF8.GetBytes (obj.ToString());
//Create a new MemoryStream object passing the buffer.
Stream stm = new MemoryStream(buff);
//Assign the stream to the message's BodyStream property.
msg.BodyStream = stm;
Read methodThe Read method deserializes the body of the message when you read or peek the message from the queue. Essentially, the Read method reverses the process that is done with the Write method.
public object Read (System.Messaging.Message msg)
//Obtain the BodyStream for the message.
Stream stm = msg.BodyStream;
//Create a StreamReader object used for reading from the stream.
StreamReader reader = new StreamReader (stm);
//Return the string read from the stream.
//StreamReader.ReadToEnd returns a string.
CanRead methodThe CanRead method attempts to determine whether the formatter can handle the message that is passed to it. For brevity, this formatter assumes that the message body is a string (all messages in the queue were sent using this formatter) and returns True.
public bool CanRead (System.Messaging.Message msg)
Clone methodThe Clone method returns a new instance of the formatter.
public object Clone()
return new MyFormatter();
Use the formatterAfter the formatter is implemented, you can set the Formatter property of the MessageQueue object to a new instance of this formatter, as follows:
//Open an existing public queue called Test.
MessageQueue msgQueue = new MessageQueue (@".\test");
//Set the Formatter property.
msgQueue.Formatter = new MyFormatter();
//Send a test message.
msgQueue.Send ("Test string message");
Article ID: 310683 - Last Review: Jul 11, 2008 - Revision: 1