Tutorial :Property default values using Properties.Settings.Default



Question:

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;


Solution:1

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


Solution:2

@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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »