Click here to Skip to main content
13,195,379 members (66,409 online)
Click here to Skip to main content
Add your own
alternative version


63 bookmarked
Posted 20 Oct 2008

Serialization in Windows Communication Foundation

, 4 Nov 2008
Rate this:
Please Sign up or sign in to vote.
It describes about serialization and message encoding in Windows Communication Foundation.


In most scenarios, when we design a service, we create a service contract and data contracts for the types used in the service. We let the service description be generated by the service contract, and we won’t ever have to look at the underlying XML, but sometimes, things don’t go that well in situations like preexisting types which implement SerializableAttribute and ISerializable, mapping an incoming message to types which are not serializable or which don’t match the predefined schema.

Internally, WCF represents all the messages with the Message class which is defined in the System.ServiceModel.Channels namespace. The Message class generate a SOAP envelop which consists of a message header and a message body. The message body contains the payload. The Message class provides an interface to interact with the message body or the message header.

The most common way of serialization in a WCF service is to mark the type with the DataContract attribute and mark each member which is to be serialized with the DataMember attribute.


The reader should be familiar with WCF, and how to create a WCF service and data contracts. The reader should also be aware of web services.

Types that support serialization

  • Types marked with DataContractAttribute or CollectionDataContractAttribute.
  • Types decorated with SerializableAttribute which can optionally implement the ISerializable or IXmlSerializable interface.
  • MessageContract decorated with MessageContractAttribute and containing the data contracts or the serializable types as header or body.
  • We can include any of these types, but the resulting message format will change based on the choice of the serializer.

There are two types of serializers: DataContractSerializer and XmlSerializer. By default, WCF uses DataContractSerializer for message serialization. Here are the differences between both the serializers.

  • In the case of DataContract, the DataContractSerializer serializes the fields marked with the DataMember attribute (irrespective of public or private), while XmlSerializer serializes only public properties and fields.
  • In the case of SerializableAttribute, the DataContractSerializer serializes all fields, while XmlSerializer serializes only the public fields.
  • In the case of the IXmlserializable interface, we provide the schema and control the serialization.
  • In the case of MessageContract, the DataContractSerializer serializes members marked with the header or body attribute, while XmlSerializer serializes only the public properties or fields.
  • In the case of DataContractSerializer, constructors are not called during deserialization. However, if you need to perform initialization, DataContractSerializer supports the [OnDeserializing], [OnDeserialized], [OnSerializing], and [OnSerialized] callbacks that were also supported on the Binary/SoapFormatter classes.

Message encoding

There exists two types of encoding, Document/literal and RPC. Actually, they are two programming models, one is the RPC programming model and the other is the Message Passing programming model. One programming model says that if you are talking to a service, you should always explicitly form a message and use explicit message-passing infrastructure to send the message to the service and, optionally, to receive the response. The following is an example of a potential implementation of such a mechanism (from the caller's perspective):

Channel chan = new ChannelFactory.CreateChannel(endpointAddress);
ActionInvocationMessage msg = new ActionInvocationMessage();
msg.Action = "SayHello";
msg.Parameters.Add(new StringParameter("Forename", "Rich"));
msg.Parameters.Add(new StringParameter("Surname", "Turner"));
Console.WriteLine(chan.SendMessageSync(msg, new SayHelloCallback(HandleResponse)));

The other camp aims to simplify the developer experience by reusing development constructs in wide use today, that results in code such as the following:

HelloWorldProxy proxy = new HelloWorldProxy(endpointAddress);
Console.WriteLine(proxy.SayHello("Rich", "Turner"));

In both the DataContractSerializer and the XmlSerializer, default the value of style is document/literal format, but we can use RPC encoding using the OperationFormatStyle enumeration in the event you need it. Each serializer has a style property based on the enumeration, and can be set to one of its two elements, Document and RPC.


We can use the RPC style like this:

     public interface IRPCStyleTest


We can support the RPC style in the case of XmlSerializer like this:

     public interface IRPCStyleTest


Actually, there exists two contracts when discussing .NET types in the context of serialization. First is the .NET contract which has properties, methods, and constructors, and the other is the contract which has the serializable properties and which would be exposed to the word. Each serializer comes with some algorithms which define the mapping details, and includes attributes that let us customize the mapping. This mapping is stored with the metadata which serializers can access at runtime and decide which property to serialize.

There exists an inbuilt tool (svc.exe) for moving between these contract representations. We can use xsd.exe while working with XmlSerializer. Svc.exe can generate the .NET data type with all the attributes from the XML schema definition. If we pass a .NET assembly to svc.exe, it will automatically generate all the types which support serialization. So, we can write the data contracts in either XML schema or in .NET code.

Windows Communication Foundation lets us specify the encoding to be used. Serialization defines how the .NET object maps to XML, while Encoding defines how the XML is written out to a stream of bytes. WCF supports three types of encoding: text, binary, and message transmission optimization mechanism (MTOM). We can also add custom encoding.

If you represent the same logical data by the three encodings, the stream will be totally different, but they all represent the same logical data. Encoding isn’t considered to be part of the service contract, but it is the configuration entry. We can change it dynamically, and we can control it by endpoint binding. Different kinds of encoding are used in different types of word scenarios. If interoperability is a concern, then text type encoding is used, while if performance is the concern, then binary encoding can be used.

When WCF creates a message at runtime, it chooses the serializer based on the service contract, and selects the encoding based on the binding configuration. Let’s see how this is accomplished. We can take the following type for understanding the serializers:

public class Name
    public string firstName;
    public string middlename;
    public string lastName;


We can use the following method to generate the serialized stream from DataContractSerializer:

public static void SerializeClass()
    Name name = new Name { firstName = "John", 
                middlename = "Fuma", lastName = "last" };
    using (Message message = Message.CreateMessage(MessageVersion.Soap11WSAddressing10,
        "", name,
        new DataContractSerializer(typeof(Name))))
        using (FileStream fs = new FileStream("binary.bin", FileMode.Create))
            using (XmlDictionaryWriter writer = 


The CreateMessage method’s last parameter specifies the serializer. The serializer controls how the message body has the Name object as XML. The writer determines which encoding will be used to write the message out to the byte stream. XmlDictionaryWriter and XmlDictionaryReader can be used to read and write the type in any encoding (text, binary, MTOM).

Here is the generated file view in Visual Studio:

Visual Studio view of the file.

The following method can be used to generate the Name type again from the bin file. We can use XmlDictionaryReader and the corresponding decoder to do the reverse engineering, and get the original message.

public static void ReadSerializeClass()
    using (FileStream fs = File.OpenRead("binary.bin"))
        using (XmlDictionaryReader reader = 
          XmlDictionaryReader.CreateBinaryReader(fs, XmlDictionaryReaderQuotas.Max))
            using (Message message = Message.CreateMessage(
                reader, 1024, MessageVersion.Soap11WSAddressing10))
                // deserialize Person object from XML
                Name name = message.GetBody<name />(
                    new DataContractSerializer(typeof(Name)));

In case we don’t want to read the XML infoset directly, we can call GetReaderAtBodyContents instead of GetBody, which returns the XmlReader and reads the specific elements.


XmlSerializer is quite an old technology which is used in web services. Windows Communication Foundation supports it for backwards compatibility. I am not going to discuss a lot about it as there are a lot of articles about it available already. Here is the sample code which serializes the same Name object. We can see that it includes the middle name too as middle name is the public property.

Serialization method:

public static void WriteNameXmlSerializer()
    Name name = new Name { firstName = "John", 
                middlename = "Fuma", lastName = "last" };

    using (FileStream fs = new FileStream("Name.xml", FileMode.Create))
    using (XmlDictionaryWriter writer =
        XmlSerializer serializer = new XmlSerializer(typeof(Name));
        serializer.Serialize(writer, name);

Serialized stream:

<Name xmlns:xsi="" 


Deserialization method:

public static void ReadNameXmlSerializer()
    using (FileStream fs = new FileStream("Name.xml", FileMode.Open))
    using (XmlDictionaryReader reader =
           XmlDictionaryReader.CreateTextReader(fs, XmlDictionaryReaderQuotas.Max))
        XmlSerializer serializer = new XmlSerializer(typeof(Name));
        Name person = (Name)serializer.Deserialize(reader);


DataContractSerializer has two modes: SharedContract and SharedType. The modes reflect whether you want to share the schema contract across the wire or the .NET type information.

In general, sharing schema contract is the preferred and recommended approach, as it loosens the coupling across the wire, but WCF still wants to support .NET Remoting style applications where maintaining type across the wire is important. WCF spilts both the modes into separate classes, so now, WCF has DataContractSerializer (SharedContract) and NetDataContractSerializer (SharedType). Since WCF wants to encourage DataContractSerializer, it is the default serializer.

NetDataContractSerializer supports the same mapping algorithm and the same customization attributes, but in the case of NetDataContractSerializer, type information is not required ahead of time as in DataContractSerializer. We can see it from the following code:

// no type specified
NetDataContractSerializer serializer = new NetDataContractSerializer();
serializer.WriteObject(writer, p);

We can use the following method to serialize the Name class:

public static void SerializeClass()
    Name name = new Name { firstName = "John", middlename = "Fuma", lastName = "last" };
    NetDataContractSerializer netData = new NetDataContractSerializer();
    using (FileStream fs = new FileStream("NetData.xml", FileMode.Create))
        netData.Serialize(fs, name);

Here is the serialized stream. It contains the type information, so there is no need for specifying the type while doing the deserialization.

<Name z:Id="1" z:Type="HelloIndigo.Name" z:Assembly="HelloIndigo,
      Version=, Culture=neutral, PublicKeyToken=null" 



  <firstName z:Id="2">John</firstName>
  <lastName z:Id="3">last</lastName>

Following are some precautions that we have to take while doing the serilalization:

  • When serializing types that use inheritance, all the types in the hierarchy should be serializable either via the DataContract or the Serializable attribute.
  • WCF also provide a KnowType attribute which can be used to substitute the type which serializers will recognize at runtime. This lets us specify the Serializable attribute to some base type and send some derived type.
  • We can use IDataContractSurrogate in case we find that there is some property which is not serializable. We can implement this interface, and the serializer will call it while doing the serialization.


Windows Communication Foundation takes care of everything, but it is important to understand how each serializer works and which one is the best on a particular scenario. You should use DataContractSerializer whenever possible in WCF. It provides interoperability. NetDataContractSerializer should be used when you need type fidelity across the wire. You should user XmlSerializer when you need backwards compatibility with ASMX pages, or you are starting with the existing types which don’t follow the DataContract rules.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer Microsoft India
India India
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMax Size Pin
josephpotgieter27-Oct-08 19:48
memberjosephpotgieter27-Oct-08 19:48 
GeneralRe: Max Size Pin
Anil_gupta28-Oct-08 8:17
memberAnil_gupta28-Oct-08 8:17 
Generalxml encoding Pin
jofol20-Oct-08 8:38
memberjofol20-Oct-08 8:38 
AnswerRe: xml encoding Pin
Anil_gupta22-Oct-08 3:12
memberAnil_gupta22-Oct-08 3:12 
I tried the same and it's working at my end. Here is the xml which I got from the trace viewer. I am able to see the characters at the client side.

<E2ETraceEvent xmlns="">
<System xmlns="">
<SubType Name="Information">0</SubType>
<TimeCreated SystemTime="2008-10-22T12:57:10.8432405Z" />
<Source Name="System.ServiceModel.MessageLogging" />
<Correlation ActivityID="{1b97ff2c-1868-421e-a3fd-5720c3e31237}" />
<Execution ProcessName="HttpWithXmlSerializer.vshost" ProcessID="6272" ThreadID="11" />
<Channel />
<MessageLogTraceRecord Time="2008-10-22T18:27:10.8432405+05:30" Source="TransportSend" Type="System.ServiceModel.Dispatcher.OperationFormatter+OperationFormatterMessage" xmlns="">
<s:Envelope xmlns:s="">
<ActivityId CorrelationId="77ac07fa-fe6a-497e-9e1f-7e88396ceff0" xmlns="">1b97ff2c-1868-421e-a3fd-5720c3e31237</ActivityId>
<ReturnNameResponse xmlns="">
<ReturnNameResult xmlns:a="" xmlns:i="">
<a:listString xmlns:b="">

Here is the object which I sent from the server.

public class Name
public string firstName;
public string middleName;
public string lastName;
public List<string> listString;

List<string> list = new List<string>();
Name obj = new Name { firstName = "øöåæâ", lastName = "last", middleName = "middle",listString = list};
return obj;

Anil Kumar Gupta

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171019.1 | Last Updated 4 Nov 2008
Article Copyright 2008 by Anil_gupta
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid