XmlMessageFormatter Class
Collapse the table of content
Expand the table of content

XmlMessageFormatter Class

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

For a list of all members of this type, see XmlMessageFormatter Members.

System.Object
   System.Messaging.XmlMessageFormatter

[Visual Basic]
Public Class XmlMessageFormatter
   Implements IMessageFormatter, ICloneable
[C#]
public class XmlMessageFormatter : IMessageFormatter, ICloneable
[C++]
public __gc class XmlMessageFormatter : public IMessageFormatter,
   ICloneable
[JScript]
public class XmlMessageFormatter implements IMessageFormatter,
   ICloneable

Thread Safety

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

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 object of the type that corresponds to the schema identied 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 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.

Example

[Visual Basic, C#, C++] The following 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.

[Visual Basic, C#, C++] The following code 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.

[Visual Basic] 
Imports System
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 'Main
    
    
    ' 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 'EnsureQueueExists
End Class 'Server

[C#] 
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);
         }
     }
 }

[C++] 
#using <mscorlib.dll>
#using <System.dll>
#using <System.Messaging.dll>
using namespace System;
using namespace System::Messaging;

public __gc class Order

// placeholder; see complete definition elsewhere in this section

{
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(S"Processing Orders");

    String* queuePath = S".\\orders";
    EnsureQueueExists(queuePath);
    MessageQueue* queue = new MessageQueue(queuePath);

    String* temp0 [] = {S"Order"};
    (dynamic_cast<XmlMessageFormatter*>(queue->Formatter))->TargetTypeNames = temp0;

    while(true){
        Order* newOrder = dynamic_cast<Order*>(queue->Receive()->Body);
        newOrder->ShipItems();
    }
}

[Visual Basic, C#, C++] This code sample represents the order class that provides a schema for the order objects that the application on the server receives and deserializes:

[Visual Basic] 
Imports System
Imports Microsoft.VisualBasic

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 'ShipItems 
End Class 'Order 

[C#] 
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. */
 
     }
 }

[C++] 
#using <mscorlib.dll>
using namespace System;
 
public __gc class Order{
 
public:
     int itemId;
     int quantity;
     String* address;

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

[Visual Basic, C#, C++] 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.

[Visual Basic, C#, C++] 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.

[Visual Basic, C#, C++] The following code 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.

[Visual Basic] 
Imports System
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 'Main
    
    ' 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 'EnsureQueueExists
End Class 'Client 

[C#] 
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);
         }
     }
 
 }

[C++] 
#using <mscorlib.dll>
#using <System.dll>
#using <System.Messaging.dll>
using namespace System;
using namespace System::Messaging;

public __gc class Order

// placeholder; see complete definition elsewhere in this section

{
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 = S".\\orders";
    EnsureQueueExists(queuePath);
    MessageQueue* queue = new MessageQueue(queuePath);

    Order* orderRequest = new Order();
    orderRequest->itemId = 1025;
    orderRequest->quantity = 5;
    orderRequest->address = S"One Microsoft Way";

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

[Visual Basic, C#, C++] 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.

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Messaging

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: System.Messaging (in System.Messaging.dll)

See Also

XmlMessageFormatter Members | System.Messaging Namespace | MessageQueue | ActiveXMessageFormatter | BinaryMessageFormatter | IMessageFormatter

Show:
© 2016 Microsoft