tags:

views:

2460

answers:

2

I am using .Net 2 and the normal way to store my settings. I store my custom object serialized to xml. I am trying to retrieve the default value of the property (but without reseting other properties). I use:

ValuationInput valuationInput = (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue;

But it seems to return a string instead of ValuationInput and it throws an exception.

I made a quick hack, which works fine:

string valuationInputStr = (string) 
Settings.Default.Properties["ValuationInput"].DefaultValue;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValuationInput));
            ValuationInput valuationInput = (ValuationInput) xmlSerializer.Deserialize(new StringReader(valuationInputStr));

But this is really ugly - when I use all the tool to define a strongly typed setting, I don't want to serialize the default value myself, I would like to read it the same way as I read the current value: ValuationInput valuationInput = Settings.Default.ValuationInput;

+2  A: 

At some point, something, somewhere is going to have to use Xml Deserialization, whether it is you or a wrapper inside the settings class. You could always abstract it away in a method to remove the "ugly" code from your business logic.

public static T FromXml<T>(string xml)
{
    XmlSerializer xmlser = new XmlSerializer(typeof(T));
    using (System.IO.StringReader sr = new System.IO.StringReader(xml))
    {
        return (T)xmlser.Deserialize(sr);
    }
}

http://www.vonsharp.net/PutDownTheXmlNodeAndStepAwayFromTheStringBuilder.aspx

viggity
+2  A: 

@Grzenio,

Why don't you use your object type directly? You can set type of your setting on Project Properties->Settings tab. You can select your type by clicking on Browse in drop down for Type column.

Citation from MSDN:

Application settings can be stored as any data type that is XML serializable or has a TypeConverter that implements ToString/FromString

That way you can have strongly typed settings, i.e. (ValuationInput) Settings.Default.Properties["ValuationInput"].DefaultValue; will return an object instead of string.

aku