Article ID: 310683 - View products that this article applies to.
This article was previously published under Q310683
This step-by-step article shows you how to use Visual C# to create a simple custom message formatter.
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:
Note that a project reference to System.Messaging.DLL is required. To add this reference in Visual Studio .NET, right-click References and select Add Reference.
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:
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.
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.
Clone methodThe Clone method returns a new instance of the formatter.
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:
Contact us for more help
Connect with Answer Desk for expert help.