Search This Blog

Wednesday, July 8, 2015

Accessing AppSettings in "unconventional" ways

I just learned 2 things about accessing the AppSettings node in a configuration file in a VS project:
  1. The framework provides a AppSettingsReader, not widespread in the community, that retrieves settings from the AppSettings configuration node, with some fluffing-behind-the-scenes (which I do not know what) Well, about the "fluffing"... question is what sort of fluffing is being done there, indeed... if you are wondering what's the use of a method that asks for the type of a value and nevertheless returns an object instead of a type-casted value... I raised this question here.
  2. Seems you can store app setting keys in whatever language you want. I tried storing in Hebrew and they are all retrieved without problems.
In the end, here is my version of the AppSettingsReader I think the framework should provide:

    public class Utils
    {
        AppSettingsReader _appSettingsReader;

        public Utils()
        {
            _appSettingsReader = new AppSettingsReader();
        }

        public T GetAppSettingValue<T>(string key, T defaultValue = default(T))
        {
            object value = _appSettingsReader.GetValue(key, typeof(T));
            T castedValue;
            try
            {
                castedValue = (T) Convert.ChangeType(value, typeof(T));
            }

            catch (Exception)
            {
                castedValue = defaultValue;
            }

            return castedValue;
        }

        public string GetAppSetting(string key)
        {
            return GetAppSettingValue<string>(key);
        }
    }

No comments:

Post a Comment