WCF, XStream, Serialization Issues and Debugging

Maybe you are familiar with the XStream Serializer which was initially available for Java and ported later on to .NET. If you aren't - its worth checking out. Its a very simple XML serializer able to handle complex objects with cyclic dependencies. It has some minor issues though. If you are aware of them, you most probably won't shoot yourself into the foot. ... Yeah, most probably ... I did!

Lets take one step back. I've been consuming a method (lets call it GetFoo()) exposed over WCF Service by an ASP.NET Client. The method would look like this:

  1. public SomeComplexObject GetFoo(long id)
  2. {
  3. String xml = DAO.GetSerializedObjectById(id);
  4. return (SomeComplexObject) XStream.fromXML(xml);
  5. }

SomeComplexObject would be a class properly annotated with the DataContract and DataMember Attributes. Calling this Method over the WCF Service would bail out a generic error message on the ASP client, basically telling you that the remote side of the connection has quit abruptly.

I must admit that I am still new to the WCF / ASP.NET development so I had no clue where to look for the exception generated by the WCF layer. After hitting Google with this question, I have figured out how to use Microsoft Service Trace Viewer to investigate the SOAP Messages passed around- and more importantly the Exception which occured somewhere deep inside the WCF stack.

The Exception type has been "System.Runtime.Serialization.InvalidDataContractException" and basically said that ".xsdyn~SomeComplexObject" has not been annotated with the DataContract Attribute and thus could not be used in a WCF Call.

.xsdyn? It turns out that XStream will create a fake assembly and create a dynamic instance of the "SomeComplexObject" in case one would not provide a default constructor for the class to be deserialized. Gee! Thats dumb! I mean, not only the way of handing the lack of an default constructor, but also my own dumbness making this mistake.

To sum it up, if you are going to use XStream for .NET, pay attention to include a) the default constructor in each class you wish to deserialize, b) use protected and not private modifiers to class variables if you are going to derive from that class. Otherwise you will be missing the fields in the serialized output. It does not matter if the properties would be public or not.

Oh, and by the way... Setting up the WCF logging was fun. The trace log generated is pretty useful if you need to inspect the SOAP messages / headers and the call history. But if you just need to check the Exception generated by the WCF Stack - take a look into the Windows EventViewer - way more convenient!