views:

928

answers:

3

I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface

public interface IPreferencesBackend
{
    bool TryGet<T>(string key, out T value);
    bool TrySet<T>(string key, T value); 
}

At runtime, I can say something like:

My.Foo.Data data = new My.Foo.Data("blabla");
Pref pref = new Preferences();
pref.TrySet("foo.data", data); 
pref.Save();

My.Foo.Data date = new My.Foo.Data();
pref.TryGet("foo.data", out data);

I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array.

What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically.

[System.Configuration.UserScopedSettingAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.Configuration.DefaultSettingValueAttribute("2008-09-24")]
public global::System.DateTime DateTime {
   get {
        return ((global::System.DateTime)(this["DateTime"]));
       }
   set {
        this["DateTime"] = value;
       }
 }
+2  A: 

Phil Haack has a great article on Creating Custom Configuration Sections

Wayne
+1  A: 

That's all you get in a an ASCII text file - strings. :-)

However, you can encode the "value" strings to include a type parameter like:

< key="myParam" value="type, value" />

for example:

< key="payRate" value="money,85.79"/>

then have your app do the conversion ...

Ron

Ron Savage
+1  A: 

I found two great articles on codeproject.com that are explaining these issues in great detail.

Unraveling the Mysteries of .NET 2.0 Configuration http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx

User Settings Applied http://www.codeproject.com/KB/dotnet/user_settings.aspx?display=PrintAll&amp;fid=1286606&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2647446&amp;fr=26

gyurisc