How can I use values of custom type in ConfigurationSection?

273 Views Asked by At

Let's say I have type Point2D (this is example), how can I use this type with ConfigurationSection -- in other words, what methods I have to implement in order value of my type be created from string.

One way would be to provide TypeConverter, is there another way? Without introducing extra types, solely within my custom type (in this example Point2D)?

Another way, but it is more a trick, would be for example having properties x and y of know type int, and then provide creator property to get Point2D -- I don't want to go that path.

Update: Example as requested:

public sealed class MyConfig : ConfigurationSection
{
    [ConfigurationProperty("LeftPoint", IsRequired = true),
        TypeConverter(typeof(Point2DTypeConverter))]
    public Point2D LeftPoint
    {
        get { return (Point2D )this["LeftPoint"]; }
        set { this["LeftPoint"] = value; }
    }

    ...
}

as you can see I use type converter for Point2D and it works. No problem. However I wonder if it would be possible to do conversion (parsing really from string) inside my type Point2D so I could remove entire converter (not as attribute tag, but completely).

2

There are 2 best solutions below

0
Evk On BEST ANSWER

TypeConverter is required in one form or another for ConfigurationProperty. If you don't provide one - it will look for it with TypeDescriptor.GetConverter if necessary. For that to work your type itself should be decorated with TypeConverter attribute, so you cannot get rid of it this way (though you can move responsibility of conversion to the type itself). You can also use generic TypeConverter, but for that you need to pass target type to it which is not possible using ConfigurationProperty attribute (but is possible if you configure your properties manually, without using attributes). All in all - there is always TypeConverter involved.

4
Adam Vincent On

Since it's a solid requirement, I would suggest using Newtonsoft.Json to convert to and from a string.

string MyPoint = Json.Serialize(MyPointObject)

Point2d MyPoint = Json.Deserialize(ConfigurationSection..)

You also may abstract your serialization logic by creating custom ConfigurationSections as explained here: How:To Create Custom ConfigurationSections