stackoverflowuser
stackoverflowuser

Reputation: 22380

How to serialize WCF message using DataContractSerializer?

I am trying to serialize WCF message using DataContractSerializer to get the message size (without using service trace viewer). Following is the code snippet:

public void BeforeSendReply(ref Message reply, object correlationState)
        {
            byte[] bytes = null;
            var messageBuffer = reply.CreateBufferedCopy(Int32.MaxValue);
            var message = messageBuffer.CreateMessage();
            var dcs = new DataContractSerializer(typeof(Message));
            using (var ms = new MemoryStream())
            {
                dcs.WriteObject(ms, message);
                bytes = ms.ToArray();
                Console.WriteLine(String.Format("Message size = {0}", bytes.Count()));
            }
        }

On doing so it raises the following exception:

Type 'System.ServiceModel.Channels.BodyWriterMessage' cannot be serialized. Cons ider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the typ e is a collection, consider marking it with the CollectionDataContractAttribute.

What can be done?

Upvotes: 2

Views: 2531

Answers (2)

Hoop Somuah
Hoop Somuah

Reputation: 56

The Message class is not a data-contract type or an Xml Serializer type. WCF special cases it. To find the length, your code shoudl look more like this:

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        var messageBuffer = reply.CreateBufferedCopy(Int32.MaxValue);
        var message = messageBuffer.CreateMessage();

        using (var ms = new MemoryStream())
        {
            var xw = XmlWriter.Create(ms);
            message.WriteMessage(xw);
            Console.WriteLine(String.Format("Message size = {0}", ms.Length));
        }
    }

Upvotes: 1

Chris Dickson
Chris Dickson

Reputation: 12135

You can call WriteMessage(XmlWriter) on a Message instance in the Created state, if you need to serialize it.

Upvotes: 0

Related Questions