XML deserialization when reading from msmq

Gerald picture Gerald · Nov 24, 2011 · Viewed 8.4k times · Source

I want to read XML Messages from a Message Queue in a C# WPF Application. Messages are saved into the Queue by a Navision codeunit. Firstly, I am not really sure if the messages that are saved in the Queue are usable, because they are in some sort of hexadecimal format which looks like this:

FF FE 3C 00 3F 00 78 00 ÿþ<.?.x.
6D 00 6C 00 20 00 76 00 m.l. .v.
65 00 72 00 73 00 69 00 e.r.s.i.
6F 00 6E 00 3D 00 22 00 o.n.=.".
31 00 2E 00 30 00 22 00 1...0.".
20 00 65 00 6E 00 63 00  .e.n.c.
6F 00 64 00 69 00 6E 00 o.d.i.n.
67 00 3D 00 22 00 55 00 g.=.".U.
54 00 46 00 2D 00 31 00 T.F.-.1.
36 00 22 00 20 00 73 00 6.". .s.
74 00 61 00 6E 00 64 00 t.a.n.d.
61 00 6C 00 6F 00 6E 00 a.l.o.n.
...

Receiving the messages from the queue already works, but somehow the format is wrong because I get this Runtime Exception "Invalid Operation Exception: Cannot deserialize the message passed as an argument. Cannot recognize the serialization format."

I am using this code to read the messages:

public MainWindow()
{
    InitializeComponent();
    mqCustomerData = new MessageQueue(@".\private$\customerData");
    mqCustomerData.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
    mqCustomerData.ReceiveCompleted += new ReceiveCompletedEventHandler(mqCustomerData_ReceiveCompleted);
    mqCustomerData.BeginReceive(new System.TimeSpan(0, 0, 0, 30));
}

private void mqCustomerData_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e)
{
    Message m = new Message();
    m.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) });
    m = mqCustomerData.EndReceive(e.AsyncResult);
    string text = (string)m.Body;
}

I've searched for the problem but not found a useful solution, only found postings of other users experiencing the same problem, like here: http://www.webmasterworld.com/microsoft_asp_net/4119362.htm

I hope someone of you out there can help me with this :)

Answer

sandunes90 picture sandunes90 · Apr 27, 2017

In competent_tech's answer, no overload for

Encoding.Unicode.GetString(m.Body);

takes a string argument.

If this is the approach that you want to use, you need to convert the string to a byte array -

byte[] arr;
    using(MemoryStream ms = new MemoryStream())
                    {
                        m.BodyStream.Position = 0;
                        m.BodyStream.CopyTo(ms);
                        arr =  ms.ToArray();
                    }



     string s = Encoding.Unicode.GetString(arr, 0, arr.Length);