/// <summary> /// Loads the settings. /// </summary> public void LoadSettings() { // get all public instance properties of this class.. PropertyInfo[] propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // loop through the properties.. foreach (var propertyInfo in propertyInfos) { try // avoid crashes.. { // get the SettingAttribute class instance of the property.. var settingAttribute = (SettingAttribute)propertyInfo.GetCustomAttribute(typeof(SettingAttribute)); // only properties marked with the SettingAttribute will be handled.. if (settingAttribute == null) { continue; } // get the default value for the property.. object currentValue = propertyInfo.GetValue(this); // null values aren't taken into count.. if (currentValue == null) { continue; } // primitive types only need a string conversion.. if (settingAttribute.SettingType.IsPrimitive || settingAttribute.SettingType == typeof(string)) { propertyInfo.SetValue(this, Convert.ChangeType(Conflib[settingAttribute.SettingName, currentValue.ToString()], settingAttribute.SettingType)); } else // try to set the value via a type converter.. { var converter = GetMeATypeConverter(settingAttribute.SettingType); if (converter != null) { propertyInfo.SetValue(this, converter.ConvertFromString(Conflib[settingAttribute.SettingName, currentValue.ToString()])); } } } catch (Exception ex) { // inform of the exception.. ReportExceptionAction?.Invoke(ex); } } }
private void SettingsBase_PropertyChanged(object sender, PropertyChangedEventArgs e) { try // just try from the beginning.. { PropertyInfo propertyInfo = // first get the property info for the property.. GetType().GetProperty(e.PropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // get the property value.. object value = propertyInfo?.GetValue(this); // get the setting attribute value of the property.. if (propertyInfo != null) { SettingAttribute settingAttribute = (SettingAttribute)propertyInfo.GetCustomAttribute(typeof(SettingAttribute)); if (value != null && settingAttribute != null) { if (value.GetType().IsPrimitive || value is string) { Conflib[settingAttribute.SettingName] = (settingAttribute.Secure ? "SECURE:" : string.Empty) + value; } else // a type converted is needed for non-primitive types.. { // try to get a type converter for the type.. var converter = GetMeATypeConverter(value.GetType()); // set the value if the type converter was successfully gotten.. if (converter != null) { Conflib[settingAttribute.SettingName] = (settingAttribute.Secure ? "SECURE:" : string.Empty) + converter.ConvertToString(value); } } } } } catch (Exception ex) { // inform of the exception.. ReportExceptionAction?.Invoke(ex); } }