2009-05-23

Serialize generics list part 2

This post is the 3rd of series on serialization in WCF.

The post is taking the previous post concept one step ahead by wrapping the List<T> as serializable type

Downloads available here

Jump into the code

see the theory in the previous post

[XmlRoot (Namespace = "htp://...")]
public class GenListCustom<T>:List<T>,IXmlSerializable {
private static readonly string ITEM_ELEMENT_NAME=
typeof (T).Name;

XmlSchema IXmlSerializable.GetSchema() {
throw new NotImplementedException();
}

void IXmlSerializable.ReadXml(XmlReader reader){
var ser=new DataContractSerializer(typeof(T));

while(reader.Name == ITEM_ELEMENT_NAME){
var item = (T)ser.ReadObject(reader);
this.Add (item);
}
}

void IXmlSerializable.WriteXml ( XmlWriter writer ) {
var ser = new DataContractSerializer (typeof (T));

writer.WriteStartElement ("Items", "htp://...");
foreach (var item in this) {
ser.WriteObject (writer, item);
}
writer.WriteEndElement ();
}
}

Actually this class is identical to the class on our previous post with one exception, it use T instead of CompositeType.

WCF and generics collections

Unfortunately WCF does not always handling well generics collections of complex types (despite the fact that it can be serialized using Data Contract serialization).

In those case you may use the the technique of having the collection as composite type and using property decorated with DataMember attribute in order to serialize the collection (as discuss in Serialize generics list part 1)

Summary

I used post reuse pattern :-) leaving the theory in the previous post, but after reading the previous post I believe it’s kind of straight forward.

Downloads available here

Previous Posts

del.icio.us Tags:

No comments: