Serializing a Binding object - TimeSpan serialization error.

Tags: .NET, WinFX

Seeing as our project is all distributed and stuff, with various services possibly running on different servers, we wanted to have the whole service address business be flexible, and not rely on hardcoded values in app.config files.
We have a Configuration service, which is the only hardcoded address, and it can return the address for any given service.

The item we're using here is my own ServiceAddress object, which contains an EndpointAddress object and a Binding object for a given service. This way we can easily have a service switch from TCP to HTTP binding if necessary without redeploying. All is well.

The problem is that this configuration is stored on the Config server as an XML file with the ServiceAddress object serialized to XML. This means that the Binding object is also serialized to XML, and there lies the problem - the TimeSpan structure in .NET 2.0 cannot be serialized to XML. It loses all data and becomes an empty node, recreated as a 0-length TimeSpan when deserialized.
Since the Binding class has several TimeSpan properties for the timeout values, my service agents timeout immediately when attempting to contact the service.

Apparently the TimeSpan problem is a well-known one (here, there and everywhere), but the common workaround (of adding a new property with the TimeSpan's Ticks value) isn't really feasible a WinFX framework class.

I can extract and store the values manually during the serialization phase, but that seems ridiculously inelegant.
Another idea is to store the configuration files in the same format as they are defined in the app.config, and use the ClientSection class from System.ServiceModel.Configuration namespace to save and load the data. This is probably more complicated since I don't know if I can generate a <client> section from a Binding object. This means I can only read the configuration, not write to it from within my program.

Anyone have any other ideas?

3 Comments

  • Brad said

    You could ToString() it and then TimeSpan.Parse() it back. I don't understand why it isn't "Serializable" (especially since it can be so easily converted to and from a string).

  • AvnerK said

    ToString() is one solution, as is getting the Ticks and deserializing from that. This only works, however, if it's my own objects I'm serializing. If it's a framework object that's holding the TimeSpan, like it is in my case, I'm plain out of luck. :(

  • Dmytro said

    How did you solve this problem? What about using SoapSerializer instead of XmlSerializer? Do you have some other cases and issues regarding Configuration service solution? I plan to implement something like that..

Comments have been disabled for this content.