lundi 3 octobre 2016

Moving app.config settings to db and using reflection to determine value type

As my application has grown, my list of settings in the app.config file has as well. I have decided to move these setting to a table in my SQLDB to be able to track them and give me a way to modify the settings from a admin site. I ran into an issue where I am trying to store the setting value type in the table and then use it to change the value property to the type stored. For instance I have quite a few TimeSpan defined. In the SQL table the data would look like this.

guid    settingName     settingValue    settingType
936767f5-63b5-4844-9991-29f6f92c53f2    SMTimeStart    12:00:00    TimeSpan

Im trying to use the following code to pull the settings and return it in the correct type.

    public class SettingDataValue
    {
        public Guid guid { get; set; }
        public string SettingName { get; set; }
        public string SettingValue { get; set; }
        public string SettingType { get; set; }


    }
    public static dynamic getSettingFromDB(string name)
    {
        SettingDataValue s = new SettingDataValue();
        using (IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString), commandTimeout = null)
        {
            s = _db.Query<SettingDataValue>("Select Guid, SettingName, SettingValue ,SettingType from SiteSettings where settingName = '" + name + "'").SingleOrDefault();
        }
        PropertyInfo propertyInfo = s.GetType().GetProperty(s.SettingType);
        propertyInfo.SetValue(s, Convert.ChangeType(s.SettingValue, propertyInfo.PropertyType), null);

        return s.SettingValue;
    }

However when I run this I get a null reference exception on the

propertyInfo.SetValue(s, Convert.ChangeType(s.SettingValue, propertyInfo.PropertyType), null);

I know the query works when I test it and watch it with the sql profiler. Any thoughts or suggestions?





Aucun commentaire:

Enregistrer un commentaire