Bewerken

Share via


XmlMessageFormatter Class

Definition

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

public ref class XmlMessageFormatter : ICloneable, System::Messaging::IMessageFormatter
public class XmlMessageFormatter : ICloneable, System.Messaging.IMessageFormatter
type XmlMessageFormatter = class
    interface IMessageFormatter
    interface ICloneable
Public Class XmlMessageFormatter
Implements ICloneable, IMessageFormatter
Inheritance
XmlMessageFormatter
Implements

Examples

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.dll>
#using <System.Messaging.dll>

using namespace System;
using namespace System::Messaging;

// placeholder; see complete definition elsewhere in this section
public ref class Order
{
public:
   void ShipItems(){}

};


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

int main()
{
   Console::WriteLine( "Processing Orders" );
   String^ queuePath = ".\\orders";
   EnsureQueueExists( queuePath );
   MessageQueue^ queue = gcnew MessageQueue( queuePath );
   array<String^>^temp0 = {"Order"};
   (dynamic_cast<XmlMessageFormatter^>(queue->Formatter))->TargetTypeNames = temp0;
   while ( true )
   {
      Order^ newOrder = dynamic_cast<Order^>(queue->Receive()->Body);
      newOrder->ShipItems();
   }
}
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);
         }
     }
 }
Imports System.Messaging



Public Class Server
    
    
    Public Shared Sub Main()
        
        Console.WriteLine("Processing Orders")
        
        Dim queuePath As String = ".\orders"
        EnsureQueueExists(queuePath)
        Dim queue As New MessageQueue(queuePath)
        CType(queue.Formatter, XmlMessageFormatter).TargetTypeNames = New String() {"Order"}
        
        While True
            Dim newOrder As Order = CType(queue.Receive().Body, Order)
            newOrder.ShipItems()
        End While
    End Sub
    
    
    ' Creates the queue if it does not already exist.
    Public Shared Sub EnsureQueueExists(path As String)
        If Not MessageQueue.Exists(path) Then
            MessageQueue.Create(path)
        End If
    End Sub
End Class

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 namespace System;
public ref class Order
{
public:
   int itemId;
   int quantity;
   String^ address;
   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. */
   }

};
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. */
     }
 }
Public Class Order
    
    Public itemId As Integer
    Public quantity As Integer
    Public address As String
    
    
    Public Sub ShipItems()
        
        Console.WriteLine("Order Placed:")
        Console.WriteLine(ControlChars.Tab & "Item ID  : {0}", itemId)
        Console.WriteLine(ControlChars.Tab & "Quantity : {0}", quantity)
        Console.WriteLine(ControlChars.Tab & "Ship To  : {0}", address)

        ' Add order to the database.
        ' Insert code here.
 
    End Sub
End Class

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.dll>
#using <System.Messaging.dll>

using namespace System;
using namespace System::Messaging;

// placeholder; see complete definition elsewhere in this section
public ref class Order
{
public:
   int itemId;
   int quantity;
   String^ address;
   void ShipItems(){}

};


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

int main()
{
   String^ queuePath = ".\\orders";
   EnsureQueueExists( queuePath );
   MessageQueue^ queue = gcnew MessageQueue( queuePath );
   Order^ orderRequest = gcnew 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();
}
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);
         }
     }
 }
Imports System.Messaging

Class Client
    
    
    Public Shared Sub Main()
        
        Dim queuePath As String = ".\orders"
        EnsureQueueExists(queuePath)
        Dim queue As New MessageQueue(queuePath)
        
        Dim orderRequest As 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()

    End Sub
    
    ' Creates the queue if it does not already exist.
    Public Shared Sub EnsureQueueExists(path As String)
        If Not MessageQueue.Exists(path) Then
            MessageQueue.Create(path)
        End If
    End Sub
End Class

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.

Remarks

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 parameterless 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.

Constructors

XmlMessageFormatter()

Initializes a new instance of the XmlMessageFormatter class, without target types set.

XmlMessageFormatter(String[])

Initializes a new instance of the XmlMessageFormatter class, setting target types passed in as an array of (fully qualified) string values.

XmlMessageFormatter(Type[])

Initializes a new instance of the XmlMessageFormatter class, setting target types passed in as an array of object types.

Properties

TargetTypeNames

Specifies the set of possible types that will be deserialized by the formatter from the message provided.

TargetTypes

Specifies the set of possible types that will be deserialized by the formatter from the message provided.

Methods

CanRead(Message)

Determines whether the formatter can deserialize the message.

Clone()

Creates an instance of the XmlMessageFormatter class whose read/write properties (the sets of target types) are the same as the current XmlMessageFormatter instance.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Read(Message)

Reads the contents from the given message and creates an object that contains the deserialized message.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
Write(Message, Object)

Serializes an object into the body of the message.

Applies to

See also