2009-05-23

Flexible Serializer Provider

This post is the first of a series.
Each post of this series will take the concept one step ahead.

Code sample download available here

What in this post?

this post will discuss the technique of writing reusable type that can be serialize both by Data Contract serialization and Xml serialization and be later deserialize by the other.

Why should we care about it?

  • This technique is the base line for following posts in this series which talk about serializing inherits generics list.
  • Some .NET technologies (like the compact framework) does not support Data Contract serialization, so it is needed in order to achieve reusable business entity.

How to write flexible serializable entity?

[DataContract(Namespace="http://…", Name="CompositeType")]
[XmlRoot(Namespace="http://…", ElementName="CompositeType")]
public class CompositeType {
[DataMember (Order = 1)]
[XmlElement (IsNullable = true, Order = 1)]
public string StringValue { get; set; }


[DataMember (Order = 2)]
[XmlElement (DataType = "base64Binary", Order = 2)]
public byte[] BytesValue{ get; set; }
}

Lets talk about it :)

  • The class should be decorated with both DataContract and XmlRoot attributes and it is important to set the namespace (otherwise you won’t be able to serialize with one technique and deserialize with the other)
  • Properties should be decorated with both DataMember and XmlElement attribute given correlated order

Summary

Simple scenarios can be adjust with little addition of xml serialization attribute to your data contract entities (remember to assign the namespace)

The sample code is available here

the following post will discuss how to serialize collections

Following Posts

Previous Posts

del.icio.us Tags:

No comments: