public override bool Write(AppConfiguration config) { EncryptFields(config); lock (syncWriteLock) { // Load the config file into DOM parser XmlDocument Dom = new XmlDocument(); string configFile = ConfigurationFile; if (string.IsNullOrEmpty(configFile)) { configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; } try { Dom.Load(configFile); } catch { // Can't load the file - create an empty document string Xml = @"<?xml version='1.0'?> <configuration> </configuration>" ; Dom.LoadXml(Xml); } // Load up the Namespaces object so we can // reference the appropriate default namespace GetXmlNamespaceInfo(Dom); // Parse through each of hte properties of the properties Type typeWebConfig = config.GetType(); MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Public); string ConfigSection = "appSettings"; if (!string.IsNullOrEmpty(ConfigurationSection)) { ConfigSection = ConfigurationSection; } // make sure we're getting the latest values before we write ConfigurationManager.RefreshSection(ConfigSection); foreach (MemberInfo Field in Fields) { // Don't persist ErrorMessage property if (Field.Name == "ErrorMessage" || Field.Name == "Provider") { continue; } object rawValue = null; if (Field.MemberType == MemberTypes.Field) { rawValue = ((FieldInfo)Field).GetValue(config); } else if (Field.MemberType == MemberTypes.Property) { rawValue = ((PropertyInfo)Field).GetValue(config, null); } else { continue; } string value = TypedValueToString(rawValue, CultureInfo.InvariantCulture); if (value == "ILIST_TYPE") { var count = 0; foreach (var item in rawValue as IList) { value = TypedValueToString(item, CultureInfo.InvariantCulture); WriteConfigurationValue(Field.Name + ++count, value, Field, Dom, ConfigSection); } } else { WriteConfigurationValue(Field.Name, value, Field, Dom, ConfigSection); } } // for each try { // this will fail if permissions are not there Dom.Save(configFile); ConfigurationManager.RefreshSection(ConfigSection); } catch { return(false); } finally { DecryptFields(config); } } return(true); }
/// <summary> /// Reads configuration settings from the current configuration manager. /// Uses the internal APIs to write these values. /// </summary> /// <typeparam name="TAppConfiguration"></typeparam> /// <param name="config"></param> /// <returns></returns> public override bool Read(AppConfiguration config) { // Config reading from external files works a bit differently // so use a separate method to handle it if (!string.IsNullOrEmpty(ConfigurationFile)) { return(Read(config, ConfigurationFile)); } Type typeWebConfig = config.GetType(); MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.GetField); // Set a flag for missing fields // If we have any we'll need to write them out into .config bool missingFields = false; // Refresh the sections - req'd after write operations // sometimes sections don't want to re-read if (string.IsNullOrEmpty(ConfigurationSection)) { ConfigurationManager.RefreshSection("appSettings"); } else { ConfigurationManager.RefreshSection(ConfigurationSection); } NameValueCollection configManager; configManager = string.IsNullOrEmpty(ConfigurationSection) ? ConfigurationManager.AppSettings as NameValueCollection : ConfigurationManager.GetSection(ConfigurationSection) as NameValueCollection; if (configManager == null) { Write(config); return(true); } // Loop through all fields and properties foreach (MemberInfo Member in Fields) { FieldInfo field = null; PropertyInfo property = null; Type fieldType = null; if (Member.MemberType == MemberTypes.Field) { field = (FieldInfo)Member; fieldType = field.FieldType; } else if (Member.MemberType == MemberTypes.Property) { property = (PropertyInfo)Member; fieldType = property.PropertyType; } else { continue; } string fieldName = Member.Name.ToLower(); // Error Message is an internal public property if (fieldName == "errormessage" || fieldName == "provider") { continue; } if (!IsIList(fieldType)) { // Single value string value = configManager[fieldName]; if (value == null) { missingFields = true; continue; } try { // Assign the value to the property ReflectionUtils.SetPropertyEx(config, Member.Name, StringToTypedValue(value, fieldType, CultureInfo.InvariantCulture)); } catch { } } else { // List Value var list = Activator.CreateInstance(fieldType) as IList; var elType = fieldType.GetElementType(); if (elType == null) { var generic = fieldType.GetGenericArguments(); if (generic != null && generic.Length > 0) { elType = generic[0]; } } int count = 1; string value = string.Empty; while (value != null) { value = configManager[fieldName + count]; if (value == null) { break; } list.Add(StringToTypedValue(value, elType, CultureInfo.InvariantCulture)); count++; } try { ReflectionUtils.SetPropertyEx(config, Member.Name, list); } catch { } } } DecryptFields(config); // We have to write any missing keys if (missingFields) { Write(config); } return(true); }
/// <summary> /// Reads Configuration settings from an external file or explicitly from a file. /// Uses XML DOM to read values instead of using the native APIs. /// </summary> /// <typeparam name="TAppConfiguration"></typeparam> /// <param name="config">Configuration instance</param> /// <param name="filename">Filename to read from</param> /// <returns></returns> public override bool Read(AppConfiguration config, string filename) { Type typeWebConfig = config.GetType(); MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Public | BindingFlags.Instance); // Set a flag for missing fields // If we have any we'll need to write them out bool missingFields = false; XmlDocument Dom = new XmlDocument(); try { Dom.Load(filename); } catch { // Can't open or doesn't exist - so try to create it if (!Write(config)) { return(false); } // Now load again Dom.Load(filename); } // Retrieve XML Namespace information to assign default // Namespace explicitly. GetXmlNamespaceInfo(Dom); string ConfigSection = ConfigurationSection; if (ConfigSection == string.Empty) { ConfigSection = "appSettings"; } foreach (MemberInfo Member in Fields) { FieldInfo Field = null; PropertyInfo Property = null; Type FieldType = null; string TypeName = null; if (Member.MemberType == MemberTypes.Field) { Field = (FieldInfo)Member; FieldType = Field.FieldType; TypeName = Field.FieldType.Name.ToLower(); } else if (Member.MemberType == MemberTypes.Property) { Property = (PropertyInfo)Member; FieldType = Property.PropertyType; TypeName = Property.PropertyType.Name.ToLower(); } else { continue; } string Fieldname = Member.Name; if (Fieldname == "Provider" || Fieldname == "ErrorMessage") { continue; } XmlNode Section = Dom.DocumentElement.SelectSingleNode(XmlNamespacePrefix + ConfigSection, XmlNamespaces); if (Section == null) { Section = CreateConfigSection(Dom, ConfigurationSection); Dom.DocumentElement.AppendChild(Section); } string Value = GetNamedValueFromXml(Dom, Fieldname, ConfigSection); if (Value == null) { missingFields = true; continue; } // Assign the Property ReflectionUtils.SetPropertyEx(config, Fieldname, StringToTypedValue(Value, FieldType, CultureInfo.InvariantCulture)); } DecryptFields(config); // We have to write any missing keys if (missingFields) { Write(config); } return(true); }
/// <summary> /// Writes the configuration settings from a specific instance /// into the configuration store. /// </summary> /// <param name="config"></param> /// <returns></returns> public abstract bool Write(AppConfiguration config);
public override bool Write(AppConfiguration config) { SqlDataAccess data = new SqlDataAccess(ConnectionString, ProviderName); string sql = $"UPDATE [{Tablename}] SET ConfigData = @ConfigData WHERE id = {Key}"; string xml = WriteAsString(config); int result = 0; try { result = data.ExecuteNonQuery(sql, data.CreateParameter("@ConfigData", xml)); } catch { result = -1; } // try to create the table if (result == -1) { sql = String.Format( @"CREATE TABLE [{0}] ( [id] [int] , [ConfigData] [ntext] )", Tablename); try { result = data.ExecuteNonQuery(sql); if (result > -1) { result = 0; } } catch (Exception ex) { SetError(ex); return(false); } } // Check for missing record if (result == 0) { sql = "Insert [" + Tablename + "] (id,configdata) values (" + Key.ToString() + ",@ConfigData)"; try { result = data.ExecuteNonQuery(sql, data.CreateParameter("@ConfigData", xml)); } catch (Exception ex) { SetError(ex); return(false); } if (result == 0) { return(false); } } if (result < 0) { return(false); } return(true); }
public override bool Write(AppConfiguration config) { lock (syncWriteLock) { // Load the config file into DOM parser XmlDocument Dom = new XmlDocument(); string configFile = ConfigurationFile; if (string.IsNullOrEmpty(configFile)) { configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; } try { Dom.Load(configFile); } catch { // Can't load the file - create an empty document string Xml = @"<?xml version='1.0'?> <configuration> </configuration>" ; Dom.LoadXml(Xml); } // Load up the Namespaces object so we can // reference the appropriate default namespace GetXmlNamespaceInfo(Dom); // Parse through each of hte properties of the properties Type typeWebConfig = config.GetType(); MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Public); string fieldsToEncrypt = "," + PropertiesToEncrypt.ToLower() + ","; string ConfigSection = "appSettings"; if (!string.IsNullOrEmpty(ConfigurationSection)) { ConfigSection = ConfigurationSection; } ConfigurationManager.RefreshSection(ConfigSection); foreach (MemberInfo Field in Fields) { // If we can't find the key - write it out to the document string Value = null; object RawValue = null; if (Field.MemberType == MemberTypes.Field) { RawValue = ((FieldInfo)Field).GetValue(config); } else if (Field.MemberType == MemberTypes.Property) { RawValue = ((PropertyInfo)Field).GetValue(config, null); } else { continue; // not a property or field } // Don't persist ErrorMessage property if (Field.Name == "ErrorMessage" || Field.Name == "Provider") { continue; } Value = ReflectionUtils.TypedValueToString(RawValue, CultureInfo.InvariantCulture); // Encrypt the field if in list if (fieldsToEncrypt.IndexOf("," + Field.Name.ToLower() + ",") > -1) { Value = Encryption.EncryptString(Value, EncryptionKey); } XmlNode Node = Dom.DocumentElement.SelectSingleNode( XmlNamespacePrefix + ConfigSection + "/" + XmlNamespacePrefix + "add[@key='" + Field.Name + "']", XmlNamespaces); if (Node == null) { // Create the node and attributes and write it Node = Dom.CreateNode(XmlNodeType.Element, "add", Dom.DocumentElement.NamespaceURI); XmlAttribute Attr2 = Dom.CreateAttribute("key"); Attr2.Value = Field.Name; XmlAttribute Attr = Dom.CreateAttribute("value"); Attr.Value = Value; Node.Attributes.Append(Attr2); Node.Attributes.Append(Attr); XmlNode Parent = Dom.DocumentElement.SelectSingleNode( XmlNamespacePrefix + ConfigSection, XmlNamespaces); if (Parent == null) { Parent = CreateConfigSection(Dom, ConfigSection); } Parent.AppendChild(Node); } else { // just write the value into the attribute Node.Attributes.GetNamedItem("value").Value = Value; } string XML = Node.OuterXml; } // for each try { // this will fail if permissions are not there Dom.Save(configFile); ConfigurationManager.RefreshSection(ConfigSection); } catch { return(false); } } return(true); }
/// <summary> /// Reads configuration settings from the store into a passed /// instance of the configuration instance. /// </summary> /// <param name="config">Specific config settings class instance</param> /// <returns>true or false</returns> public abstract bool Read(AppConfiguration config);
/// <summary> /// Reads configuration settings from the current configuration manager. /// Uses the internal APIs to write these values. /// </summary> /// <typeparam name="TAppConfiguration"></typeparam> /// <param name="config"></param> /// <returns></returns> public override bool Read(AppConfiguration config) { // Config reading from external files works a bit differently // so use a separate method to handle it if (!string.IsNullOrEmpty(ConfigurationFile)) { return(Read(config, ConfigurationFile)); } Type typeWebConfig = config.GetType(); MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.GetField); // Set a flag for missing fields // If we have any we'll need to write them out into .config bool missingFields = false; string fieldsToEncrypt = "," + PropertiesToEncrypt.ToLower() + ","; // Refresh the sections - req'd after write operations // sometimes sections don't want to re-read if (string.IsNullOrEmpty(ConfigurationSection)) { ConfigurationManager.RefreshSection("appSettings"); } else { ConfigurationManager.RefreshSection(ConfigurationSection); } // Loop through all fields and properties foreach (MemberInfo Member in Fields) { string typeName = null; FieldInfo field = null; PropertyInfo property = null; Type fieldType = null; if (Member.MemberType == MemberTypes.Field) { field = (FieldInfo)Member; fieldType = field.FieldType; typeName = fieldType.Name.ToLower(); } else if (Member.MemberType == MemberTypes.Property) { property = (PropertyInfo)Member; fieldType = property.PropertyType; typeName = fieldType.Name.ToLower(); } else { continue; } string fieldName = Member.Name.ToLower(); // Error Message is an internal public property if (fieldName == "errormessage" || fieldName == "provider") { continue; } string value = null; if (string.IsNullOrEmpty(ConfigurationSection)) { value = ConfigurationManager.AppSettings[fieldName]; } else { NameValueCollection Values = ConfigurationManager.GetSection(ConfigurationSection) as NameValueCollection; if (Values != null) { value = Values[fieldName]; } } if (value == null) { missingFields = true; continue; } // If we're encrypting decrypt any field that are encyrpted if (value != string.Empty && fieldsToEncrypt.IndexOf("," + fieldName + ",") > -1) { value = Encryption.DecryptString(value, EncryptionKey); } try { // Assign the value to the property ReflectionUtils.SetPropertyEx(config, fieldName, ReflectionUtils.StringToTypedValue(value, fieldType, CultureInfo.InvariantCulture)); } catch {; } } // We have to write any missing keys if (missingFields) { Write(config); } return(true); }
/// <summary> /// Reads Configuration settings from an external file or explicitly from a file. /// Uses XML DOM to read values instead of using the native APIs. /// </summary> /// <param name="config">Configuration instance</param> /// <param name="filename">Filename to read from</param> /// <returns></returns> public override bool Read(AppConfiguration config, string filename) { Type typeWebConfig = config.GetType(); PropertyInfo[] properties = typeWebConfig.GetProperties(BindingFlags.Public | BindingFlags.Instance); // Set a flag for missing fields // If we have any we'll need to write them out bool missingFields = false; XmlDocument Dom = new XmlDocument(); try { Dom.Load(filename); } catch { // Can't open or doesn't exist - so try to create it if (!Write(config)) { return(false); } // Now load again Dom.Load(filename); } // Retrieve XML Namespace information to assign default // Namespace explicitly. GetXmlNamespaceInfo(Dom); string ConfigSection = ConfigurationSection; if (ConfigSection == string.Empty) { ConfigSection = "appSettings"; } foreach (var property in properties) { if (!property.CanWrite || Attribute.IsDefined(property, typeof(XmlIgnoreAttribute))) { continue; } Type fieldType = null; string typeName = null; fieldType = property.PropertyType; typeName = property.PropertyType.Name.ToLower(); string propertyName = property.Name; if (propertyName == "Provider" || propertyName == "ErrorMessage") { continue; } XmlNode Section = Dom.DocumentElement.SelectSingleNode(XmlNamespacePrefix + ConfigSection, XmlNamespaces); if (Section == null) { Section = CreateConfigSection(Dom, ConfigurationSection); Dom.DocumentElement.AppendChild(Section); } string Value = GetNamedValueFromXml(Dom, propertyName, ConfigSection); if (Value == null) { missingFields = true; continue; } // Assign the Property ReflectionUtils.SetPropertyEx(config, propertyName, StringToTypedValue(Value, fieldType, CultureInfo.InvariantCulture)); } DecryptFields(config); // We have to write any missing keys if (missingFields) { Write(config); } return(true); }
public override bool Write(AppConfiguration config) { #if NETFULL SqlDataAccess data = new SqlDataAccess(ConnectionString, ProviderName); #else SqlDataAccess data = new SqlDataAccess(ConnectionString, SqlClientFactory.Instance); #endif string sql = String.Format( "Update [{0}] set ConfigData=@ConfigData where id={1}", Tablename, Key); string xml = WriteAsString(config); int result = 0; try { result = data.ExecuteNonQuery(sql, data.CreateParameter("@ConfigData", xml)); } catch { result = -1; } // try to create the table if (result == -1) { sql = String.Format( @"CREATE TABLE [{0}] ( [id] [int] , [ConfigData] [ntext] )", Tablename); try { result = data.ExecuteNonQuery(sql); if (result > -1) { result = 0; } } catch (Exception ex) { SetError(ex); return(false); } } // Check for missing record if (result == 0) { sql = "Insert [" + Tablename + "] (id,configdata) values (" + Key.ToString() + ",@ConfigData)"; try { result = data.ExecuteNonQuery(sql, data.CreateParameter("@ConfigData", xml)); } catch (Exception ex) { SetError(ex); return(false); } if (result == 0) { return(false); } } if (result < 0) { return(false); } return(true); }
/// <summary> /// Not supported for StringConfiguration /// </summary> /// <param name="config"></param> /// <returns></returns> public override bool Write(AppConfiguration config) { throw new NotImplementedException(); }
/// <summary> /// Reads configuration information into config from InitialStringData /// </summary> /// <param name="config"></param> /// <returns></returns> public override bool Read(AppConfiguration config) { return(Read(config, InitialStringData)); }