Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

XmlMessageFormatter Class

Serializes and deserializes objects to or from the body of a message, using the XML format based on the XSD schema definition.

Namespace: System.Messaging
Assembly: System.Messaging (in system.messaging.dll)

public class XmlMessageFormatter : IMessageFormatter, ICloneable
public class XmlMessageFormatter implements IMessageFormatter, ICloneable
public class XmlMessageFormatter implements IMessageFormatter, ICloneable

The XmlMessageFormatter is the default formatter that an instance of MessageQueue uses to serialize messages written to the queue. When you create an instance of MessageQueue, an instance of XmlMessageFormatter is created for you and associated with the MessageQueue. You can specify a different formatter by creating it in your code and assigning it to the Formatter property of your MessageQueue.

A queue's default XmlMessageFormatter instance can be used to write to the queue, but it cannot be used to read from the queue until you set either the TargetTypes or TargetTypeNames property on the formatter. You can either set one or both of these values on the default formatter instance, or you can create a new instance of the formatter and set the values automatically by passing them as arguments into the appropriate XmlMessageFormatter constructor.

When specifying TargetTypes rather than TargetTypeNames, type existence is checked at compile time rather than read time, reducing possibility for error. TargetTypeNames requires every entry to be fully qualified, specifying its assembly name. Further, when working with multiple concurrent versions, the version number must also be appended to the target type name as well.

The TargetTypeNames and TargetTypes properties tell the formatter what schemas to attempt to match when deserializing a message. This allows the formatter to interpret the message body.

The instance serialized in the message body must comply with one of the schemas represented in the type array. When you read the message using the Receive method, the method creates an object of the type that corresponds to the schema identified and reads the message body into it.

Only one of the two properties needs to be set when reading from the queue, but you can set both. The set of types is the combined set from the two properties. The decision of which property to use is specific to your application. If the message body contains a type whose schema does not match any of the types in the array for either property, an exception will be thrown when the message is read.

The XmlMessageFormatter is a crucial component of loosely coupled XML-based messaging. The XSD.exe utility uses the XML format is used to generate XML schema, such as when you use the utility to serialize a class used by your application. The class must have a default constructor.

The format is used again in the reverse process when the utility generates a class based on the schema you distribute to describe your class data. The use of the utility and the XML schema it generates enables you to avoid redistributing.dll files every time you recompile a class after the implementation of your class has changed. As long as the schema does not change on the client or the server, other changes on either side do not affect the other.

The following code example includes three pieces of code: a server component, an order class, and client code. The order class can be used by the XSD.exe utility to generate schema that the server recognizes within incoming messages. The schema is an XML formatted file that describes the "shape" of the class. This schema can then be used on the client side to generate a client-specific order class that shares the same schema as the server class.

The following code example represents a server component that receives orders through a message queue. The body of the message should be an order object whose schema matches the Order.cs class below. The server process or application deserializes the order.

using System;
using System.Messaging;
 
 public class Server{
 
     public static void Main(){
 
         Console.WriteLine("Processing Orders");
 
         string queuePath = ".\\orders";
         EnsureQueueExists(queuePath);
         MessageQueue queue = new MessageQueue(queuePath);
         ((XmlMessageFormatter)queue.Formatter).TargetTypeNames = new string[]{"Order"};
 
         while(true){
             Order newOrder = (Order)queue.Receive().Body;
             newOrder.ShipItems();
         }
     }
 
     // Creates the queue if it does not already exist.
     public static void EnsureQueueExists(string path){
         if(!MessageQueue.Exists(path)){
             MessageQueue.Create(path);
         }
     }
 }

import System.*;
import System.Messaging.*;

public class Server
{
    public static void main(String[] args)
    {
        Console.WriteLine("Processing Orders");

        String queuePath = ".\\orders";
        EnsureQueueExists(queuePath);
        MessageQueue queue = new MessageQueue(queuePath);
        ((XmlMessageFormatter)queue.get_Formatter()).
            set_TargetTypeNames(new String[] { "Order" });

        while (true) {
            Order newOrder = (Order)queue.Receive().get_Body();
            newOrder.ShipItems();
        }
    } //main

    // Creates the queue if it does not already exist.
    public static void EnsureQueueExists(String path)
    {
        if (!(MessageQueue.Exists(path))) {
            MessageQueue.Create(path);
        }
    } //EnsureQueueExists
} //Server

The following code example represents the order class that provides a schema for the order objects that the application on the server receives and deserializes.

using System;
 
 public class Order{
 
     public int itemId;
     public int quantity;
     public string address;
 
     public void ShipItems(){
 
         Console.WriteLine("Order Placed:");
         Console.WriteLine("\tItem ID  : {0}",itemId);
         Console.WriteLine("\tQuantity : {0}",quantity);
         Console.WriteLine("\tShip To  : {0}",address);
 
         // Add order to the database.
         /* Insert code here. */
 
     }
 }

import System.*;

public class Order
{
    public int itemId;
    public int quantity;
    public String address;

    public void ShipItems()
    {
        Console.WriteLine("Order Placed:");
        Console.WriteLine("\tItem ID  : {0}", System.Convert.ToString(itemId));
        Console.WriteLine("\tQuantity : {0}", System.Convert.ToString(quantity));
        Console.WriteLine("\tShip To  : {0}", System.Convert.ToString(address));
        // Add order to the database.
        /* Insert code here. */
    } //ShipItems 
} //Order 

Any client application that interacts with the application on the server must send messages to the server by serializing information in a locally defined order class into the message body. The locally defined order class must have the same schema as the server-defined order class into which the application on the server will attempt to deserialize the message body. The XSD.exe utility lets the manager of the application on the server create and distribute the schema the client must use to serialize messages going to the server.

When the manager of the client application receives the schema for the order class, the XSD.exe utility is used again to generate a client-specific order class from the schema. It is this class that is used in the client code example below, not the server's order class (the XSD.exe utility causes the schema-generated class to have the same name as the original class). This new order class is used to serialize the order into the message body.

The following code example is the client-side processing, used to serialize an order and send the information associated with the order to a queue. The code associates Item, Quantity, and Address information with elements of the schema that were generated for the Order.cs class by the XSD.exe utility. An order is sent to the Orders queue on the local computer.

using System;
using System.Messaging;
 
 class Client{
 
     public static void Main(){
 
         string queuePath = ".\\orders";
         EnsureQueueExists(queuePath);
         MessageQueue queue = new MessageQueue(queuePath);
 
         Order orderRequest = new Order();
         orderRequest.itemId = 1025;
         orderRequest.quantity = 5;
         orderRequest.address = "One Microsoft Way";
 
         queue.Send(orderRequest);
         // This line uses a new method you define on the Order class:
         // orderRequest.PrintReceipt();
     }
 
     // Creates the queue if it does not already exist.
     public static void EnsureQueueExists(string path){
         if(!MessageQueue.Exists(path)){
             MessageQueue.Create(path);
         }
     }
 
 }

import System.*;
import System.Messaging.*;

class Client
{
    public static void main(String args[])
    {
        String queuePath = ".\\orders";
        EnsureQueueExists(queuePath);
        MessageQueue queue = new MessageQueue(queuePath);

        Order orderRequest = new Order();
        orderRequest.itemId = 1025;
        orderRequest.quantity = 5;
        orderRequest.address = "One Microsoft Way";

        queue.Send(orderRequest);
        // This line uses a new method you define on the Order class:
        // orderRequest.PrintReceipt();
    } //main

    // Creates the queue if it does not already exist.
    public static void EnsureQueueExists(String path)
    {
        if (!(MessageQueue.Exists(path))) {
            MessageQueue.Create(path);
        }
    } //EnsureQueueExists
} //Client

After the schema is generated from the order class on the server, you can modify the class. Unless the schema changes, you do not need to redistribute the schema. After you have distributed the schema and generated a client-side order class, that client class can also be modified independently of the server's order class, as long as the schema itself is not modified. The two classes have become loosely coupled.

System.Object
  System.Messaging.XmlMessageFormatter
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.