How to serialize type derived from ConfigurationSection with NetDataContractSerializer

310 Views Asked by At

I wrote my type derived from ConfigurationSection tagged all properties with DataMember and class with DataContract, however program crashes stating I cannot inherit my type from a type that is not marked with DataContract.

So how could I use this serializer with ConfigurationSection?

[DataContract]
public sealed class MyConfig : ConfigurationSection
{
    [DataMember]
    [ConfigurationProperty("ConnectionTimeout", DefaultValue = 1000)]
    public int ConnectionTimeout
    {
        get { return (int)this["ConnectionTimeout"]; }
        set { this["ConnectionTimeout"] = value; }
    }
    ... // other values
}
2

There are 2 best solutions below

0
On BEST ANSWER

There is another way -- instead of relying on automatic serialization, write your custom serialization manually. Since NetDataContractSerializer supports it, you can end up with just single type with 2 additional methods (more precisely: extra method for serializing and constructor for deserializing).

As for example see the post: When using ISerializable with DataContractSerializer, how do I stop the serializer from outputting type information?

3
On

Well I guess if you cant use the serializer with non data contract class than maybe you should separate data member properties into another class which will aggregated in your ConfigurationSection:

[DataContract]
public sealed class CustomConfig
{
   [DataMember]
    public int ConnectionTimeout {get;set;}
}

public sealed class MyConfig : ConfigurationSection
{
    private CustomConfig _customCfg = new  CustomConfig(){ConnectionTimeout = this.ConnectionTimeout};

    [ConfigurationProperty("ConnectionTimeout", DefaultValue = 1000)]
    public int ConnectionTimeout
    {
        get { return (int)this["ConnectionTimeout"]; }
        set { _customCfg.ConnectionTimeout = value;this["ConnectionTimeout"] = value; }
    }
    ... // other values
}

Than you can serialize CustomConfig instance with your serializer