Tuesday, September 9, 2008

Working around DataContract serialization with existing .Net classes

I'm working on moving some existing code to WCF. The code was originally passed via remoting so I thought it would be a pretty straight forward move. Turns out that's not the case. I ran into an issue with properties defined as System.Object and WCF. The error message that was returned was telling me that the connection was forcibly closed by the host, which I'm finding out can really be interpreted as "There was a problem with the object you want". After tracking the problem for the better part of the day it came down to an issue with the properties which looked like this:

[DataContract]
public class ContractTest
{
[DataMember]
public int PropOne { get; set; }

[DataMember]
public object PropTwo { get; set; }

[DataMember]
public string PropThree { get; set; }

[DataMember]
public object PropFour { get; set; }
}





It turns out that the serialization of the data contract can be altered by using the XmlSerializer. This is really helpful when moving older code. So to fix the issue, I modified the class like this:



using System.ServiceModel;

[DataContract]
[XmlSerializerFormat]
public class ContractTest
{
[DataMember]
public int PropOne { get; set; }


public object PropTwo { get; set; }

[DataMember]
public string PropThree { get; set; }


public object PropFour { get; set; }
}

The XmlSerializer will serialize the public properties and the end result is that you can now pass the class through the service noramlly.

No comments: