using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration.Internal; using System.Configuration.Provider; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Unity; [assembly: ComCompatibleVersion(1, 0, 3300, 0)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.Configuration.dll")] [assembly: AssemblyDescription("System.Configuration.dll")] [assembly: AssemblyDefaultAlias("System.Configuration.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: CompilationRelaxations(8)] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyDelaySign(true)] [assembly: InternalsVisibleTo("System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: AssemblyVersion("4.0.0.0")] internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal sealed class Locale { private Locale() { } public static string GetText(string msg) { return msg; } public static string GetText(string fmt, params object[] args) { return string.Format(fmt, args); } } internal class ConfigXmlTextReader : XmlTextReader, IConfigErrorInfo { private readonly string fileName; public string Filename => fileName; public ConfigXmlTextReader(Stream s, string fileName) : base(s) { if (fileName == null) { throw new ArgumentNullException("fileName"); } this.fileName = fileName; } public ConfigXmlTextReader(TextReader input, string fileName) : base(input) { if (fileName == null) { throw new ArgumentNullException("fileName"); } this.fileName = fileName; } } namespace System { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoTODOAttribute : Attribute { private string comment; public string Comment => comment; public MonoTODOAttribute() { } public MonoTODOAttribute(string comment) { this.comment = comment; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoDocumentationNoteAttribute : MonoTODOAttribute { public MonoDocumentationNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoExtensionAttribute : MonoTODOAttribute { public MonoExtensionAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoInternalNoteAttribute : MonoTODOAttribute { public MonoInternalNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoLimitationAttribute : MonoTODOAttribute { public MonoLimitationAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoNotSupportedAttribute : MonoTODOAttribute { public MonoNotSupportedAttribute(string comment) : base(comment) { } } } namespace System.Configuration { public sealed class AppSettingsSection : ConfigurationSection { private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propFile; private static readonly ConfigurationProperty _propSettings; [ConfigurationProperty("file", DefaultValue = "")] public string File { get { return (string)base[_propFile]; } set { base[_propFile] = value; } } [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)] public KeyValueConfigurationCollection Settings => (KeyValueConfigurationCollection)base[_propSettings]; protected internal override ConfigurationPropertyCollection Properties => _properties; static AppSettingsSection() { _propFile = new ConfigurationProperty("file", typeof(string), "", new StringConverter(), null, ConfigurationPropertyOptions.None); _propSettings = new ConfigurationProperty("", typeof(KeyValueConfigurationCollection), null, null, null, ConfigurationPropertyOptions.IsDefaultCollection); _properties = new ConfigurationPropertyCollection(); _properties.Add(_propFile); _properties.Add(_propSettings); } protected internal override bool IsModified() { return Settings.IsModified(); } [MonoInternalNote("file path? do we use a System.Configuration api for opening it? do we keep it open? do we open it writable?")] protected internal override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) { base.DeserializeElement(reader, serializeCollectionKey); if (!(File != "")) { return; } try { string text = File; if (!Path.IsPathRooted(text)) { text = Path.Combine(Path.GetDirectoryName(base.Configuration.FilePath), text); } FileStream fileStream = System.IO.File.OpenRead(text); XmlReader reader2 = (XmlReader)(object)new ConfigXmlTextReader(fileStream, text); base.DeserializeElement(reader2, serializeCollectionKey); fileStream.Close(); } catch { } } protected internal override void Reset(ConfigurationElement parentSection) { if (parentSection is AppSettingsSection appSettingsSection) { Settings.Reset(appSettingsSection.Settings); } } [MonoTODO] protected internal override string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode) { if (File == "") { return base.SerializeSection(parentElement, name, saveMode); } throw new NotImplementedException(); } protected internal override object GetRuntimeObject() { KeyValueInternalCollection keyValueInternalCollection = new KeyValueInternalCollection(); string[] allKeys = Settings.AllKeys; foreach (string key in allKeys) { KeyValueConfigurationElement keyValueConfigurationElement = Settings[key]; keyValueInternalCollection.Add(keyValueConfigurationElement.Key, keyValueConfigurationElement.Value); } if (!ConfigurationManager.ConfigurationSystem.SupportsUserConfig) { keyValueInternalCollection.SetReadOnly(); } return keyValueInternalCollection; } } public sealed class CallbackValidator : ConfigurationValidatorBase { private Type type; private ValidatorCallback callback; public CallbackValidator(Type type, ValidatorCallback callback) { this.type = type; this.callback = callback; } public override bool CanValidate(Type type) { return type == this.type; } public override void Validate(object value) { callback(value); } } [AttributeUsage(AttributeTargets.Property)] public sealed class CallbackValidatorAttribute : ConfigurationValidatorAttribute { private string callbackMethodName = ""; private Type type; private ConfigurationValidatorBase instance; public string CallbackMethodName { get { return callbackMethodName; } set { callbackMethodName = value; instance = null; } } public Type Type { get { return type; } set { type = value; instance = null; } } public override ConfigurationValidatorBase ValidatorInstance => instance; } internal class ClientConfigurationSystem : IInternalConfigSystem { private Configuration cfg; private Configuration Configuration { get { if (cfg == null) { Assembly entryAssembly = Assembly.GetEntryAssembly(); try { cfg = ConfigurationManager.OpenExeConfigurationInternal(ConfigurationUserLevel.None, entryAssembly, null); } catch (Exception inner) { throw new ConfigurationErrorsException("Error Initializing the configuration system.", inner); } } return cfg; } } bool IInternalConfigSystem.SupportsUserConfig => false; object IInternalConfigSystem.GetSection(string configKey) { return Configuration.GetSection(configKey)?.GetRuntimeObject(); } void IInternalConfigSystem.RefreshConfig(string sectionName) { } } public sealed class CommaDelimitedStringCollection : StringCollection { private bool modified; private bool readOnly; private int originalStringHash; public bool IsModified { get { if (modified) { return true; } string text = ToString(); if (text == null) { return false; } return text.GetHashCode() != originalStringHash; } } public new bool IsReadOnly => readOnly; public new string this[int index] { get { return base[index]; } set { if (readOnly) { throw new ConfigurationErrorsException("The configuration is read only"); } base[index] = value; modified = true; } } public new void Add(string value) { if (readOnly) { throw new ConfigurationErrorsException("The configuration is read only"); } base.Add(value); modified = true; } public new void AddRange(string[] range) { if (readOnly) { throw new ConfigurationErrorsException("The configuration is read only"); } base.AddRange(range); modified = true; } public new void Clear() { if (readOnly) { throw new ConfigurationErrorsException("The configuration is read only"); } base.Clear(); modified = true; } public CommaDelimitedStringCollection Clone() { CommaDelimitedStringCollection commaDelimitedStringCollection = new CommaDelimitedStringCollection(); string[] array = new string[base.Count]; CopyTo(array, 0); commaDelimitedStringCollection.AddRange(array); commaDelimitedStringCollection.originalStringHash = originalStringHash; return commaDelimitedStringCollection; } public new void Insert(int index, string value) { if (readOnly) { throw new ConfigurationErrorsException("The configuration is read only"); } base.Insert(index, value); modified = true; } public new void Remove(string value) { if (readOnly) { throw new ConfigurationErrorsException("The configuration is read only"); } base.Remove(value); modified = true; } public void SetReadOnly() { readOnly = true; } public override string ToString() { if (base.Count == 0) { return null; } string[] array = new string[base.Count]; CopyTo(array, 0); return string.Join(",", array); } internal void UpdateStringHash() { string text = ToString(); if (text == null) { originalStringHash = 0; } else { originalStringHash = text.GetHashCode(); } } } public sealed class CommaDelimitedStringCollectionConverter : ConfigurationConverterBase { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { CommaDelimitedStringCollection commaDelimitedStringCollection = new CommaDelimitedStringCollection(); string[] array = ((string)data).Split(','); foreach (string text in array) { commaDelimitedStringCollection.Add(text.Trim()); } commaDelimitedStringCollection.UpdateStringHash(); return commaDelimitedStringCollection; } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value == null) { return null; } if (!typeof(StringCollection).IsAssignableFrom(value.GetType())) { throw new ArgumentException(); } return value.ToString(); } } internal class ConfigNameValueCollection : NameValueCollection { private bool modified; public bool IsModified => modified; public ConfigNameValueCollection() { } public ConfigNameValueCollection(ConfigNameValueCollection col) : base(col.Count, col) { } public void ResetModified() { modified = false; } public override void Set(string name, string value) { base.Set(name, value); modified = true; } } internal abstract class ConfigInfo { public string Name; public string TypeName; protected Type Type; private string streamName; public ConfigInfo Parent; public IInternalConfigHost ConfigHost; public string XPath { get { StringBuilder stringBuilder = new StringBuilder(Name); for (ConfigInfo parent = Parent; parent != null; parent = parent.Parent) { stringBuilder.Insert(0, parent.Name + "/"); } return stringBuilder.ToString(); } } public string StreamName { get { return streamName; } set { streamName = value; } } public virtual object CreateInstance() { if (Type == null) { Type = ConfigHost.GetConfigType(TypeName, throwOnError: true); } return Activator.CreateInstance(Type, nonPublic: true); } public abstract bool HasConfigContent(Configuration cfg); public abstract bool HasDataContent(Configuration cfg); protected void ThrowException(string text, XmlReader reader) { throw new ConfigurationErrorsException(text, reader); } public abstract void ReadConfig(Configuration cfg, string streamName, XmlReader reader); public abstract void WriteConfig(Configuration cfg, XmlWriter writer, ConfigurationSaveMode mode); public abstract void ReadData(Configuration config, XmlReader reader, bool overrideAllowed); public abstract void WriteData(Configuration config, XmlWriter writer, ConfigurationSaveMode mode); internal abstract void Merge(ConfigInfo data); internal abstract bool HasValues(Configuration config, ConfigurationSaveMode mode); internal abstract void ResetModified(Configuration config); } internal class ConfigurationXmlDocument : XmlDocument { public override XmlElement CreateElement(string prefix, string localName, string namespaceURI) { if (namespaceURI == "http://schemas.microsoft.com/.NetConfiguration/v2.0") { return ((XmlDocument)this).CreateElement(string.Empty, localName, string.Empty); } return ((XmlDocument)this).CreateElement(prefix, localName, namespaceURI); } } public sealed class Configuration { private Configuration parent; private Hashtable elementData; private string streamName; private ConfigurationSectionGroup rootSectionGroup; private ConfigurationLocationCollection locations; private SectionGroupInfo rootGroup; private IConfigSystem system; private bool hasFile; private string rootNamespace; private string configPath; private string locationConfigPath; private string locationSubPath; private ContextInformation evaluationContext; internal Configuration Parent { get { return parent; } set { parent = value; } } internal string FileName => streamName; internal IInternalConfigHost ConfigHost => system.Host; internal string LocationConfigPath => locationConfigPath; internal string ConfigPath => configPath; public AppSettingsSection AppSettings => (AppSettingsSection)GetSection("appSettings"); public ConnectionStringsSection ConnectionStrings => (ConnectionStringsSection)GetSection("connectionStrings"); public string FilePath { get { if (streamName == null && parent != null) { return parent.FilePath; } return streamName; } } public bool HasFile => hasFile; public ContextInformation EvaluationContext { get { if (evaluationContext == null) { object ctx = system.Host.CreateConfigurationContext(configPath, GetLocationSubPath()); evaluationContext = new ContextInformation(this, ctx); } return evaluationContext; } } public ConfigurationLocationCollection Locations { get { if (locations == null) { locations = new ConfigurationLocationCollection(); } return locations; } } public bool NamespaceDeclared { get { return rootNamespace != null; } set { rootNamespace = (value ? "http://schemas.microsoft.com/.NetConfiguration/v2.0" : null); } } public ConfigurationSectionGroup RootSectionGroup { get { if (rootSectionGroup == null) { rootSectionGroup = new ConfigurationSectionGroup(); rootSectionGroup.Initialize(this, rootGroup); } return rootSectionGroup; } } public ConfigurationSectionGroupCollection SectionGroups => RootSectionGroup.SectionGroups; public ConfigurationSectionCollection Sections => RootSectionGroup.Sections; public Func AssemblyStringTransformer { get { //IL_0007: Expected O, but got I4 ThrowStub.ThrowNotSupportedException(); return (Func)0; } [ConfigurationPermission(SecurityAction.Demand, Unrestricted = true)] set { ThrowStub.ThrowNotSupportedException(); } } public FrameworkName TargetFramework { get { ThrowStub.ThrowNotSupportedException(); return null; } [ConfigurationPermission(SecurityAction.Demand, Unrestricted = true)] set { ThrowStub.ThrowNotSupportedException(); } } public Func TypeStringTransformer { get { //IL_0007: Expected O, but got I4 ThrowStub.ThrowNotSupportedException(); return (Func)0; } [ConfigurationPermission(SecurityAction.Demand, Unrestricted = true)] set { ThrowStub.ThrowNotSupportedException(); } } internal static event ConfigurationSaveEventHandler SaveStart; internal static event ConfigurationSaveEventHandler SaveEnd; internal Configuration(Configuration parent, string locationSubPath) { elementData = new Hashtable(); base..ctor(); this.parent = parent; system = parent.system; rootGroup = parent.rootGroup; this.locationSubPath = locationSubPath; configPath = parent.ConfigPath; } internal Configuration(InternalConfigurationSystem system, string locationSubPath) { elementData = new Hashtable(); base..ctor(); hasFile = true; this.system = system; system.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath); Configuration configuration = null; if (locationSubPath != null) { configuration = new Configuration(system, locationSubPath); if (locationConfigPath != null) { configuration = configuration.FindLocationConfiguration(locationConfigPath, configuration); } } Init(system, configPath, configuration); } internal Configuration FindLocationConfiguration(string relativePath, Configuration defaultConfiguration) { Configuration configuration = defaultConfiguration; if (!string.IsNullOrEmpty(LocationConfigPath)) { Configuration parentWithFile = GetParentWithFile(); if (parentWithFile != null) { string configPathFromLocationSubPath = system.Host.GetConfigPathFromLocationSubPath(configPath, relativePath); configuration = parentWithFile.FindLocationConfiguration(configPathFromLocationSubPath, defaultConfiguration); } } string text = configPath.Substring(1) + "/"; if (relativePath.StartsWith(text, StringComparison.Ordinal)) { relativePath = relativePath.Substring(text.Length); } ConfigurationLocation configurationLocation = Locations.FindBest(relativePath); if (configurationLocation == null) { return configuration; } configurationLocation.SetParentConfiguration(configuration); return configurationLocation.OpenConfiguration(); } internal void Init(IConfigSystem system, string configPath, Configuration parent) { //IL_0067: Expected O, but got Unknown this.system = system; this.configPath = configPath; streamName = system.Host.GetStreamName(configPath); this.parent = parent; if (parent != null) { rootGroup = parent.rootGroup; } else { rootGroup = new SectionGroupInfo(); rootGroup.StreamName = streamName; } try { if (streamName != null) { Load(); } } catch (XmlException ex) { XmlException ex2 = ex; throw new ConfigurationErrorsException(((Exception)(object)ex2).Message, (Exception)(object)ex2, streamName, 0); } } internal Configuration GetParentWithFile() { Configuration configuration = Parent; while (configuration != null && !configuration.HasFile) { configuration = configuration.Parent; } return configuration; } internal string GetLocationSubPath() { Configuration configuration = parent; string text = null; while (configuration != null) { text = configuration.locationSubPath; if (!string.IsNullOrEmpty(text)) { return text; } configuration = configuration.parent; } return text; } public ConfigurationSection GetSection(string sectionName) { string[] array = sectionName.Split('/'); if (array.Length == 1) { return Sections[array[0]]; } ConfigurationSectionGroup configurationSectionGroup = SectionGroups[array[0]]; int num = 1; while (configurationSectionGroup != null && num < array.Length - 1) { configurationSectionGroup = configurationSectionGroup.SectionGroups[array[num]]; num++; } return configurationSectionGroup?.Sections[array[^1]]; } public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName) { string[] array = sectionGroupName.Split('/'); ConfigurationSectionGroup configurationSectionGroup = SectionGroups[array[0]]; int num = 1; while (configurationSectionGroup != null && num < array.Length) { configurationSectionGroup = configurationSectionGroup.SectionGroups[array[num]]; num++; } return configurationSectionGroup; } internal ConfigurationSection GetSectionInstance(SectionInfo config, bool createDefaultInstance) { object obj = elementData[config]; ConfigurationSection configurationSection = obj as ConfigurationSection; if (configurationSection != null || !createDefaultInstance) { return configurationSection; } object obj2 = config.CreateInstance(); configurationSection = obj2 as ConfigurationSection; if (configurationSection == null) { configurationSection = new DefaultSection { SectionHandler = (IConfigurationSectionHandler)((obj2 is IConfigurationSectionHandler) ? obj2 : null) }; } configurationSection.Configuration = this; ConfigurationSection configurationSection2 = null; if (parent != null) { configurationSection2 = parent.GetSectionInstance(config, createDefaultInstance: true); configurationSection.SectionInformation.SetParentSection(configurationSection2); } configurationSection.SectionInformation.ConfigFilePath = FilePath; configurationSection.ConfigContext = system.Host.CreateDeprecatedConfigContext(configPath); string text = (configurationSection.RawXml = obj as string); configurationSection.Reset(configurationSection2); if (text != null) { XmlTextReader val = (XmlTextReader)(object)new ConfigXmlTextReader(new StringReader(text), FilePath); configurationSection.DeserializeSection((XmlReader)(object)val); ((XmlReader)val).Close(); if (!string.IsNullOrEmpty(configurationSection.SectionInformation.ConfigSource) && !string.IsNullOrEmpty(FilePath)) { configurationSection.DeserializeConfigSource(Path.GetDirectoryName(FilePath)); } } elementData[config] = configurationSection; return configurationSection; } internal ConfigurationSectionGroup GetSectionGroupInstance(SectionGroupInfo group) { ConfigurationSectionGroup configurationSectionGroup = group.CreateInstance() as ConfigurationSectionGroup; configurationSectionGroup?.Initialize(this, group); return configurationSectionGroup; } internal void SetConfigurationSection(SectionInfo config, ConfigurationSection sec) { elementData[config] = sec; } internal void SetSectionXml(SectionInfo config, string data) { elementData[config] = data; } internal string GetSectionXml(SectionInfo config) { return elementData[config] as string; } internal void CreateSection(SectionGroupInfo group, string name, ConfigurationSection sec) { if (group.HasChild(name)) { throw new ConfigurationErrorsException("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'"); } if (!HasFile && !sec.SectionInformation.AllowLocation) { throw new ConfigurationErrorsException("The configuration section <" + name + "> cannot be defined inside a element."); } if (!system.Host.IsDefinitionAllowed(configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) { object obj = ((sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication) ? ((object)sec.SectionInformation.AllowExeDefinition) : ((object)sec.SectionInformation.AllowDefinition)); throw new ConfigurationErrorsException("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + obj?.ToString() + "')."); } if (sec.SectionInformation.Type == null) { sec.SectionInformation.Type = system.Host.GetConfigTypeName(sec.GetType()); } SectionInfo sectionInfo = new SectionInfo(name, sec.SectionInformation); sectionInfo.StreamName = streamName; sectionInfo.ConfigHost = system.Host; group.AddChild(sectionInfo); elementData[sectionInfo] = sec; sec.Configuration = this; } internal void CreateSectionGroup(SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec) { if (parentGroup.HasChild(name)) { throw new ConfigurationErrorsException("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'"); } if (sec.Type == null) { sec.Type = system.Host.GetConfigTypeName(sec.GetType()); } sec.SetName(name); SectionGroupInfo sectionGroupInfo = new SectionGroupInfo(name, sec.Type); sectionGroupInfo.StreamName = streamName; sectionGroupInfo.ConfigHost = system.Host; parentGroup.AddChild(sectionGroupInfo); elementData[sectionGroupInfo] = sec; sec.Initialize(this, sectionGroupInfo); } internal void RemoveConfigInfo(ConfigInfo config) { elementData.Remove(config); } public void Save() { Save(ConfigurationSaveMode.Modified, forceSaveAll: false); } public void Save(ConfigurationSaveMode saveMode) { Save(saveMode, forceSaveAll: false); } public void Save(ConfigurationSaveMode saveMode, bool forceSaveAll) { if (!forceSaveAll && saveMode != ConfigurationSaveMode.Full && !HasValues(saveMode)) { ResetModified(); return; } ConfigurationSaveEventHandler saveStart = Configuration.SaveStart; ConfigurationSaveEventHandler saveEnd = Configuration.SaveEnd; object writeContext = null; Exception ex = null; Stream stream = system.Host.OpenStreamForWrite(streamName, null, ref writeContext); try { saveStart?.Invoke(this, new ConfigurationSaveEventArgs(streamName, start: true, null, writeContext)); Save(stream, saveMode, forceSaveAll); system.Host.WriteCompleted(streamName, success: true, writeContext); } catch (Exception ex2) { ex = ex2; system.Host.WriteCompleted(streamName, success: false, writeContext); throw; } finally { stream.Close(); saveEnd?.Invoke(this, new ConfigurationSaveEventArgs(streamName, start: false, ex, writeContext)); } } public void SaveAs(string filename) { SaveAs(filename, ConfigurationSaveMode.Modified, forceSaveAll: false); } public void SaveAs(string filename, ConfigurationSaveMode saveMode) { SaveAs(filename, saveMode, forceSaveAll: false); } [MonoInternalNote("Detect if file has changed")] public void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll) { if (!forceSaveAll && saveMode != ConfigurationSaveMode.Full && !HasValues(saveMode)) { ResetModified(); return; } string directoryName = Path.GetDirectoryName(Path.GetFullPath(filename)); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Save(new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write), saveMode, forceSaveAll); } private void Save(Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown XmlTextWriter val = new XmlTextWriter((TextWriter)new StreamWriter(stream)); val.Formatting = (Formatting)1; try { ((XmlWriter)val).WriteStartDocument(); if (rootNamespace != null) { ((XmlWriter)val).WriteStartElement("configuration", rootNamespace); } else { ((XmlWriter)val).WriteStartElement("configuration"); } if (rootGroup.HasConfigContent(this)) { rootGroup.WriteConfig(this, (XmlWriter)(object)val, mode); } foreach (ConfigurationLocation location in Locations) { if (location.OpenedConfiguration == null) { ((XmlWriter)val).WriteRaw("\n"); ((XmlWriter)val).WriteRaw(location.XmlContent); continue; } ((XmlWriter)val).WriteStartElement("location"); ((XmlWriter)val).WriteAttributeString("path", location.Path); if (!location.AllowOverride) { ((XmlWriter)val).WriteAttributeString("allowOverride", "false"); } location.OpenedConfiguration.SaveData(val, mode, forceUpdateAll); ((XmlWriter)val).WriteEndElement(); } SaveData(val, mode, forceUpdateAll); ((XmlWriter)val).WriteEndElement(); ResetModified(); } finally { ((XmlWriter)val).Flush(); ((XmlWriter)val).Close(); } } private void SaveData(XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll) { rootGroup.WriteRootData((XmlWriter)(object)tw, this, mode); } private bool HasValues(ConfigurationSaveMode mode) { foreach (ConfigurationLocation location in Locations) { if (location.OpenedConfiguration != null && location.OpenedConfiguration.HasValues(mode)) { return true; } } return rootGroup.HasValues(this, mode); } private void ResetModified() { foreach (ConfigurationLocation location in Locations) { if (location.OpenedConfiguration != null) { location.OpenedConfiguration.ResetModified(); } } rootGroup.ResetModified(this); } private bool Load() { if (string.IsNullOrEmpty(streamName)) { return true; } Stream stream = null; try { stream = system.Host.OpenStreamForRead(streamName); if (stream == null) { return false; } } catch { return false; } XmlTextReader val = (XmlTextReader)(object)new ConfigXmlTextReader(stream, streamName); try { ReadConfigFile((XmlReader)(object)val, streamName); } finally { ((IDisposable)val)?.Dispose(); } ResetModified(); return true; } private void ReadConfigFile(XmlReader reader, string fileName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_0094: Unknown result type (might be due to invalid IL or missing references) reader.MoveToContent(); if ((int)reader.NodeType != 1 || reader.Name != "configuration") { ThrowException("Configuration file does not have a valid root element", reader); } if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "xmlns") { rootNamespace = reader.Value; } else { ThrowException($"Unrecognized attribute '{reader.LocalName}' in root element", reader); } } } reader.MoveToElement(); if (reader.IsEmptyElement) { reader.Skip(); return; } reader.ReadStartElement(); reader.MoveToContent(); if (reader.LocalName == "configSections") { if (reader.HasAttributes) { ThrowException("Unrecognized attribute in .", reader); } rootGroup.ReadConfig(this, fileName, reader); } rootGroup.ReadRootData(reader, this, overrideAllowed: true); } internal void ReadData(XmlReader reader, bool allowOverride) { rootGroup.ReadData(this, reader, allowOverride); } private void ThrowException(string text, XmlReader reader) { IXmlLineInfo val = (IXmlLineInfo)(object)((reader is IXmlLineInfo) ? reader : null); throw new ConfigurationErrorsException(text, streamName, (val != null) ? val.LineNumber : 0); } internal Configuration() { ThrowStub.ThrowNotSupportedException(); } } public enum ConfigurationAllowDefinition { MachineOnly = 0, MachineToWebRoot = 100, MachineToApplication = 200, Everywhere = 300 } public enum ConfigurationAllowExeDefinition { MachineOnly = 0, MachineToApplication = 100, MachineToLocalUser = 300, MachineToRoamingUser = 200 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] public sealed class ConfigurationCollectionAttribute : Attribute { private string addItemName = "add"; private string clearItemsName = "clear"; private string removeItemName = "remove"; private ConfigurationElementCollectionType collectionType; private Type itemType; public string AddItemName { get { return addItemName; } set { addItemName = value; } } public string ClearItemsName { get { return clearItemsName; } set { clearItemsName = value; } } public string RemoveItemName { get { return removeItemName; } set { removeItemName = value; } } public ConfigurationElementCollectionType CollectionType { get { return collectionType; } set { collectionType = value; } } [MonoInternalNote("Do something with this in ConfigurationElementCollection")] public Type ItemType => itemType; public ConfigurationCollectionAttribute(Type itemType) { this.itemType = itemType; } } public abstract class ConfigurationConverterBase : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type) { if (type == typeof(string)) { return true; } return base.CanConvertFrom(ctx, type); } public override bool CanConvertTo(ITypeDescriptorContext ctx, Type type) { if (type == typeof(string)) { return true; } return base.CanConvertTo(ctx, type); } } public abstract class ConfigurationElement { private class SaveContext { public readonly ConfigurationElement Element; public readonly ConfigurationElement Parent; public readonly ConfigurationSaveMode Mode; public SaveContext(ConfigurationElement element, ConfigurationElement parent, ConfigurationSaveMode mode) { Element = element; Parent = parent; Mode = mode; } public bool HasValues() { if (Mode == ConfigurationSaveMode.Full) { return true; } return Element.HasValues(Parent, Mode); } public bool HasValue(PropertyInformation prop) { if (Mode == ConfigurationSaveMode.Full) { return true; } return Element.HasValue(Parent, prop, Mode); } } private string rawXml; private bool modified; private ElementMap map; private ConfigurationPropertyCollection keyProps; private ConfigurationElementCollection defaultCollection; private bool readOnly; private ElementInformation elementInfo; private ConfigurationElementProperty elementProperty; private Configuration _configuration; private bool elementPresent; private ConfigurationLockCollection lockAllAttributesExcept; private ConfigurationLockCollection lockAllElementsExcept; private ConfigurationLockCollection lockAttributes; private ConfigurationLockCollection lockElements; private bool lockItem; private SaveContext saveContext; internal Configuration Configuration { get { return _configuration; } set { _configuration = value; } } public ElementInformation ElementInformation { get { if (elementInfo == null) { elementInfo = new ElementInformation(this, null); } return elementInfo; } } internal string RawXml { get { return rawXml; } set { if (rawXml == null || value != null) { rawXml = value; } } } protected internal virtual ConfigurationElementProperty ElementProperty { get { if (elementProperty == null) { elementProperty = new ConfigurationElementProperty(ElementInformation.Validator); } return elementProperty; } } protected ContextInformation EvaluationContext { get { if (Configuration != null) { return Configuration.EvaluationContext; } throw new ConfigurationErrorsException("This element is not currently associated with any context."); } } public ConfigurationLockCollection LockAllAttributesExcept { get { if (lockAllAttributesExcept == null) { lockAllAttributesExcept = new ConfigurationLockCollection(this, ConfigurationLockType.Attribute | ConfigurationLockType.Exclude); } return lockAllAttributesExcept; } } public ConfigurationLockCollection LockAllElementsExcept { get { if (lockAllElementsExcept == null) { lockAllElementsExcept = new ConfigurationLockCollection(this, ConfigurationLockType.Element | ConfigurationLockType.Exclude); } return lockAllElementsExcept; } } public ConfigurationLockCollection LockAttributes { get { if (lockAttributes == null) { lockAttributes = new ConfigurationLockCollection(this, ConfigurationLockType.Attribute); } return lockAttributes; } } public ConfigurationLockCollection LockElements { get { if (lockElements == null) { lockElements = new ConfigurationLockCollection(this, ConfigurationLockType.Element); } return lockElements; } } public bool LockItem { get { return lockItem; } set { lockItem = value; } } protected internal object this[ConfigurationProperty prop] { get { return this[prop.Name]; } set { this[prop.Name] = value; } } protected internal object this[string propertyName] { get { return (ElementInformation.Properties[propertyName] ?? throw new InvalidOperationException("Property '" + propertyName + "' not found in configuration element")).Value; } set { PropertyInformation propertyInformation = ElementInformation.Properties[propertyName]; if (propertyInformation == null) { throw new InvalidOperationException("Property '" + propertyName + "' not found in configuration element"); } SetPropertyValue(propertyInformation.Property, value, ignoreLocks: false); propertyInformation.Value = value; modified = true; } } protected internal virtual ConfigurationPropertyCollection Properties { get { if (map == null) { map = ElementMap.GetMap(GetType()); } return map.Properties; } } internal bool IsElementPresent => elementPresent; public Configuration CurrentConfiguration { get { ThrowStub.ThrowNotSupportedException(); return null; } } protected bool HasContext { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } } internal virtual void InitFromProperty(PropertyInformation propertyInfo) { elementInfo = new ElementInformation(this, propertyInfo); Init(); } protected internal virtual void Init() { } [MonoTODO] protected virtual void ListErrors(IList errorList) { throw new NotImplementedException(); } [MonoTODO] protected void SetPropertyValue(ConfigurationProperty prop, object value, bool ignoreLocks) { try { if (value != null) { prop.Validate(value); } } catch (Exception inner) { throw new ConfigurationErrorsException($"The value for the property '{prop.Name}' on type {ElementInformation.Type} is not valid.", inner); } } internal ConfigurationPropertyCollection GetKeyProperties() { if (keyProps != null) { return keyProps; } ConfigurationPropertyCollection configurationPropertyCollection = new ConfigurationPropertyCollection(); foreach (ConfigurationProperty property in Properties) { if (property.IsKey) { configurationPropertyCollection.Add(property); } } return keyProps = configurationPropertyCollection; } internal ConfigurationElementCollection GetDefaultCollection() { if (defaultCollection != null) { return defaultCollection; } ConfigurationProperty configurationProperty = null; foreach (ConfigurationProperty property in Properties) { if (property.IsDefaultCollection) { configurationProperty = property; break; } } if (configurationProperty != null) { defaultCollection = this[configurationProperty] as ConfigurationElementCollection; } return defaultCollection; } public override bool Equals(object compareTo) { if (!(compareTo is ConfigurationElement configurationElement)) { return false; } if (GetType() != configurationElement.GetType()) { return false; } foreach (ConfigurationProperty property in Properties) { if (!object.Equals(this[property], configurationElement[property])) { return false; } } return true; } public override int GetHashCode() { int num = 0; foreach (ConfigurationProperty property in Properties) { object obj = this[property]; if (obj != null) { num += obj.GetHashCode(); } } return num; } internal virtual bool HasLocalModifications() { foreach (PropertyInformation property in ElementInformation.Properties) { if (property.ValueOrigin == PropertyValueOrigin.SetHere && property.IsModified) { return true; } } return false; } protected internal virtual void DeserializeElement(XmlReader reader, bool serializeCollectionKey) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Invalid comparison between Unknown and I4 Hashtable hashtable = new Hashtable(); reader.MoveToContent(); elementPresent = true; while (reader.MoveToNextAttribute()) { PropertyInformation propertyInformation = ElementInformation.Properties[reader.LocalName]; if (propertyInformation == null || (serializeCollectionKey && !propertyInformation.IsKey)) { if (reader.LocalName == "lockAllAttributesExcept") { LockAllAttributesExcept.SetFromList(reader.Value); } else if (reader.LocalName == "lockAllElementsExcept") { LockAllElementsExcept.SetFromList(reader.Value); } else if (reader.LocalName == "lockAttributes") { LockAttributes.SetFromList(reader.Value); } else if (reader.LocalName == "lockElements") { LockElements.SetFromList(reader.Value); } else if (reader.LocalName == "lockItem") { LockItem = reader.Value.ToLowerInvariant() == "true"; } else if (!(reader.LocalName == "xmlns") && (!(this is ConfigurationSection) || !(reader.LocalName == "configSource")) && !OnDeserializeUnrecognizedAttribute(reader.LocalName, reader.Value)) { throw new ConfigurationErrorsException("Unrecognized attribute '" + reader.LocalName + "'.", reader); } continue; } if (hashtable.ContainsKey(propertyInformation)) { throw new ConfigurationErrorsException("The attribute '" + propertyInformation.Name + "' may only appear once in this element.", reader); } string text = null; try { text = reader.Value; ValidateValue(propertyInformation.Property, text); propertyInformation.SetStringValue(text); } catch (ConfigurationErrorsException) { throw; } catch (ConfigurationException) { throw; } catch (Exception ex3) { throw new ConfigurationErrorsException($"The value for the property '{propertyInformation.Name}' is not valid. The error is: {ex3.Message}", reader); } hashtable[propertyInformation] = propertyInformation.Name; if (reader is ConfigXmlTextReader configXmlTextReader) { propertyInformation.Source = configXmlTextReader.Filename; propertyInformation.LineNumber = ((XmlTextReader)configXmlTextReader).LineNumber; } } reader.MoveToElement(); if (reader.IsEmptyElement) { reader.Skip(); } else { int depth = reader.Depth; reader.ReadStartElement(); reader.MoveToContent(); do { if ((int)reader.NodeType != 1) { reader.Skip(); continue; } PropertyInformation propertyInformation2 = ElementInformation.Properties[reader.LocalName]; if (propertyInformation2 == null || (serializeCollectionKey && !propertyInformation2.IsKey)) { if (OnDeserializeUnrecognizedElement(reader.LocalName, reader)) { continue; } if (propertyInformation2 == null) { ConfigurationElementCollection configurationElementCollection = GetDefaultCollection(); if (configurationElementCollection != null && configurationElementCollection.OnDeserializeUnrecognizedElement(reader.LocalName, reader)) { continue; } } throw new ConfigurationErrorsException("Unrecognized element '" + reader.LocalName + "'.", reader); } if (!propertyInformation2.IsElement) { throw new ConfigurationErrorsException("Property '" + propertyInformation2.Name + "' is not a ConfigurationElement."); } if (hashtable.Contains(propertyInformation2)) { throw new ConfigurationErrorsException("The element <" + propertyInformation2.Name + "> may only appear once in this section.", reader); } ((ConfigurationElement)propertyInformation2.Value).DeserializeElement(reader, serializeCollectionKey); hashtable[propertyInformation2] = propertyInformation2.Name; if (depth == reader.Depth) { reader.Read(); } } while (depth < reader.Depth); } modified = false; foreach (PropertyInformation property in ElementInformation.Properties) { if (!string.IsNullOrEmpty(property.Name) && property.IsRequired && !hashtable.ContainsKey(property) && ElementInformation.Properties[property.Name] == null) { object obj = OnRequiredPropertyNotFound(property.Name); if (!object.Equals(obj, property.DefaultValue)) { property.Value = obj; property.IsModified = false; } } } PostDeserialize(); } protected virtual bool OnDeserializeUnrecognizedAttribute(string name, string value) { return false; } protected virtual bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader) { return false; } protected virtual object OnRequiredPropertyNotFound(string name) { throw new ConfigurationErrorsException("Required attribute '" + name + "' not found."); } protected virtual void PreSerialize(XmlWriter writer) { } protected virtual void PostDeserialize() { } protected internal virtual void InitializeDefault() { } protected internal virtual bool IsModified() { if (modified) { return true; } foreach (PropertyInformation property in ElementInformation.Properties) { if (property.IsElement && property.Value is ConfigurationElement configurationElement && configurationElement.IsModified()) { modified = true; break; } } return modified; } protected internal virtual void SetReadOnly() { readOnly = true; } public virtual bool IsReadOnly() { return readOnly; } protected internal virtual void Reset(ConfigurationElement parentElement) { elementPresent = false; if (parentElement != null) { ElementInformation.Reset(parentElement.ElementInformation); } else { InitializeDefault(); } } protected internal virtual void ResetModified() { modified = false; foreach (PropertyInformation property in ElementInformation.Properties) { property.IsModified = false; if (property.Value is ConfigurationElement configurationElement) { configurationElement.ResetModified(); } } } protected internal virtual bool SerializeElement(XmlWriter writer, bool serializeCollectionKey) { PreSerialize(writer); if (serializeCollectionKey) { ConfigurationPropertyCollection keyProperties = GetKeyProperties(); foreach (ConfigurationProperty item in keyProperties) { writer.WriteAttributeString(item.Name, item.ConvertToString(this[item.Name])); } return keyProperties.Count > 0; } bool flag = false; foreach (PropertyInformation property in ElementInformation.Properties) { if (!property.IsElement) { if (saveContext == null) { throw new InvalidOperationException(); } if (saveContext.HasValue(property)) { writer.WriteAttributeString(property.Name, property.GetStringValue()); flag = true; } } } foreach (PropertyInformation property2 in ElementInformation.Properties) { if (property2.IsElement) { ConfigurationElement configurationElement = (ConfigurationElement)property2.Value; if (configurationElement != null) { flag = configurationElement.SerializeToXmlElement(writer, property2.Name) || flag; } } } return flag; } protected internal virtual bool SerializeToXmlElement(XmlWriter writer, string elementName) { if (saveContext == null) { throw new InvalidOperationException(); } if (!saveContext.HasValues()) { return false; } if (elementName != null && elementName != "") { writer.WriteStartElement(elementName); } bool result = SerializeElement(writer, serializeCollectionKey: false); if (elementName != null && elementName != "") { writer.WriteEndElement(); } return result; } protected internal virtual void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode) { if (parentElement != null && sourceElement.GetType() != parentElement.GetType()) { throw new ConfigurationErrorsException("Can't unmerge two elements of different type"); } bool flag = saveMode == ConfigurationSaveMode.Minimal || saveMode == ConfigurationSaveMode.Modified; foreach (PropertyInformation property in sourceElement.ElementInformation.Properties) { if (property.ValueOrigin == PropertyValueOrigin.Default) { continue; } PropertyInformation propertyInformation2 = ElementInformation.Properties[property.Name]; object value = property.Value; if (parentElement == null || !parentElement.HasValue(property.Name)) { propertyInformation2.Value = value; } else { if (value == null) { continue; } object obj = parentElement[property.Name]; if (!property.IsElement) { if (!object.Equals(value, obj) || saveMode == ConfigurationSaveMode.Full || (saveMode == ConfigurationSaveMode.Modified && property.ValueOrigin == PropertyValueOrigin.SetHere)) { propertyInformation2.Value = value; } continue; } ConfigurationElement configurationElement = (ConfigurationElement)value; if (!flag || configurationElement.IsModified()) { if (obj == null) { propertyInformation2.Value = value; continue; } ConfigurationElement parentElement2 = (ConfigurationElement)obj; ((ConfigurationElement)propertyInformation2.Value).Unmerge(configurationElement, parentElement2, saveMode); } } } } internal bool HasValue(string propName) { PropertyInformation propertyInformation = ElementInformation.Properties[propName]; if (propertyInformation != null) { return propertyInformation.ValueOrigin != PropertyValueOrigin.Default; } return false; } internal bool IsReadFromConfig(string propName) { PropertyInformation propertyInformation = ElementInformation.Properties[propName]; if (propertyInformation != null) { return propertyInformation.ValueOrigin == PropertyValueOrigin.SetHere; } return false; } private void ValidateValue(ConfigurationProperty p, string value) { ConfigurationValidatorBase validator; if (p != null && (validator = p.Validator) != null) { if (!validator.CanValidate(p.Type)) { throw new ConfigurationErrorsException($"Validator does not support type {p.Type}"); } validator.Validate(p.ConvertFromString(value)); } } internal bool HasValue(ConfigurationElement parent, PropertyInformation prop, ConfigurationSaveMode mode) { if (prop.ValueOrigin == PropertyValueOrigin.Default) { return false; } if (mode == ConfigurationSaveMode.Modified && prop.ValueOrigin == PropertyValueOrigin.SetHere && prop.IsModified) { return true; } object obj = ((parent != null && parent.HasValue(prop.Name)) ? parent[prop.Name] : prop.DefaultValue); if (!prop.IsElement) { return !object.Equals(prop.Value, obj); } ConfigurationElement obj2 = (ConfigurationElement)prop.Value; ConfigurationElement parent2 = (ConfigurationElement)obj; return obj2.HasValues(parent2, mode); } internal virtual bool HasValues(ConfigurationElement parent, ConfigurationSaveMode mode) { if (mode == ConfigurationSaveMode.Full) { return true; } if (modified && mode == ConfigurationSaveMode.Modified) { return true; } foreach (PropertyInformation property in ElementInformation.Properties) { if (HasValue(parent, property, mode)) { return true; } } return false; } internal virtual void PrepareSave(ConfigurationElement parent, ConfigurationSaveMode mode) { saveContext = new SaveContext(this, parent, mode); foreach (PropertyInformation property in ElementInformation.Properties) { if (property.IsElement) { ConfigurationElement configurationElement = (ConfigurationElement)property.Value; if (parent == null || !parent.HasValue(property.Name)) { configurationElement.PrepareSave(null, mode); continue; } ConfigurationElement parent2 = (ConfigurationElement)parent[property.Name]; configurationElement.PrepareSave(parent2, mode); } } } protected virtual string GetTransformedAssemblyString(string assemblyName) { ThrowStub.ThrowNotSupportedException(); return null; } protected virtual string GetTransformedTypeString(string typeName) { ThrowStub.ThrowNotSupportedException(); return null; } } internal class ElementMap { private static readonly Hashtable elementMaps = Hashtable.Synchronized(new Hashtable()); private readonly ConfigurationPropertyCollection properties; private readonly ConfigurationCollectionAttribute collectionAttribute; public ConfigurationCollectionAttribute CollectionAttribute => collectionAttribute; public bool HasProperties => properties.Count > 0; public ConfigurationPropertyCollection Properties => properties; public static ElementMap GetMap(Type t) { if (elementMaps[t] is ElementMap result) { return result; } ElementMap elementMap = new ElementMap(t); elementMaps[t] = elementMap; return elementMap; } public ElementMap(Type t) { properties = new ConfigurationPropertyCollection(); collectionAttribute = Attribute.GetCustomAttribute(t, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute; PropertyInfo[] array = t.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (PropertyInfo propertyInfo in array) { if (Attribute.GetCustomAttribute(propertyInfo, typeof(ConfigurationPropertyAttribute)) is ConfigurationPropertyAttribute configurationPropertyAttribute) { string name = ((configurationPropertyAttribute.Name != null) ? configurationPropertyAttribute.Name : propertyInfo.Name); ConfigurationValidatorBase validator = ((Attribute.GetCustomAttribute(propertyInfo, typeof(ConfigurationValidatorAttribute)) is ConfigurationValidatorAttribute configurationValidatorAttribute) ? configurationValidatorAttribute.ValidatorInstance : null); TypeConverterAttribute typeConverterAttribute = (TypeConverterAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(TypeConverterAttribute)); ConfigurationProperty property = new ConfigurationProperty(typeConverter: (typeConverterAttribute != null) ? ((TypeConverter)Activator.CreateInstance(Type.GetType(typeConverterAttribute.ConverterTypeName), nonPublic: true)) : null, name: name, type: propertyInfo.PropertyType, defaultValue: configurationPropertyAttribute.DefaultValue, validator: validator, options: configurationPropertyAttribute.Options) { CollectionAttribute = (Attribute.GetCustomAttribute(propertyInfo, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute) }; properties.Add(property); } } } } [DebuggerDisplay("Count = {Count}")] public abstract class ConfigurationElementCollection : ConfigurationElement, ICollection, IEnumerable { private sealed class ConfigurationRemoveElement : ConfigurationElement { private readonly ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection(); private readonly ConfigurationElement _origElement; private readonly ConfigurationElementCollection _origCollection; internal object KeyValue { get { foreach (ConfigurationProperty property in Properties) { _origElement[property] = base[property]; } return _origCollection.GetElementKey(_origElement); } } protected internal override ConfigurationPropertyCollection Properties => properties; internal ConfigurationRemoveElement(ConfigurationElement origElement, ConfigurationElementCollection origCollection) { _origElement = origElement; _origCollection = origCollection; foreach (ConfigurationProperty property in origElement.Properties) { if (property.IsKey) { properties.Add(property); } } } } private ArrayList list = new ArrayList(); private ArrayList removed; private ArrayList inherited; private bool emitClear; private bool modified; private IComparer comparer; private int inheritedLimitIndex; private string addElementName = "add"; private string clearElementName = "clear"; private string removeElementName = "remove"; public virtual ConfigurationElementCollectionType CollectionType => ConfigurationElementCollectionType.AddRemoveClearMap; private bool IsBasic { get { if (CollectionType != ConfigurationElementCollectionType.BasicMap) { return CollectionType == ConfigurationElementCollectionType.BasicMapAlternate; } return true; } } private bool IsAlternate { get { if (CollectionType != ConfigurationElementCollectionType.AddRemoveClearMapAlternate) { return CollectionType == ConfigurationElementCollectionType.BasicMapAlternate; } return true; } } public int Count => list.Count; protected virtual string ElementName => string.Empty; public bool EmitClear { get { return emitClear; } set { emitClear = value; } } public bool IsSynchronized => false; public object SyncRoot => this; protected virtual bool ThrowOnDuplicate { get { if (CollectionType != ConfigurationElementCollectionType.AddRemoveClearMap && CollectionType != ConfigurationElementCollectionType.AddRemoveClearMapAlternate) { return false; } return true; } } protected internal string AddElementName { get { return addElementName; } set { addElementName = value; } } protected internal string ClearElementName { get { return clearElementName; } set { clearElementName = value; } } protected internal string RemoveElementName { get { return removeElementName; } set { removeElementName = value; } } protected ConfigurationElementCollection() { } protected ConfigurationElementCollection(IComparer comparer) { this.comparer = comparer; } internal override void InitFromProperty(PropertyInformation propertyInfo) { ConfigurationCollectionAttribute configurationCollectionAttribute = propertyInfo.Property.CollectionAttribute; if (configurationCollectionAttribute == null) { configurationCollectionAttribute = Attribute.GetCustomAttribute(propertyInfo.Type, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute; } if (configurationCollectionAttribute != null) { addElementName = configurationCollectionAttribute.AddItemName; clearElementName = configurationCollectionAttribute.ClearItemsName; removeElementName = configurationCollectionAttribute.RemoveItemName; } base.InitFromProperty(propertyInfo); } protected virtual void BaseAdd(ConfigurationElement element) { BaseAdd(element, ThrowOnDuplicate); } protected void BaseAdd(ConfigurationElement element, bool throwIfExists) { if (IsReadOnly()) { throw new ConfigurationErrorsException("Collection is read only."); } if (IsAlternate) { list.Insert(inheritedLimitIndex, element); inheritedLimitIndex++; } else { int num = IndexOfKey(GetElementKey(element)); if (num >= 0) { if (element.Equals(list[num])) { return; } if (throwIfExists) { throw new ConfigurationErrorsException("Duplicate element in collection"); } list.RemoveAt(num); } list.Add(element); } modified = true; } protected virtual void BaseAdd(int index, ConfigurationElement element) { if (ThrowOnDuplicate && BaseIndexOf(element) != -1) { throw new ConfigurationErrorsException("Duplicate element in collection"); } if (IsReadOnly()) { throw new ConfigurationErrorsException("Collection is read only."); } if (IsAlternate && index > inheritedLimitIndex) { throw new ConfigurationErrorsException("Can't insert new elements below the inherited elements."); } if (!IsAlternate && index <= inheritedLimitIndex) { throw new ConfigurationErrorsException("Can't insert new elements above the inherited elements."); } list.Insert(index, element); modified = true; } protected internal void BaseClear() { if (IsReadOnly()) { throw new ConfigurationErrorsException("Collection is read only."); } list.Clear(); modified = true; } protected internal ConfigurationElement BaseGet(int index) { return (ConfigurationElement)list[index]; } protected internal ConfigurationElement BaseGet(object key) { int num = IndexOfKey(key); if (num != -1) { return (ConfigurationElement)list[num]; } return null; } protected internal object[] BaseGetAllKeys() { object[] array = new object[list.Count]; for (int i = 0; i < list.Count; i++) { array[i] = BaseGetKey(i); } return array; } protected internal object BaseGetKey(int index) { if (index < 0 || index >= list.Count) { throw new ConfigurationErrorsException($"Index {index} is out of range"); } return GetElementKey((ConfigurationElement)list[index]).ToString(); } protected int BaseIndexOf(ConfigurationElement element) { return list.IndexOf(element); } private int IndexOfKey(object key) { for (int i = 0; i < list.Count; i++) { if (CompareKeys(GetElementKey((ConfigurationElement)list[i]), key)) { return i; } } return -1; } protected internal bool BaseIsRemoved(object key) { if (removed == null) { return false; } foreach (ConfigurationElement item in removed) { if (CompareKeys(GetElementKey(item), key)) { return true; } } return false; } protected internal void BaseRemove(object key) { if (IsReadOnly()) { throw new ConfigurationErrorsException("Collection is read only."); } int num = IndexOfKey(key); if (num != -1) { BaseRemoveAt(num); modified = true; } } protected internal void BaseRemoveAt(int index) { if (IsReadOnly()) { throw new ConfigurationErrorsException("Collection is read only."); } ConfigurationElement configurationElement = (ConfigurationElement)list[index]; if (!IsElementRemovable(configurationElement)) { throw new ConfigurationErrorsException("Element can't be removed from element collection."); } if (inherited != null && inherited.Contains(configurationElement)) { throw new ConfigurationErrorsException("Inherited items can't be removed."); } list.RemoveAt(index); if (IsAlternate && inheritedLimitIndex > 0) { inheritedLimitIndex--; } modified = true; } private bool CompareKeys(object key1, object key2) { if (comparer != null) { return comparer.Compare(key1, key2) == 0; } return object.Equals(key1, key2); } public void CopyTo(ConfigurationElement[] array, int index) { list.CopyTo(array, index); } protected abstract ConfigurationElement CreateNewElement(); protected virtual ConfigurationElement CreateNewElement(string elementName) { return CreateNewElement(); } private ConfigurationElement CreateNewElementInternal(string elementName) { ConfigurationElement configurationElement = ((elementName != null) ? CreateNewElement(elementName) : CreateNewElement()); configurationElement.Init(); return configurationElement; } public override bool Equals(object compareTo) { if (!(compareTo is ConfigurationElementCollection configurationElementCollection)) { return false; } if (GetType() != configurationElementCollection.GetType()) { return false; } if (Count != configurationElementCollection.Count) { return false; } for (int i = 0; i < Count; i++) { if (!BaseGet(i).Equals(configurationElementCollection.BaseGet(i))) { return false; } } return true; } protected abstract object GetElementKey(ConfigurationElement element); public override int GetHashCode() { int num = 0; for (int i = 0; i < Count; i++) { num += BaseGet(i).GetHashCode(); } return num; } void ICollection.CopyTo(Array arr, int index) { list.CopyTo(arr, index); } public IEnumerator GetEnumerator() { return list.GetEnumerator(); } protected virtual bool IsElementName(string elementName) { return false; } protected virtual bool IsElementRemovable(ConfigurationElement element) { return !IsReadOnly(); } protected internal override bool IsModified() { if (modified) { return true; } for (int i = 0; i < list.Count; i++) { if (((ConfigurationElement)list[i]).IsModified()) { modified = true; break; } } return modified; } [MonoTODO] public override bool IsReadOnly() { return base.IsReadOnly(); } internal override void PrepareSave(ConfigurationElement parentElement, ConfigurationSaveMode mode) { ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)parentElement; base.PrepareSave(parentElement, mode); for (int i = 0; i < list.Count; i++) { ConfigurationElement configurationElement = (ConfigurationElement)list[i]; object elementKey = GetElementKey(configurationElement); ConfigurationElement parent = configurationElementCollection?.BaseGet(elementKey); configurationElement.PrepareSave(parent, mode); } } internal override bool HasValues(ConfigurationElement parentElement, ConfigurationSaveMode mode) { ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)parentElement; if (mode == ConfigurationSaveMode.Full) { return list.Count > 0; } for (int i = 0; i < list.Count; i++) { ConfigurationElement configurationElement = (ConfigurationElement)list[i]; object elementKey = GetElementKey(configurationElement); ConfigurationElement parent = configurationElementCollection?.BaseGet(elementKey); if (configurationElement.HasValues(parent, mode)) { return true; } } return false; } protected internal override void Reset(ConfigurationElement parentElement) { bool isBasic = IsBasic; ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)parentElement; for (int i = 0; i < configurationElementCollection.Count; i++) { ConfigurationElement parentElement2 = configurationElementCollection.BaseGet(i); ConfigurationElement configurationElement = CreateNewElementInternal(null); configurationElement.Reset(parentElement2); BaseAdd(configurationElement); if (isBasic) { if (inherited == null) { inherited = new ArrayList(); } inherited.Add(configurationElement); } } if (IsAlternate) { inheritedLimitIndex = 0; } else { inheritedLimitIndex = Count - 1; } modified = false; } protected internal override void ResetModified() { modified = false; for (int i = 0; i < list.Count; i++) { ((ConfigurationElement)list[i]).ResetModified(); } } [MonoTODO] protected internal override void SetReadOnly() { base.SetReadOnly(); } protected internal override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey) { if (serializeCollectionKey) { return base.SerializeElement(writer, serializeCollectionKey); } bool flag = false; if (IsBasic) { for (int i = 0; i < list.Count; i++) { ConfigurationElement configurationElement = (ConfigurationElement)list[i]; flag = ((!(ElementName != string.Empty)) ? (configurationElement.SerializeElement(writer, serializeCollectionKey: false) || flag) : (configurationElement.SerializeToXmlElement(writer, ElementName) || flag)); } } else { if (emitClear) { writer.WriteElementString(clearElementName, ""); flag = true; } if (removed != null) { for (int j = 0; j < removed.Count; j++) { writer.WriteStartElement(removeElementName); ((ConfigurationElement)removed[j]).SerializeElement(writer, serializeCollectionKey: true); writer.WriteEndElement(); } flag = flag || removed.Count > 0; } for (int k = 0; k < list.Count; k++) { ((ConfigurationElement)list[k]).SerializeToXmlElement(writer, addElementName); } flag = flag || list.Count > 0; } return flag; } protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) if (IsBasic) { ConfigurationElement configurationElement = null; if (elementName == ElementName) { configurationElement = CreateNewElementInternal(null); } if (IsElementName(elementName)) { configurationElement = CreateNewElementInternal(elementName); } if (configurationElement != null) { configurationElement.DeserializeElement(reader, serializeCollectionKey: false); BaseAdd(configurationElement); modified = false; return true; } } else { if (elementName == clearElementName) { reader.MoveToContent(); if (reader.MoveToNextAttribute()) { throw new ConfigurationErrorsException("Unrecognized attribute '" + reader.LocalName + "'."); } reader.MoveToElement(); reader.Skip(); BaseClear(); emitClear = true; modified = false; return true; } if (elementName == removeElementName) { ConfigurationRemoveElement configurationRemoveElement = new ConfigurationRemoveElement(CreateNewElementInternal(null), this); configurationRemoveElement.DeserializeElement(reader, serializeCollectionKey: true); BaseRemove(configurationRemoveElement.KeyValue); modified = false; return true; } if (elementName == addElementName) { ConfigurationElement configurationElement2 = CreateNewElementInternal(null); configurationElement2.DeserializeElement(reader, serializeCollectionKey: false); BaseAdd(configurationElement2); modified = false; return true; } } return false; } protected internal override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode) { ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)sourceElement; ConfigurationElementCollection configurationElementCollection2 = (ConfigurationElementCollection)parentElement; for (int i = 0; i < configurationElementCollection.Count; i++) { ConfigurationElement configurationElement = configurationElementCollection.BaseGet(i); object elementKey = configurationElementCollection.GetElementKey(configurationElement); ConfigurationElement configurationElement2 = configurationElementCollection2?.BaseGet(elementKey); ConfigurationElement configurationElement3 = CreateNewElementInternal(null); if (configurationElement2 != null && saveMode != ConfigurationSaveMode.Full) { configurationElement3.Unmerge(configurationElement, configurationElement2, saveMode); if (configurationElement3.HasValues(configurationElement2, saveMode)) { BaseAdd(configurationElement3); } } else { configurationElement3.Unmerge(configurationElement, null, ConfigurationSaveMode.Full); BaseAdd(configurationElement3); } } if (saveMode == ConfigurationSaveMode.Full) { EmitClear = true; } else { if (configurationElementCollection2 == null) { return; } for (int j = 0; j < configurationElementCollection2.Count; j++) { ConfigurationElement configurationElement4 = configurationElementCollection2.BaseGet(j); object elementKey2 = configurationElementCollection2.GetElementKey(configurationElement4); if (configurationElementCollection.IndexOfKey(elementKey2) == -1) { if (removed == null) { removed = new ArrayList(); } removed.Add(configurationElement4); } } } } } public enum ConfigurationElementCollectionType { BasicMap, AddRemoveClearMap, BasicMapAlternate, AddRemoveClearMapAlternate } public sealed class ConfigurationElementProperty { private ConfigurationValidatorBase validator; public ConfigurationValidatorBase Validator => validator; public ConfigurationElementProperty(ConfigurationValidatorBase validator) { this.validator = validator; } } [Serializable] public class ConfigurationErrorsException : ConfigurationException { private readonly string filename; private readonly int line; public override string BareMessage => ((ConfigurationException)this).BareMessage; public ICollection Errors { get { throw new NotImplementedException(); } } public override string Filename => filename; public override int Line => line; public override string Message { get { if (!string.IsNullOrEmpty(filename)) { if (line != 0) { return ((ConfigurationException)this).BareMessage + " (" + filename + " line " + line + ")"; } return ((ConfigurationException)this).BareMessage + " (" + filename + ")"; } if (line != 0) { return ((ConfigurationException)this).BareMessage + " (line " + line + ")"; } return ((ConfigurationException)this).BareMessage; } } public ConfigurationErrorsException() { } public ConfigurationErrorsException(string message) : base(message) { } protected ConfigurationErrorsException(SerializationInfo info, StreamingContext context) : base(info, context) { filename = info.GetString("ConfigurationErrors_Filename"); line = info.GetInt32("ConfigurationErrors_Line"); } public ConfigurationErrorsException(string message, Exception inner) : base(message, inner) { } public ConfigurationErrorsException(string message, XmlNode node) : this(message, null, GetFilename(node), GetLineNumber(node)) { } public ConfigurationErrorsException(string message, Exception inner, XmlNode node) : this(message, inner, GetFilename(node), GetLineNumber(node)) { } public ConfigurationErrorsException(string message, XmlReader reader) : this(message, null, GetFilename(reader), GetLineNumber(reader)) { } public ConfigurationErrorsException(string message, Exception inner, XmlReader reader) : this(message, inner, GetFilename(reader), GetLineNumber(reader)) { } public ConfigurationErrorsException(string message, string filename, int line) : this(message, null, filename, line) { } public ConfigurationErrorsException(string message, Exception inner, string filename, int line) : base(message, inner) { this.filename = filename; this.line = line; } public static string GetFilename(XmlReader reader) { if (reader is IConfigErrorInfo) { return ((IConfigErrorInfo)reader).Filename; } if (reader == null) { return null; } return reader.BaseURI; } public static int GetLineNumber(XmlReader reader) { if (reader is IConfigErrorInfo) { return ((IConfigErrorInfo)reader).LineNumber; } IXmlLineInfo val = (IXmlLineInfo)(object)((reader is IXmlLineInfo) ? reader : null); if (val == null) { return 0; } return val.LineNumber; } public static string GetFilename(XmlNode node) { if (!(node is IConfigErrorInfo)) { return null; } return ((IConfigErrorInfo)node).Filename; } public static int GetLineNumber(XmlNode node) { if (!(node is IConfigErrorInfo)) { return 0; } return ((IConfigErrorInfo)node).LineNumber; } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { ((ConfigurationException)this).GetObjectData(info, context); info.AddValue("ConfigurationErrors_Filename", filename); info.AddValue("ConfigurationErrors_Line", line); } } public class ConfigurationFileMap : ICloneable { private string machineConfigFilename; public string MachineConfigFilename { get { return machineConfigFilename; } set { machineConfigFilename = value; } } public ConfigurationFileMap() { machineConfigFilename = RuntimeEnvironment.SystemConfigurationFile; } public ConfigurationFileMap(string machineConfigFilename) { this.machineConfigFilename = machineConfigFilename; } public virtual object Clone() { return new ConfigurationFileMap(machineConfigFilename); } } public class ConfigurationLocation { private static readonly char[] pathTrimChars = new char[1] { '/' }; private string path; private Configuration configuration; private Configuration parent; private string xmlContent; private bool parentResolved; private bool allowOverride; public string Path => path; internal bool AllowOverride => allowOverride; internal string XmlContent => xmlContent; internal Configuration OpenedConfiguration => configuration; internal ConfigurationLocation() { } internal ConfigurationLocation(string path, string xmlContent, Configuration parent, bool allowOverride) { if (!string.IsNullOrEmpty(path)) { switch (path[0]) { case ' ': case '.': case '/': case '\\': throw new ConfigurationErrorsException(" path attribute must be a relative virtual path. It cannot start with any of ' ' '.' '/' or '\\'."); } path = path.TrimEnd(pathTrimChars); } this.path = path; this.xmlContent = xmlContent; this.parent = parent; this.allowOverride = allowOverride; } public Configuration OpenConfiguration() { if (configuration == null) { if (!parentResolved) { Configuration parentWithFile = parent.GetParentWithFile(); if (parentWithFile != null) { string configPathFromLocationSubPath = parent.ConfigHost.GetConfigPathFromLocationSubPath(parent.LocationConfigPath, path); parent = parentWithFile.FindLocationConfiguration(configPathFromLocationSubPath, parent); } } configuration = new Configuration(parent, path); XmlTextReader val = (XmlTextReader)(object)new ConfigXmlTextReader(new StringReader(xmlContent), path); try { configuration.ReadData((XmlReader)(object)val, allowOverride); } finally { ((IDisposable)val)?.Dispose(); } xmlContent = null; } return configuration; } internal void SetParentConfiguration(Configuration parent) { if (!parentResolved) { parentResolved = true; this.parent = parent; if (configuration != null) { configuration.Parent = parent; } } } } public class ConfigurationLocationCollection : ReadOnlyCollectionBase { public ConfigurationLocation this[int index] => base.InnerList[index] as ConfigurationLocation; internal ConfigurationLocationCollection() { } internal void Add(ConfigurationLocation loc) { base.InnerList.Add(loc); } internal ConfigurationLocation Find(string location) { foreach (ConfigurationLocation inner in base.InnerList) { if (string.Compare(inner.Path, location, StringComparison.OrdinalIgnoreCase) == 0) { return inner; } } return null; } internal ConfigurationLocation FindBest(string location) { if (string.IsNullOrEmpty(location)) { return null; } ConfigurationLocation configurationLocation = null; int length = location.Length; int num = 0; foreach (ConfigurationLocation inner in base.InnerList) { string path = inner.Path; if (string.IsNullOrEmpty(path)) { continue; } int length2 = path.Length; if (!location.StartsWith(path, StringComparison.OrdinalIgnoreCase)) { continue; } if (length == length2) { return inner; } if (length <= length2 || location[length2] == '/') { if (configurationLocation == null) { configurationLocation = inner; } else if (num < length2) { configurationLocation = inner; num = length2; } } } return configurationLocation; } } [Flags] internal enum ConfigurationLockType { Attribute = 1, Element = 2, Exclude = 0x10 } public sealed class ConfigurationLockCollection : ICollection, IEnumerable { private ArrayList names; private ConfigurationElement element; private ConfigurationLockType lockType; private bool is_modified; private Hashtable valid_name_hash; private string valid_names; public string AttributeList { get { string[] array = new string[names.Count]; names.CopyTo(array, 0); return string.Join(",", array); } } public int Count => names.Count; [MonoTODO] public bool HasParentElements => false; [MonoTODO] public bool IsModified { get { return is_modified; } internal set { is_modified = value; } } [MonoTODO] public bool IsSynchronized => false; [MonoTODO] public object SyncRoot => this; internal ConfigurationLockCollection(ConfigurationElement element, ConfigurationLockType lockType) { names = new ArrayList(); this.element = element; this.lockType = lockType; } private void CheckName(string name) { bool flag = (lockType & ConfigurationLockType.Attribute) == ConfigurationLockType.Attribute; if (valid_name_hash == null) { valid_name_hash = new Hashtable(); foreach (ConfigurationProperty property in element.Properties) { if (flag != property.IsElement) { valid_name_hash.Add(property.Name, true); } } if (!flag) { ConfigurationElementCollection defaultCollection = element.GetDefaultCollection(); valid_name_hash.Add(defaultCollection.AddElementName, true); valid_name_hash.Add(defaultCollection.ClearElementName, true); valid_name_hash.Add(defaultCollection.RemoveElementName, true); } string[] array = new string[valid_name_hash.Keys.Count]; valid_name_hash.Keys.CopyTo(array, 0); valid_names = string.Join(",", array); } if (valid_name_hash[name] == null) { throw new ConfigurationErrorsException(string.Format("The {2} '{0}' is not valid in the locked list for this section. The following {3} can be locked: '{1}'", name, valid_names, flag ? "attribute" : "element", flag ? "attributes" : "elements")); } } public void Add(string name) { CheckName(name); if (!names.Contains(name)) { names.Add(name); is_modified = true; } } public void Clear() { names.Clear(); is_modified = true; } public bool Contains(string name) { return names.Contains(name); } public void CopyTo(string[] array, int index) { names.CopyTo(array, index); } public IEnumerator GetEnumerator() { return names.GetEnumerator(); } [MonoInternalNote("we can't possibly *always* return false here...")] public bool IsReadOnly(string name) { for (int i = 0; i < names.Count; i++) { if ((string)names[i] == name) { return false; } } throw new ConfigurationErrorsException($"The entry '{name}' is not in the collection."); } public void Remove(string name) { names.Remove(name); is_modified = true; } public void SetFromList(string attributeList) { Clear(); char[] separator = new char[1] { ',' }; string[] array = attributeList.Split(separator); foreach (string text in array) { Add(text.Trim()); } } void ICollection.CopyTo(Array array, int index) { names.CopyTo(array, index); } internal ConfigurationLockCollection() { ThrowStub.ThrowNotSupportedException(); } } public static class ConfigurationManager { private static InternalConfigurationFactory configFactory = new InternalConfigurationFactory(); private static IInternalConfigSystem configSystem = new ClientConfigurationSystem(); private static object lockobj = new object(); internal static IInternalConfigConfigurationFactory ConfigurationFactory => configFactory; internal static IInternalConfigSystem ConfigurationSystem => configSystem; public static NameValueCollection AppSettings => (NameValueCollection)GetSection("appSettings"); public static ConnectionStringSettingsCollection ConnectionStrings => ((ConnectionStringsSection)GetSection("connectionStrings")).ConnectionStrings; [MonoTODO("Evidence and version still needs work")] private static string GetAssemblyInfo(Assembly a) { object[] customAttributes = a.GetCustomAttributes(typeof(AssemblyProductAttribute), inherit: false); string arg = ((customAttributes == null || customAttributes.Length == 0) ? AppDomain.CurrentDomain.FriendlyName : ((AssemblyProductAttribute)customAttributes[0]).Product); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("evidencehere"); string arg2 = stringBuilder.ToString(); customAttributes = a.GetCustomAttributes(typeof(AssemblyVersionAttribute), inherit: false); return Path.Combine(path2: (customAttributes == null || customAttributes.Length == 0) ? "1.0.0.0" : ((AssemblyVersionAttribute)customAttributes[0]).Version, path1: $"{arg}_{arg2}"); } internal static Configuration OpenExeConfigurationInternal(ConfigurationUserLevel userLevel, Assembly calling_assembly, string exePath) { ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap(); if (userLevel != ConfigurationUserLevel.None) { if (userLevel != ConfigurationUserLevel.PerUserRoaming) { if (userLevel != ConfigurationUserLevel.PerUserRoamingAndLocal) { goto IL_00ea; } exeConfigurationFileMap.LocalUserConfigFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GetAssemblyInfo(calling_assembly)); exeConfigurationFileMap.LocalUserConfigFilename = Path.Combine(exeConfigurationFileMap.LocalUserConfigFilename, "user.config"); } exeConfigurationFileMap.RoamingUserConfigFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), GetAssemblyInfo(calling_assembly)); exeConfigurationFileMap.RoamingUserConfigFilename = Path.Combine(exeConfigurationFileMap.RoamingUserConfigFilename, "user.config"); } if (exePath == null || exePath.Length == 0) { exeConfigurationFileMap.ExeConfigFilename = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; } else { if (!Path.IsPathRooted(exePath)) { exePath = Path.GetFullPath(exePath); } if (!File.Exists(exePath)) { Exception inner = new ArgumentException("The specified path does not exist.", "exePath"); throw new ConfigurationErrorsException("Error Initializing the configuration system:", inner); } exeConfigurationFileMap.ExeConfigFilename = exePath + ".config"; } goto IL_00ea; IL_00ea: return ConfigurationFactory.Create(typeof(ExeConfigurationHost), exeConfigurationFileMap, userLevel); } public static Configuration OpenExeConfiguration(ConfigurationUserLevel userLevel) { return OpenExeConfigurationInternal(userLevel, Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly(), null); } public static Configuration OpenExeConfiguration(string exePath) { return OpenExeConfigurationInternal(ConfigurationUserLevel.None, Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly(), exePath); } [MonoLimitation("ConfigurationUserLevel parameter is not supported.")] public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel) { return ConfigurationFactory.Create(typeof(ExeConfigurationHost), fileMap, userLevel); } public static Configuration OpenMachineConfiguration() { ConfigurationFileMap configurationFileMap = new ConfigurationFileMap(); return ConfigurationFactory.Create(typeof(MachineConfigurationHost), configurationFileMap); } public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap) { return ConfigurationFactory.Create(typeof(MachineConfigurationHost), fileMap); } public static object GetSection(string sectionName) { object section = ConfigurationSystem.GetSection(sectionName); if (section is ConfigurationSection) { return ((ConfigurationSection)section).GetRuntimeObject(); } return section; } public static void RefreshSection(string sectionName) { ConfigurationSystem.RefreshConfig(sectionName); } internal static IInternalConfigSystem ChangeConfigurationSystem(IInternalConfigSystem newSystem) { if (newSystem == null) { throw new ArgumentNullException("newSystem"); } lock (lockobj) { IInternalConfigSystem result = configSystem; configSystem = newSystem; return result; } } public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel, bool preLoad) { ThrowStub.ThrowNotSupportedException(); return null; } } [Serializable] public sealed class ConfigurationPermission : CodeAccessPermission, IUnrestrictedPermission { private bool unrestricted; public ConfigurationPermission(PermissionState state) { unrestricted = state == PermissionState.Unrestricted; } public override IPermission Copy() { return (IPermission)(object)new ConfigurationPermission(unrestricted ? PermissionState.Unrestricted : PermissionState.None); } public override void FromXml(SecurityElement securityElement) { if (securityElement == null) { throw new ArgumentNullException("securityElement"); } if (securityElement.Tag != "IPermission") { throw new ArgumentException("securityElement"); } string text = securityElement.Attribute("Unrestricted"); if (text != null) { unrestricted = string.Compare(text, "true", StringComparison.InvariantCultureIgnoreCase) == 0; } } public override IPermission Intersect(IPermission target) { if (target == null) { return null; } if (!(target is ConfigurationPermission configurationPermission)) { throw new ArgumentException("target"); } return (IPermission)(object)new ConfigurationPermission((unrestricted && configurationPermission.IsUnrestricted()) ? PermissionState.Unrestricted : PermissionState.None); } public override IPermission Union(IPermission target) { if (target == null) { return ((CodeAccessPermission)this).Copy(); } if (!(target is ConfigurationPermission configurationPermission)) { throw new ArgumentException("target"); } return (IPermission)(object)new ConfigurationPermission((unrestricted || configurationPermission.IsUnrestricted()) ? PermissionState.Unrestricted : PermissionState.None); } public override bool IsSubsetOf(IPermission target) { if (target == null) { return !unrestricted; } if (!(target is ConfigurationPermission configurationPermission)) { throw new ArgumentException("target"); } if (unrestricted) { return configurationPermission.IsUnrestricted(); } return true; } public bool IsUnrestricted() { return unrestricted; } public override SecurityElement ToXml() { SecurityElement securityElement = new SecurityElement("IPermission"); securityElement.AddAttribute("class", ((object)this).GetType().AssemblyQualifiedName); securityElement.AddAttribute("version", "1"); if (unrestricted) { securityElement.AddAttribute("Unrestricted", "true"); } return securityElement; } } [Serializable] [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public sealed class ConfigurationPermissionAttribute : CodeAccessSecurityAttribute { public ConfigurationPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { return (IPermission)(object)new ConfigurationPermission(base.Unrestricted ? PermissionState.Unrestricted : PermissionState.None); } } public sealed class ConfigurationProperty { internal static readonly object NoDefaultValue = new object(); private string name; private Type type; private object default_value; private TypeConverter converter; private ConfigurationValidatorBase validation; private ConfigurationPropertyOptions flags; private string description; private ConfigurationCollectionAttribute collectionAttribute; public TypeConverter Converter => converter; public object DefaultValue => default_value; public bool IsKey => (flags & ConfigurationPropertyOptions.IsKey) != 0; public bool IsRequired => (flags & ConfigurationPropertyOptions.IsRequired) != 0; public bool IsDefaultCollection => (flags & ConfigurationPropertyOptions.IsDefaultCollection) != 0; public string Name => name; public string Description => description; public Type Type => type; public ConfigurationValidatorBase Validator => validation; internal bool IsElement => typeof(ConfigurationElement).IsAssignableFrom(type); internal ConfigurationCollectionAttribute CollectionAttribute { get { return collectionAttribute; } set { collectionAttribute = value; } } public bool IsAssemblyStringTransformationRequired { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } } public bool IsTypeStringTransformationRequired { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } } public bool IsVersionCheckRequired { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } } public ConfigurationProperty(string name, Type type) : this(name, type, NoDefaultValue, TypeDescriptor.GetConverter(type), new DefaultValidator(), ConfigurationPropertyOptions.None, null) { } public ConfigurationProperty(string name, Type type, object defaultValue) : this(name, type, defaultValue, TypeDescriptor.GetConverter(type), new DefaultValidator(), ConfigurationPropertyOptions.None, null) { } public ConfigurationProperty(string name, Type type, object defaultValue, ConfigurationPropertyOptions options) : this(name, type, defaultValue, TypeDescriptor.GetConverter(type), new DefaultValidator(), options, null) { } public ConfigurationProperty(string name, Type type, object defaultValue, TypeConverter typeConverter, ConfigurationValidatorBase validator, ConfigurationPropertyOptions options) : this(name, type, defaultValue, typeConverter, validator, options, null) { } public ConfigurationProperty(string name, Type type, object defaultValue, TypeConverter typeConverter, ConfigurationValidatorBase validator, ConfigurationPropertyOptions options, string description) { this.name = name; converter = ((typeConverter != null) ? typeConverter : TypeDescriptor.GetConverter(type)); if (defaultValue != null) { if (defaultValue == NoDefaultValue) { defaultValue = Type.GetTypeCode(type) switch { TypeCode.Object => null, TypeCode.String => string.Empty, _ => Activator.CreateInstance(type), }; } else if (!type.IsAssignableFrom(defaultValue.GetType())) { if (!converter.CanConvertFrom(defaultValue.GetType())) { throw new ConfigurationErrorsException($"The default value for property '{name}' has a different type than the one of the property itself: expected {type} but was {defaultValue.GetType()}"); } defaultValue = converter.ConvertFrom(defaultValue); } } default_value = defaultValue; flags = options; this.type = type; validation = ((validator != null) ? validator : new DefaultValidator()); this.description = description; } internal object ConvertFromString(string value) { if (converter != null) { return converter.ConvertFromInvariantString(value); } throw new NotImplementedException(); } internal string ConvertToString(object value) { if (converter != null) { return converter.ConvertToInvariantString(value); } throw new NotImplementedException(); } internal void Validate(object value) { if (validation != null) { validation.Validate(value); } } } [AttributeUsage(AttributeTargets.Property)] public sealed class ConfigurationPropertyAttribute : Attribute { private string name; private object default_value = ConfigurationProperty.NoDefaultValue; private ConfigurationPropertyOptions flags; public bool IsKey { get { return (flags & ConfigurationPropertyOptions.IsKey) != 0; } set { if (value) { flags |= ConfigurationPropertyOptions.IsKey; } else { flags &= ~ConfigurationPropertyOptions.IsKey; } } } public bool IsDefaultCollection { get { return (flags & ConfigurationPropertyOptions.IsDefaultCollection) != 0; } set { if (value) { flags |= ConfigurationPropertyOptions.IsDefaultCollection; } else { flags &= ~ConfigurationPropertyOptions.IsDefaultCollection; } } } public object DefaultValue { get { return default_value; } set { default_value = value; } } public ConfigurationPropertyOptions Options { get { return flags; } set { flags = value; } } public string Name => name; public bool IsRequired { get { return (flags & ConfigurationPropertyOptions.IsRequired) != 0; } set { if (value) { flags |= ConfigurationPropertyOptions.IsRequired; } else { flags &= ~ConfigurationPropertyOptions.IsRequired; } } } public ConfigurationPropertyAttribute(string name) { this.name = name; } } public class ConfigurationPropertyCollection : ICollection, IEnumerable { private List collection; public int Count => collection.Count; public ConfigurationProperty this[string name] { get { foreach (ConfigurationProperty item in collection) { if (item.Name == name) { return item; } } return null; } } public bool IsSynchronized => false; public object SyncRoot => collection; public ConfigurationPropertyCollection() { collection = new List(); } public void Add(ConfigurationProperty property) { if (property == null) { throw new ArgumentNullException("property"); } collection.Add(property); } public bool Contains(string name) { ConfigurationProperty configurationProperty = this[name]; if (configurationProperty == null) { return false; } return collection.Contains(configurationProperty); } public void CopyTo(ConfigurationProperty[] array, int index) { collection.CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { ((ICollection)collection).CopyTo(array, index); } public IEnumerator GetEnumerator() { return collection.GetEnumerator(); } public bool Remove(string name) { return collection.Remove(this[name]); } public void Clear() { collection.Clear(); } } [Flags] public enum ConfigurationPropertyOptions { None = 0, IsDefaultCollection = 1, IsRequired = 2, IsKey = 4, IsTypeStringTransformationRequired = 8, IsAssemblyStringTransformationRequired = 0x10, IsVersionCheckRequired = 0x20 } internal class ConfigurationSaveEventArgs : EventArgs { public string StreamPath { get; private set; } public bool Start { get; private set; } public object Context { get; private set; } public bool Failed { get; private set; } public Exception Exception { get; private set; } public ConfigurationSaveEventArgs(string streamPath, bool start, Exception ex, object context) { StreamPath = streamPath; Start = start; Failed = ex != null; Exception = ex; Context = context; } } internal delegate void ConfigurationSaveEventHandler(Configuration sender, ConfigurationSaveEventArgs args); public enum ConfigurationSaveMode { Minimal = 1, Full = 2, Modified = 0 } public abstract class ConfigurationSection : ConfigurationElement { private SectionInformation sectionInformation; private IConfigurationSectionHandler section_handler; private string externalDataXml; private object _configContext; internal string ExternalDataXml => externalDataXml; internal IConfigurationSectionHandler SectionHandler { get { return section_handler; } set { section_handler = value; } } [MonoTODO] public SectionInformation SectionInformation { get { if (sectionInformation == null) { sectionInformation = new SectionInformation(); } return sectionInformation; } } internal object ConfigContext { get { return _configContext; } set { _configContext = value; } } [MonoTODO("Provide ConfigContext. Likely the culprit of bug #322493")] protected internal virtual object GetRuntimeObject() { if (SectionHandler != null) { object obj = ((sectionInformation != null) ? sectionInformation.GetParentSection() : null)?.GetRuntimeObject(); if (base.RawXml == null) { return obj; } try { XmlReader reader = (XmlReader)(object)new ConfigXmlTextReader(new StringReader(base.RawXml), base.Configuration.FilePath); DoDeserializeSection(reader); if (!string.IsNullOrEmpty(SectionInformation.ConfigSource)) { string configFilePath = SectionInformation.ConfigFilePath; configFilePath = (string.IsNullOrEmpty(configFilePath) ? string.Empty : Path.GetDirectoryName(configFilePath)); string path = Path.Combine(configFilePath, SectionInformation.ConfigSource); if (File.Exists(path)) { base.RawXml = File.ReadAllText(path); SectionInformation.SetRawXml(base.RawXml); } } } catch { } XmlDocument val = (XmlDocument)(object)new ConfigurationXmlDocument(); val.LoadXml(base.RawXml); return SectionHandler.Create(obj, ConfigContext, (XmlNode)(object)val.DocumentElement); } return this; } [MonoTODO] protected internal override bool IsModified() { return base.IsModified(); } [MonoTODO] protected internal override void ResetModified() { base.ResetModified(); } private ConfigurationElement CreateElement(Type t) { ConfigurationElement configurationElement = (ConfigurationElement)Activator.CreateInstance(t); configurationElement.Init(); configurationElement.Configuration = base.Configuration; if (IsReadOnly()) { configurationElement.SetReadOnly(); } return configurationElement; } private void DoDeserializeSection(XmlReader reader) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_0088: Unknown result type (might be due to invalid IL or missing references) reader.MoveToContent(); string text = null; string text2 = null; while (reader.MoveToNextAttribute()) { string localName = reader.LocalName; if (localName == "configProtectionProvider") { text = reader.Value; } else if (localName == "configSource") { text2 = reader.Value; } } if (text != null) { ProtectedConfigurationProvider provider = ProtectedConfiguration.GetProvider(text, throwOnError: true); XmlDocument val = (XmlDocument)(object)new ConfigurationXmlDocument(); reader.MoveToElement(); val.Load((TextReader)new StringReader(reader.ReadInnerXml())); reader = (XmlReader)new XmlNodeReader(provider.Decrypt((XmlNode)(object)val)); SectionInformation.ProtectSection(text); reader.MoveToContent(); } if (text2 != null) { SectionInformation.ConfigSource = text2; } SectionInformation.SetRawXml(base.RawXml); if (SectionHandler == null) { DeserializeElement(reader, serializeCollectionKey: false); } } [MonoInternalNote("find the proper location for the decryption stuff")] protected internal virtual void DeserializeSection(XmlReader reader) { try { DoDeserializeSection(reader); } catch (ConfigurationErrorsException ex) { throw new ConfigurationErrorsException($"Error deserializing configuration section {SectionInformation.Name}: {((Exception)(object)ex).Message}"); } } internal void DeserializeConfigSource(string basePath) { string configSource = SectionInformation.ConfigSource; if (!string.IsNullOrEmpty(configSource)) { if (Path.IsPathRooted(configSource)) { throw new ConfigurationErrorsException("The configSource attribute must be a relative physical path."); } if (HasLocalModifications()) { throw new ConfigurationErrorsException("A section using 'configSource' may contain no other attributes or elements."); } string text = Path.Combine(basePath, configSource); if (!File.Exists(text)) { base.RawXml = null; SectionInformation.SetRawXml(null); throw new ConfigurationErrorsException($"Unable to open configSource file '{text}'."); } base.RawXml = File.ReadAllText(text); SectionInformation.SetRawXml(base.RawXml); DeserializeElement((XmlReader)(object)new ConfigXmlTextReader(new StringReader(base.RawXml), text), serializeCollectionKey: false); } } protected internal virtual string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown externalDataXml = null; ConfigurationElement configurationElement; if (parentElement != null) { configurationElement = CreateElement(GetType()); configurationElement.Unmerge(this, parentElement, saveMode); } else { configurationElement = this; } configurationElement.PrepareSave(parentElement, saveMode); bool flag = configurationElement.HasValues(parentElement, saveMode); string result; using (StringWriter stringWriter = new StringWriter()) { XmlTextWriter val = new XmlTextWriter((TextWriter)stringWriter); try { val.Formatting = (Formatting)1; if (flag) { configurationElement.SerializeToXmlElement((XmlWriter)(object)val, name); } else if (saveMode == ConfigurationSaveMode.Modified && configurationElement.IsModified()) { ((XmlWriter)val).WriteStartElement(name); ((XmlWriter)val).WriteEndElement(); } ((XmlWriter)val).Close(); } finally { ((IDisposable)val)?.Dispose(); } result = stringWriter.ToString(); } string configSource = SectionInformation.ConfigSource; if (string.IsNullOrEmpty(configSource)) { return result; } externalDataXml = result; using StringWriter stringWriter2 = new StringWriter(); bool flag2 = !string.IsNullOrEmpty(name); XmlTextWriter val2 = new XmlTextWriter((TextWriter)stringWriter2); try { if (flag2) { ((XmlWriter)val2).WriteStartElement(name); } ((XmlWriter)val2).WriteAttributeString("configSource", configSource); if (flag2) { ((XmlWriter)val2).WriteEndElement(); } } finally { ((IDisposable)val2)?.Dispose(); } return stringWriter2.ToString(); } protected internal virtual bool ShouldSerializeElementInTargetVersion(ConfigurationElement element, string elementName, FrameworkName targetFramework) { ThrowStub.ThrowNotSupportedException(); return default(bool); } protected internal virtual bool ShouldSerializePropertyInTargetVersion(ConfigurationProperty property, string propertyName, FrameworkName targetFramework, ConfigurationElement parentConfigurationElement) { ThrowStub.ThrowNotSupportedException(); return default(bool); } protected internal virtual bool ShouldSerializeSectionInTargetVersion(FrameworkName targetFramework) { ThrowStub.ThrowNotSupportedException(); return default(bool); } } [Serializable] public sealed class ConfigurationSectionCollection : NameObjectCollectionBase { private SectionGroupInfo group; private Configuration config; private static readonly object lockObject = new object(); public override KeysCollection Keys => group.Sections.Keys; public override int Count => group.Sections.Count; public ConfigurationSection this[string name] { get { ConfigurationSection configurationSection = BaseGet(name) as ConfigurationSection; if (configurationSection == null) { if (!(group.Sections[name] is SectionInfo sectionInfo)) { return null; } configurationSection = config.GetSectionInstance(sectionInfo, createDefaultInstance: true); if (configurationSection == null) { return null; } lock (lockObject) { BaseSet(name, configurationSection); } } return configurationSection; } } public ConfigurationSection this[int index] => this[GetKey(index)]; internal ConfigurationSectionCollection(Configuration config, SectionGroupInfo group) : base(StringComparer.Ordinal) { this.config = config; this.group = group; } public void Add(string name, ConfigurationSection section) { config.CreateSection(group, name, section); } public void Clear() { if (group.Sections == null) { return; } foreach (ConfigInfo section in group.Sections) { config.RemoveConfigInfo(section); } } public void CopyTo(ConfigurationSection[] array, int index) { for (int i = 0; i < group.Sections.Count; i++) { array[i + index] = this[i]; } } public ConfigurationSection Get(int index) { return this[index]; } public ConfigurationSection Get(string name) { return this[name]; } public override IEnumerator GetEnumerator() { foreach (string allKey in group.Sections.AllKeys) { yield return this[allKey]; } } public string GetKey(int index) { return group.Sections.GetKey(index); } public void Remove(string name) { if (group.Sections[name] is SectionInfo sectionInfo) { config.RemoveConfigInfo(sectionInfo); } } public void RemoveAt(int index) { SectionInfo sectionInfo = group.Sections[index] as SectionInfo; config.RemoveConfigInfo(sectionInfo); } [MonoTODO] [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } internal ConfigurationSectionCollection() { ThrowStub.ThrowNotSupportedException(); } } public class ConfigurationSectionGroup { private bool require_declaration; private string name; private string type_name; private ConfigurationSectionCollection sections; private ConfigurationSectionGroupCollection groups; private Configuration config; private SectionGroupInfo group; private bool initialized; private Configuration Config { get { if (config == null) { throw new InvalidOperationException("ConfigurationSectionGroup cannot be edited until it is added to a Configuration instance as its descendant"); } return config; } } [MonoTODO] public bool IsDeclared => false; [MonoTODO] public bool IsDeclarationRequired => require_declaration; public string Name => name; [MonoInternalNote("Check if this is correct")] public string SectionGroupName => group.XPath; public ConfigurationSectionGroupCollection SectionGroups { get { if (groups == null) { groups = new ConfigurationSectionGroupCollection(Config, group); } return groups; } } public ConfigurationSectionCollection Sections { get { if (sections == null) { sections = new ConfigurationSectionCollection(Config, group); } return sections; } } public string Type { get { return type_name; } set { type_name = value; } } internal void Initialize(Configuration config, SectionGroupInfo group) { if (initialized) { throw new SystemException("INTERNAL ERROR: this configuration section is being initialized twice: " + GetType()); } initialized = true; this.config = config; this.group = group; } internal void SetName(string name) { this.name = name; } [MonoTODO] public void ForceDeclaration(bool force) { require_declaration = force; } public void ForceDeclaration() { ForceDeclaration(force: true); } protected internal virtual bool ShouldSerializeSectionGroupInTargetVersion(FrameworkName targetFramework) { ThrowStub.ThrowNotSupportedException(); return default(bool); } } [Serializable] public sealed class ConfigurationSectionGroupCollection : NameObjectCollectionBase { private SectionGroupInfo group; private Configuration config; public override KeysCollection Keys => group.Groups.Keys; public override int Count => group.Groups.Count; public ConfigurationSectionGroup this[string name] { get { ConfigurationSectionGroup configurationSectionGroup = BaseGet(name) as ConfigurationSectionGroup; if (configurationSectionGroup == null) { if (!(group.Groups[name] is SectionGroupInfo sectionGroupInfo)) { return null; } configurationSectionGroup = config.GetSectionGroupInstance(sectionGroupInfo); BaseSet(name, configurationSectionGroup); } return configurationSectionGroup; } } public ConfigurationSectionGroup this[int index] => this[GetKey(index)]; internal ConfigurationSectionGroupCollection(Configuration config, SectionGroupInfo group) : base(StringComparer.Ordinal) { this.config = config; this.group = group; } public void Add(string name, ConfigurationSectionGroup sectionGroup) { config.CreateSectionGroup(group, name, sectionGroup); } public void Clear() { if (group.Groups == null) { return; } foreach (ConfigInfo group in group.Groups) { config.RemoveConfigInfo(group); } } public void CopyTo(ConfigurationSectionGroup[] array, int index) { for (int i = 0; i < group.Groups.Count; i++) { array[i + index] = this[i]; } } public ConfigurationSectionGroup Get(int index) { return this[index]; } public ConfigurationSectionGroup Get(string name) { return this[name]; } public override IEnumerator GetEnumerator() { return group.Groups.AllKeys.GetEnumerator(); } public string GetKey(int index) { return group.Groups.GetKey(index); } public void Remove(string name) { if (group.Groups[name] is SectionGroupInfo sectionGroupInfo) { config.RemoveConfigInfo(sectionGroupInfo); } } public void RemoveAt(int index) { SectionGroupInfo sectionGroupInfo = group.Groups[index] as SectionGroupInfo; config.RemoveConfigInfo(sectionGroupInfo); } [MonoTODO] [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } internal ConfigurationSectionGroupCollection() { ThrowStub.ThrowNotSupportedException(); } } public enum ConfigurationUserLevel { None = 0, PerUserRoaming = 10, PerUserRoamingAndLocal = 20 } [AttributeUsage(AttributeTargets.Property)] public class ConfigurationValidatorAttribute : Attribute { private Type validatorType; private ConfigurationValidatorBase instance; public virtual ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = (ConfigurationValidatorBase)Activator.CreateInstance(validatorType); } return instance; } } public Type ValidatorType => validatorType; protected ConfigurationValidatorAttribute() { } public ConfigurationValidatorAttribute(Type validator) { validatorType = validator; } } public abstract class ConfigurationValidatorBase { public virtual bool CanValidate(Type type) { return false; } public abstract void Validate(object value); } public sealed class ConnectionStringSettings : ConfigurationElement { private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propConnectionString; private static readonly ConfigurationProperty _propName; private static readonly ConfigurationProperty _propProviderName; protected internal override ConfigurationPropertyCollection Properties => _properties; [ConfigurationProperty("name", DefaultValue = "", Options = (ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey))] public string Name { get { return (string)base[_propName]; } set { base[_propName] = value; } } [ConfigurationProperty("providerName", DefaultValue = "System.Data.SqlClient")] public string ProviderName { get { return (string)base[_propProviderName]; } set { base[_propProviderName] = value; } } [ConfigurationProperty("connectionString", DefaultValue = "", Options = ConfigurationPropertyOptions.IsRequired)] public string ConnectionString { get { return (string)base[_propConnectionString]; } set { base[_propConnectionString] = value; } } static ConnectionStringSettings() { _properties = new ConfigurationPropertyCollection(); _propName = new ConfigurationProperty("name", typeof(string), null, TypeDescriptor.GetConverter(typeof(string)), null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey); _propProviderName = new ConfigurationProperty("providerName", typeof(string), "", ConfigurationPropertyOptions.None); _propConnectionString = new ConfigurationProperty("connectionString", typeof(string), "", ConfigurationPropertyOptions.IsRequired); _properties.Add(_propName); _properties.Add(_propProviderName); _properties.Add(_propConnectionString); } public ConnectionStringSettings() { } public ConnectionStringSettings(string name, string connectionString) : this(name, connectionString, "") { } public ConnectionStringSettings(string name, string connectionString, string providerName) { Name = name; ConnectionString = connectionString; ProviderName = providerName; } public override string ToString() { return ConnectionString; } } [ConfigurationCollection(typeof(ConnectionStringSettings), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)] public sealed class ConnectionStringSettingsCollection : ConfigurationElementCollection { public new ConnectionStringSettings this[string name] { get { IEnumerator enumerator = GetEnumerator(); try { while (enumerator.MoveNext()) { ConfigurationElement configurationElement = (ConfigurationElement)enumerator.Current; if (configurationElement is ConnectionStringSettings && string.Compare(((ConnectionStringSettings)configurationElement).Name, name, ignoreCase: true, CultureInfo.InvariantCulture) == 0) { return configurationElement as ConnectionStringSettings; } } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } return null; } } public ConnectionStringSettings this[int index] { get { return (ConnectionStringSettings)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } [MonoTODO] protected internal override ConfigurationPropertyCollection Properties => base.Properties; protected override ConfigurationElement CreateNewElement() { return new ConnectionStringSettings(); } protected override object GetElementKey(ConfigurationElement element) { return ((ConnectionStringSettings)element).Name; } public void Add(ConnectionStringSettings settings) { BaseAdd(settings); } public void Clear() { BaseClear(); } public int IndexOf(ConnectionStringSettings settings) { return BaseIndexOf(settings); } public void Remove(ConnectionStringSettings settings) { BaseRemove(settings.Name); } public void Remove(string name) { BaseRemove(name); } public void RemoveAt(int index) { BaseRemoveAt(index); } protected override void BaseAdd(int index, ConfigurationElement element) { if (!(element is ConnectionStringSettings)) { base.BaseAdd(element); } if (IndexOf((ConnectionStringSettings)element) >= 0) { throw new ConfigurationErrorsException($"The element {((ConnectionStringSettings)element).Name} already exist!"); } this[index] = (ConnectionStringSettings)element; } } public sealed class ConnectionStringsSection : ConfigurationSection { private static readonly ConfigurationProperty _propConnectionStrings; private static ConfigurationPropertyCollection _properties; [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)] public ConnectionStringSettingsCollection ConnectionStrings => (ConnectionStringSettingsCollection)base[_propConnectionStrings]; protected internal override ConfigurationPropertyCollection Properties => _properties; static ConnectionStringsSection() { _propConnectionStrings = new ConfigurationProperty("", typeof(ConnectionStringSettingsCollection), null, ConfigurationPropertyOptions.IsDefaultCollection); _properties = new ConfigurationPropertyCollection(); _properties.Add(_propConnectionStrings); } protected internal override object GetRuntimeObject() { return base.GetRuntimeObject(); } } public sealed class ContextInformation { private object ctx; private Configuration config; public object HostingContext => ctx; [MonoInternalNote("should this use HostingContext instead?")] public bool IsMachineLevel => config.ConfigPath == "machine"; internal ContextInformation(Configuration config, object ctx) { this.ctx = ctx; this.config = config; } public object GetSection(string sectionName) { return config.GetSection(sectionName); } internal ContextInformation() { ThrowStub.ThrowNotSupportedException(); } } public sealed class DefaultSection : ConfigurationSection { private static ConfigurationPropertyCollection properties; protected internal override ConfigurationPropertyCollection Properties => properties; static DefaultSection() { properties = new ConfigurationPropertyCollection(); } protected internal override void DeserializeSection(XmlReader xmlReader) { if (base.RawXml == null) { base.RawXml = xmlReader.ReadOuterXml(); } else { xmlReader.Skip(); } } [MonoTODO] protected internal override bool IsModified() { return base.IsModified(); } [MonoTODO] protected internal override void Reset(ConfigurationElement parentSection) { base.Reset(parentSection); } [MonoTODO] protected internal override void ResetModified() { base.ResetModified(); } [MonoTODO] protected internal override string SerializeSection(ConfigurationElement parentSection, string name, ConfigurationSaveMode saveMode) { return base.SerializeSection(parentSection, name, saveMode); } } public sealed class DefaultValidator : ConfigurationValidatorBase { public override bool CanValidate(Type type) { return true; } public override void Validate(object value) { } } public sealed class DpapiProtectedConfigurationProvider : ProtectedConfigurationProvider { private bool useMachineProtection; private const string NotSupportedReason = "DpapiProtectedConfigurationProvider depends on the Microsoft Data\nProtection API, and is unimplemented in Mono. For portability's sake,\nit is suggested that you use the RsaProtectedConfigurationProvider."; public bool UseMachineProtection => useMachineProtection; [MonoNotSupported("DpapiProtectedConfigurationProvider depends on the Microsoft Data\nProtection API, and is unimplemented in Mono. For portability's sake,\nit is suggested that you use the RsaProtectedConfigurationProvider.")] public override XmlNode Decrypt(XmlNode encryptedNode) { throw new NotSupportedException("DpapiProtectedConfigurationProvider depends on the Microsoft Data\nProtection API, and is unimplemented in Mono. For portability's sake,\nit is suggested that you use the RsaProtectedConfigurationProvider."); } [MonoNotSupported("DpapiProtectedConfigurationProvider depends on the Microsoft Data\nProtection API, and is unimplemented in Mono. For portability's sake,\nit is suggested that you use the RsaProtectedConfigurationProvider.")] public override XmlNode Encrypt(XmlNode node) { throw new NotSupportedException("DpapiProtectedConfigurationProvider depends on the Microsoft Data\nProtection API, and is unimplemented in Mono. For portability's sake,\nit is suggested that you use the RsaProtectedConfigurationProvider."); } [MonoTODO] public override void Initialize(string name, NameValueCollection configurationValues) { base.Initialize(name, configurationValues); string text = configurationValues["useMachineProtection"]; if (text != null && text.ToLowerInvariant() == "true") { useMachineProtection = true; } } } public sealed class ElementInformation { private readonly PropertyInformation propertyInfo; private readonly ConfigurationElement owner; private readonly PropertyInformationCollection properties; [MonoTODO] public ICollection Errors { get { throw new NotImplementedException(); } } public bool IsCollection => owner is ConfigurationElementCollection; public bool IsLocked { get { if (propertyInfo == null) { return false; } return propertyInfo.IsLocked; } } [MonoTODO("Support multiple levels of inheritance")] public bool IsPresent => owner.IsElementPresent; public int LineNumber { get { if (propertyInfo == null) { return 0; } return propertyInfo.LineNumber; } } public string Source { get { if (propertyInfo == null) { return null; } return propertyInfo.Source; } } public Type Type { get { if (propertyInfo == null) { return owner.GetType(); } return propertyInfo.Type; } } public ConfigurationValidatorBase Validator { get { if (propertyInfo == null) { return new DefaultValidator(); } return propertyInfo.Validator; } } public PropertyInformationCollection Properties => properties; internal ElementInformation(ConfigurationElement owner, PropertyInformation propertyInfo) { this.propertyInfo = propertyInfo; this.owner = owner; properties = new PropertyInformationCollection(); foreach (ConfigurationProperty property in owner.Properties) { properties.Add(new PropertyInformation(owner, property)); } } internal void Reset(ElementInformation parentInfo) { foreach (PropertyInformation property in Properties) { PropertyInformation parentProperty = parentInfo.Properties[property.Name]; property.Reset(parentProperty); } } internal ElementInformation() { ThrowStub.ThrowNotSupportedException(); } } public sealed class ExeConfigurationFileMap : ConfigurationFileMap { private string exeConfigFilename; private string localUserConfigFilename; private string roamingUserConfigFilename; public string ExeConfigFilename { get { return exeConfigFilename; } set { exeConfigFilename = value; } } public string LocalUserConfigFilename { get { return localUserConfigFilename; } set { localUserConfigFilename = value; } } public string RoamingUserConfigFilename { get { return roamingUserConfigFilename; } set { roamingUserConfigFilename = value; } } public ExeConfigurationFileMap() { exeConfigFilename = ""; localUserConfigFilename = ""; roamingUserConfigFilename = ""; } public override object Clone() { return new ExeConfigurationFileMap { exeConfigFilename = exeConfigFilename, localUserConfigFilename = localUserConfigFilename, roamingUserConfigFilename = roamingUserConfigFilename, MachineConfigFilename = base.MachineConfigFilename }; } public ExeConfigurationFileMap(string machineConfigFileName) { ThrowStub.ThrowNotSupportedException(); } } public sealed class ExeContext { private string path; private ConfigurationUserLevel level; public string ExePath => path; public ConfigurationUserLevel UserLevel => level; internal ExeContext(string path, ConfigurationUserLevel level) { this.path = path; this.level = level; } internal ExeContext() { ThrowStub.ThrowNotSupportedException(); } } public sealed class GenericEnumConverter : ConfigurationConverterBase { private Type typeEnum; public GenericEnumConverter(Type typeEnum) { if (typeEnum == null) { throw new ArgumentNullException("typeEnum"); } this.typeEnum = typeEnum; } public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { if (data == null) { throw new ArgumentException(); } return Enum.Parse(typeEnum, (string)data); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { return value.ToString(); } } internal interface IConfigXmlNode { string Filename { get; } int LineNumber { get; } } public sealed class IgnoreSection : ConfigurationSection { private string xml; private static ConfigurationPropertyCollection properties; protected internal override ConfigurationPropertyCollection Properties => properties; static IgnoreSection() { properties = new ConfigurationPropertyCollection(); } protected internal override bool IsModified() { return false; } protected internal override void DeserializeSection(XmlReader xmlReader) { xml = xmlReader.ReadOuterXml(); } [MonoTODO] protected internal override void Reset(ConfigurationElement parentSection) { base.Reset(parentSection); } [MonoTODO] protected internal override void ResetModified() { base.ResetModified(); } protected internal override string SerializeSection(ConfigurationElement parentSection, string name, ConfigurationSaveMode saveMode) { return xml; } } public sealed class InfiniteIntConverter : ConfigurationConverterBase { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { if ((string)data == "Infinite") { return int.MaxValue; } return Convert.ToInt32((string)data, 10); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value.GetType() != typeof(int)) { throw new ArgumentException(); } if ((int)value == int.MaxValue) { return "Infinite"; } return value.ToString(); } } public sealed class InfiniteTimeSpanConverter : ConfigurationConverterBase { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { if ((string)data == "Infinite") { return TimeSpan.MaxValue; } return TimeSpan.Parse((string)data); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value.GetType() != typeof(TimeSpan)) { throw new ArgumentException(); } if ((TimeSpan)value == TimeSpan.MaxValue) { return "Infinite"; } return value.ToString(); } } public class IntegerValidator : ConfigurationValidatorBase { private bool rangeIsExclusive; private int minValue; private int maxValue = int.MaxValue; private int resolution; public IntegerValidator(int minValue, int maxValue, bool rangeIsExclusive, int resolution) { if (minValue != 0) { this.minValue = minValue; } if (maxValue != 0) { this.maxValue = maxValue; } this.rangeIsExclusive = rangeIsExclusive; this.resolution = resolution; } public IntegerValidator(int minValue, int maxValue, bool rangeIsExclusive) : this(minValue, maxValue, rangeIsExclusive, 0) { } public IntegerValidator(int minValue, int maxValue) : this(minValue, maxValue, rangeIsExclusive: false, 0) { } public override bool CanValidate(Type type) { return type == typeof(int); } public override void Validate(object value) { int num = (int)value; if (!rangeIsExclusive) { if (num < minValue || num > maxValue) { throw new ArgumentException("The value must be in the range " + minValue + " - " + maxValue); } } else if (num >= minValue && num <= maxValue) { throw new ArgumentException("The value must not be in the range " + minValue + " - " + maxValue); } if (resolution != 0 && num % resolution != 0) { throw new ArgumentException("The value must have a resolution of " + resolution); } } } [AttributeUsage(AttributeTargets.Property)] public sealed class IntegerValidatorAttribute : ConfigurationValidatorAttribute { private bool excludeRange; private int maxValue; private int minValue; private ConfigurationValidatorBase instance; public bool ExcludeRange { get { return excludeRange; } set { excludeRange = value; instance = null; } } public int MaxValue { get { return maxValue; } set { maxValue = value; instance = null; } } public int MinValue { get { return minValue; } set { minValue = value; instance = null; } } public override ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = new IntegerValidator(minValue, maxValue, excludeRange); } return instance; } } } internal class InternalConfigurationFactory : IInternalConfigConfigurationFactory { public Configuration Create(Type typeConfigHost, params object[] hostInitConfigurationParams) { InternalConfigurationSystem internalConfigurationSystem = new InternalConfigurationSystem(); internalConfigurationSystem.Init(typeConfigHost, hostInitConfigurationParams); return new Configuration(internalConfigurationSystem, null); } public string NormalizeLocationSubPath(string subPath, IConfigErrorInfo errorInfo) { return subPath; } } internal class InternalConfigurationSystem : IConfigSystem { private IInternalConfigHost host; private IInternalConfigRoot root; private object[] hostInitParams; public IInternalConfigHost Host => host; public IInternalConfigRoot Root => root; public void Init(Type typeConfigHost, params object[] hostInitParams) { this.hostInitParams = hostInitParams; host = (IInternalConfigHost)Activator.CreateInstance(typeConfigHost); root = new InternalConfigurationRoot(); root.Init(host, isDesignTime: false); } public void InitForConfiguration(ref string locationConfigPath, out string parentConfigPath, out string parentLocationConfigPath) { host.InitForConfiguration(ref locationConfigPath, out parentConfigPath, out parentLocationConfigPath, root, hostInitParams); } } internal abstract class InternalConfigurationHost : IInternalConfigHost { public virtual bool IsRemote { get { throw new NotImplementedException(); } } public virtual bool SupportsChangeNotifications => false; public virtual bool SupportsLocation => false; public virtual bool SupportsPath => false; public virtual bool SupportsRefresh => false; public virtual object CreateConfigurationContext(string configPath, string locationSubPath) { return null; } public virtual object CreateDeprecatedConfigContext(string configPath) { return null; } public virtual void DeleteStream(string streamName) { File.Delete(streamName); } string IInternalConfigHost.DecryptSection(string encryptedXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedSection) { return protectedSection.DecryptSection(encryptedXml, protectionProvider); } string IInternalConfigHost.EncryptSection(string clearXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedSection) { return protectedSection.EncryptSection(clearXml, protectionProvider); } public virtual string GetConfigPathFromLocationSubPath(string configPath, string locationSubPath) { return configPath; } public virtual Type GetConfigType(string typeName, bool throwOnError) { Type type = Type.GetType(typeName); if (type == null) { type = Type.GetType(typeName + ",System"); } if (type == null && throwOnError) { throw new ConfigurationErrorsException("Type '" + typeName + "' not found."); } return type; } public virtual string GetConfigTypeName(Type t) { return t.AssemblyQualifiedName; } public virtual void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady) { throw new NotImplementedException(); } public abstract string GetStreamName(string configPath); public abstract void Init(IInternalConfigRoot root, params object[] hostInitParams); public abstract void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot root, params object[] hostInitConfigurationParams); [MonoNotSupported("mono does not support remote configuration")] public virtual string GetStreamNameForConfigSource(string streamName, string configSource) { throw new NotSupportedException("mono does not support remote configuration"); } public virtual object GetStreamVersion(string streamName) { throw new NotImplementedException(); } public virtual IDisposable Impersonate() { throw new NotImplementedException(); } public virtual bool IsAboveApplication(string configPath) { throw new NotImplementedException(); } public virtual bool IsConfigRecordRequired(string configPath) { throw new NotImplementedException(); } public virtual bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) { switch (allowDefinition) { case ConfigurationAllowDefinition.MachineOnly: return configPath == "machine"; case ConfigurationAllowDefinition.MachineToApplication: if (!(configPath == "machine")) { return configPath == "exe"; } return true; default: return true; } } public virtual bool IsFile(string streamName) { throw new NotImplementedException(); } public virtual bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord) { throw new NotImplementedException(); } public virtual bool IsInitDelayed(IInternalConfigRecord configRecord) { throw new NotImplementedException(); } public virtual bool IsLocationApplicable(string configPath) { throw new NotImplementedException(); } public virtual bool IsSecondaryRoot(string configPath) { throw new NotImplementedException(); } public virtual bool IsTrustedConfigPath(string configPath) { throw new NotImplementedException(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern string get_bundled_machine_config(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern string get_bundled_app_config(); public virtual Stream OpenStreamForRead(string streamName) { if (string.CompareOrdinal(streamName, RuntimeEnvironment.SystemConfigurationFile) == 0) { string bundled_machine_config = get_bundled_machine_config(); if (bundled_machine_config != null) { return new MemoryStream(Encoding.UTF8.GetBytes(bundled_machine_config)); } } if (string.CompareOrdinal(streamName, AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) == 0) { string bundled_app_config = get_bundled_app_config(); if (bundled_app_config != null) { return new MemoryStream(Encoding.UTF8.GetBytes(bundled_app_config)); } } if (!File.Exists(streamName)) { return null; } return new FileStream(streamName, FileMode.Open, FileAccess.Read); } public virtual Stream OpenStreamForRead(string streamName, bool assertPermissions) { throw new NotImplementedException(); } public virtual Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { string directoryName = Path.GetDirectoryName(streamName); if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } return new FileStream(streamName, FileMode.Create, FileAccess.Write); } public virtual Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext, bool assertPermissions) { throw new NotImplementedException(); } public virtual bool PrefetchAll(string configPath, string streamName) { throw new NotImplementedException(); } public virtual bool PrefetchSection(string sectionGroupName, string sectionName) { throw new NotImplementedException(); } public virtual void RequireCompleteInit(IInternalConfigRecord configRecord) { throw new NotImplementedException(); } public virtual object StartMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { throw new NotImplementedException(); } public virtual void StopMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { throw new NotImplementedException(); } public virtual void VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) { if (!IsDefinitionAllowed(configPath, allowDefinition, allowExeDefinition)) { throw new ConfigurationErrorsException("The section can't be defined in this file (the allowed definition context is '" + allowDefinition.ToString() + "').", errorInfo.Filename, errorInfo.LineNumber); } } public virtual void WriteCompleted(string streamName, bool success, object writeContext) { } public virtual void WriteCompleted(string streamName, bool success, object writeContext, bool assertPermissions) { } } internal class ExeConfigurationHost : InternalConfigurationHost { private ExeConfigurationFileMap map; private ConfigurationUserLevel level; public override void Init(IInternalConfigRoot root, params object[] hostInitParams) { map = (ExeConfigurationFileMap)hostInitParams[0]; level = (ConfigurationUserLevel)hostInitParams[1]; CheckFileMap(level, map); } private static void CheckFileMap(ConfigurationUserLevel level, ExeConfigurationFileMap map) { if (level != ConfigurationUserLevel.None) { switch (level) { default: return; case ConfigurationUserLevel.PerUserRoamingAndLocal: if (string.IsNullOrEmpty(map.LocalUserConfigFilename)) { throw new ArgumentException("The 'LocalUserConfigFilename' argument cannot be null."); } break; case ConfigurationUserLevel.PerUserRoaming: break; } if (string.IsNullOrEmpty(map.RoamingUserConfigFilename)) { throw new ArgumentException("The 'RoamingUserConfigFilename' argument cannot be null."); } } if (string.IsNullOrEmpty(map.ExeConfigFilename)) { throw new ArgumentException("The 'ExeConfigFilename' argument cannot be null."); } } public override string GetStreamName(string configPath) { return configPath switch { "exe" => map.ExeConfigFilename, "local" => map.LocalUserConfigFilename, "roaming" => map.RoamingUserConfigFilename, "machine" => map.MachineConfigFilename, _ => level switch { ConfigurationUserLevel.None => map.ExeConfigFilename, ConfigurationUserLevel.PerUserRoaming => map.RoamingUserConfigFilename, ConfigurationUserLevel.PerUserRoamingAndLocal => map.LocalUserConfigFilename, _ => map.MachineConfigFilename, }, }; } public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot root, params object[] hostInitConfigurationParams) { map = (ExeConfigurationFileMap)hostInitConfigurationParams[0]; if (hostInitConfigurationParams.Length > 1 && hostInitConfigurationParams[1] is ConfigurationUserLevel) { level = (ConfigurationUserLevel)hostInitConfigurationParams[1]; } CheckFileMap(level, map); if (locationSubPath == null) { switch (level) { case ConfigurationUserLevel.PerUserRoaming: if (map.RoamingUserConfigFilename == null) { throw new ArgumentException("RoamingUserConfigFilename must be set correctly"); } locationSubPath = "roaming"; break; case ConfigurationUserLevel.PerUserRoamingAndLocal: if (map.LocalUserConfigFilename == null) { throw new ArgumentException("LocalUserConfigFilename must be set correctly"); } locationSubPath = "local"; break; } } if (locationSubPath == "exe" || (locationSubPath == null && map.ExeConfigFilename != null)) { configPath = "exe"; locationSubPath = "machine"; locationConfigPath = map.ExeConfigFilename; return; } if (locationSubPath == "local" && map.LocalUserConfigFilename != null) { configPath = "local"; locationSubPath = "roaming"; locationConfigPath = map.LocalUserConfigFilename; return; } if (locationSubPath == "roaming" && map.RoamingUserConfigFilename != null) { configPath = "roaming"; locationSubPath = "exe"; locationConfigPath = map.RoamingUserConfigFilename; return; } if (locationSubPath == "machine" && map.MachineConfigFilename != null) { configPath = "machine"; locationSubPath = null; locationConfigPath = null; return; } throw new NotImplementedException(); } } internal class MachineConfigurationHost : InternalConfigurationHost { private ConfigurationFileMap map; public override void Init(IInternalConfigRoot root, params object[] hostInitParams) { map = (ConfigurationFileMap)hostInitParams[0]; } public override string GetStreamName(string configPath) { return map.MachineConfigFilename; } public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot root, params object[] hostInitConfigurationParams) { map = (ConfigurationFileMap)hostInitConfigurationParams[0]; locationSubPath = null; configPath = null; locationConfigPath = null; } public override bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) { return true; } } internal class InternalConfigurationRoot : IInternalConfigRoot { private IInternalConfigHost host; private bool isDesignTime; public bool IsDesignTime => isDesignTime; public event InternalConfigEventHandler ConfigChanged; public event InternalConfigEventHandler ConfigRemoved; [MonoTODO] public IInternalConfigRecord GetConfigRecord(string configPath) { throw new NotImplementedException(); } public object GetSection(string section, string configPath) { return GetConfigRecord(configPath).GetSection(section); } [MonoTODO] public string GetUniqueConfigPath(string configPath) { return configPath; } [MonoTODO] public IInternalConfigRecord GetUniqueConfigRecord(string configPath) { return GetConfigRecord(GetUniqueConfigPath(configPath)); } public void Init(IInternalConfigHost host, bool isDesignTime) { this.host = host; this.isDesignTime = isDesignTime; } [MonoTODO] public void RemoveConfig(string configPath) { host.DeleteStream(configPath); if (this.ConfigRemoved != null) { this.ConfigRemoved(this, new InternalConfigEventArgs(configPath)); } } } [ConfigurationCollection(typeof(KeyValueConfigurationElement), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)] public class KeyValueConfigurationCollection : ConfigurationElementCollection { private ConfigurationPropertyCollection properties; public string[] AllKeys { get { string[] array = new string[base.Count]; int num = 0; IEnumerator enumerator = GetEnumerator(); try { while (enumerator.MoveNext()) { KeyValueConfigurationElement keyValueConfigurationElement = (KeyValueConfigurationElement)enumerator.Current; array[num++] = keyValueConfigurationElement.Key; } return array; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } } public new KeyValueConfigurationElement this[string key] => (KeyValueConfigurationElement)BaseGet(key); protected internal override ConfigurationPropertyCollection Properties { get { if (properties == null) { properties = new ConfigurationPropertyCollection(); } return properties; } } protected override bool ThrowOnDuplicate => false; public void Add(KeyValueConfigurationElement keyValue) { keyValue.Init(); BaseAdd(keyValue); } public void Add(string key, string value) { Add(new KeyValueConfigurationElement(key, value)); } public void Clear() { BaseClear(); } public void Remove(string key) { BaseRemove(key); } protected override ConfigurationElement CreateNewElement() { return new KeyValueConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((KeyValueConfigurationElement)element).Key; } } public class KeyValueConfigurationElement : ConfigurationElement { private static ConfigurationProperty keyProp; private static ConfigurationProperty valueProp; private static ConfigurationPropertyCollection properties; [ConfigurationProperty("key", DefaultValue = "", Options = ConfigurationPropertyOptions.IsKey)] public string Key => (string)base[keyProp]; [ConfigurationProperty("value", DefaultValue = "")] public string Value { get { return (string)base[valueProp]; } set { base[valueProp] = value; } } protected internal override ConfigurationPropertyCollection Properties => properties; static KeyValueConfigurationElement() { keyProp = new ConfigurationProperty("key", typeof(string), "", ConfigurationPropertyOptions.IsKey); valueProp = new ConfigurationProperty("value", typeof(string), ""); properties = new ConfigurationPropertyCollection(); properties.Add(keyProp); properties.Add(valueProp); } internal KeyValueConfigurationElement() { } public KeyValueConfigurationElement(string key, string value) { base[keyProp] = key; base[valueProp] = value; } [MonoTODO] protected internal override void Init() { } } internal class KeyValueInternalCollection : NameValueCollection { public void SetReadOnly() { base.IsReadOnly = true; } public override void Add(string name, string val) { Remove(name); base.Add(name, val); } } public class LongValidator : ConfigurationValidatorBase { private bool rangeIsExclusive; private long minValue; private long maxValue; private long resolution; public LongValidator(long minValue, long maxValue, bool rangeIsExclusive, long resolution) { this.minValue = minValue; this.maxValue = maxValue; this.rangeIsExclusive = rangeIsExclusive; this.resolution = resolution; } public LongValidator(long minValue, long maxValue, bool rangeIsExclusive) : this(minValue, maxValue, rangeIsExclusive, 0L) { } public LongValidator(long minValue, long maxValue) : this(minValue, maxValue, rangeIsExclusive: false, 0L) { } public override bool CanValidate(Type type) { return type == typeof(long); } public override void Validate(object value) { long num = (long)value; if (!rangeIsExclusive) { if (num < minValue || num > maxValue) { throw new ArgumentException("The value must be in the range " + minValue + " - " + maxValue); } } else if (num >= minValue && num <= maxValue) { throw new ArgumentException("The value must not be in the range " + minValue + " - " + maxValue); } if (resolution != 0L && num % resolution != 0L) { throw new ArgumentException("The value must have a resolution of " + resolution); } } } [AttributeUsage(AttributeTargets.Property)] public sealed class LongValidatorAttribute : ConfigurationValidatorAttribute { private bool excludeRange; private long maxValue; private long minValue; private ConfigurationValidatorBase instance; public bool ExcludeRange { get { return excludeRange; } set { excludeRange = value; instance = null; } } public long MaxValue { get { return maxValue; } set { maxValue = value; instance = null; } } public long MinValue { get { return minValue; } set { minValue = value; instance = null; } } public override ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = new LongValidator(minValue, maxValue, excludeRange); } return instance; } } } [ConfigurationCollection(typeof(NameValueConfigurationElement), AddItemName = "add", RemoveItemName = "remove", ClearItemsName = "clear", CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)] public sealed class NameValueConfigurationCollection : ConfigurationElementCollection { private static ConfigurationPropertyCollection properties; public string[] AllKeys => (string[])BaseGetAllKeys(); public new NameValueConfigurationElement this[string name] { get { return (NameValueConfigurationElement)BaseGet(name); } set { throw new NotImplementedException(); } } protected internal override ConfigurationPropertyCollection Properties => properties; static NameValueConfigurationCollection() { properties = new ConfigurationPropertyCollection(); } public void Add(NameValueConfigurationElement nameValue) { BaseAdd(nameValue, throwIfExists: false); } public void Clear() { BaseClear(); } protected override ConfigurationElement CreateNewElement() { return new NameValueConfigurationElement("", ""); } protected override object GetElementKey(ConfigurationElement element) { return ((NameValueConfigurationElement)element).Name; } public void Remove(NameValueConfigurationElement nameValue) { throw new NotImplementedException(); } public void Remove(string name) { BaseRemove(name); } } public sealed class NameValueConfigurationElement : ConfigurationElement { private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propName; private static readonly ConfigurationProperty _propValue; [ConfigurationProperty("name", DefaultValue = "", Options = ConfigurationPropertyOptions.IsKey)] public string Name => (string)base[_propName]; [ConfigurationProperty("value", DefaultValue = "", Options = ConfigurationPropertyOptions.None)] public string Value { get { return (string)base[_propValue]; } set { base[_propValue] = value; } } protected internal override ConfigurationPropertyCollection Properties => _properties; static NameValueConfigurationElement() { _properties = new ConfigurationPropertyCollection(); _propName = new ConfigurationProperty("name", typeof(string), "", ConfigurationPropertyOptions.IsKey); _propValue = new ConfigurationProperty("value", typeof(string), ""); _properties.Add(_propName); _properties.Add(_propValue); } public NameValueConfigurationElement(string name, string value) { base[_propName] = name; base[_propValue] = value; } } public class PositiveTimeSpanValidator : ConfigurationValidatorBase { public override bool CanValidate(Type type) { return type == typeof(TimeSpan); } public override void Validate(object value) { if ((TimeSpan)value <= new TimeSpan(0L)) { throw new ArgumentException("The time span value must be positive"); } } } [AttributeUsage(AttributeTargets.Property)] public sealed class PositiveTimeSpanValidatorAttribute : ConfigurationValidatorAttribute { private ConfigurationValidatorBase instance; public override ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = new PositiveTimeSpanValidator(); } return instance; } } } public sealed class PropertyInformation { private bool isLocked; private bool isModified; private int lineNumber; private string source; private object val; private PropertyValueOrigin origin; private readonly ConfigurationElement owner; private readonly ConfigurationProperty property; public TypeConverter Converter => property.Converter; public object DefaultValue => property.DefaultValue; public string Description => property.Description; public bool IsKey => property.IsKey; [MonoTODO] public bool IsLocked { get { return isLocked; } internal set { isLocked = value; } } public bool IsModified { get { return isModified; } internal set { isModified = value; } } public bool IsRequired => property.IsRequired; public int LineNumber { get { return lineNumber; } internal set { lineNumber = value; } } public string Name => property.Name; public string Source { get { return source; } internal set { source = value; } } public Type Type => property.Type; public ConfigurationValidatorBase Validator => property.Validator; public object Value { get { if (origin == PropertyValueOrigin.Default) { if (!property.IsElement) { return DefaultValue; } ConfigurationElement configurationElement = (ConfigurationElement)Activator.CreateInstance(Type, nonPublic: true); configurationElement.InitFromProperty(this); if (owner != null && owner.IsReadOnly()) { configurationElement.SetReadOnly(); } val = configurationElement; origin = PropertyValueOrigin.Inherited; } return val; } set { val = value; isModified = true; origin = PropertyValueOrigin.SetHere; } } internal bool IsElement => property.IsElement; public PropertyValueOrigin ValueOrigin => origin; internal ConfigurationProperty Property => property; internal PropertyInformation(ConfigurationElement owner, ConfigurationProperty property) { if (owner == null) { throw new ArgumentNullException("owner"); } if (property == null) { throw new ArgumentNullException("property"); } this.owner = owner; this.property = property; } internal void Reset(PropertyInformation parentProperty) { if (parentProperty != null) { if (property.IsElement) { ((ConfigurationElement)Value).Reset((ConfigurationElement)parentProperty.Value); return; } val = parentProperty.Value; origin = PropertyValueOrigin.Inherited; } else { origin = PropertyValueOrigin.Default; } } internal string GetStringValue() { return property.ConvertToString(Value); } internal void SetStringValue(string value) { val = property.ConvertFromString(value); if (!object.Equals(val, DefaultValue)) { origin = PropertyValueOrigin.SetHere; } } internal PropertyInformation() { ThrowStub.ThrowNotSupportedException(); } } [Serializable] public sealed class PropertyInformationCollection : NameObjectCollectionBase { private class PropertyInformationEnumerator : IEnumerator { private PropertyInformationCollection collection; private int position; public object Current { get { if (position < collection.Count && position >= 0) { return collection.BaseGet(position); } throw new InvalidOperationException(); } } public PropertyInformationEnumerator(PropertyInformationCollection collection) { this.collection = collection; position = -1; } public bool MoveNext() { if (++position >= collection.Count) { return false; } return true; } public void Reset() { position = -1; } } public PropertyInformation this[string propertyName] => (PropertyInformation)BaseGet(propertyName); internal PropertyInformationCollection() : base(StringComparer.Ordinal) { } public void CopyTo(PropertyInformation[] array, int index) { ((ICollection)this).CopyTo((Array)array, index); } public override IEnumerator GetEnumerator() { return new PropertyInformationEnumerator(this); } internal void Add(PropertyInformation pi) { BaseAdd(pi.Name, pi); } [MonoTODO] [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } } public enum PropertyValueOrigin { Default, Inherited, SetHere } public static class ProtectedConfiguration { public const string DataProtectionProviderName = "DataProtectionConfigurationProvider"; public const string ProtectedDataSectionName = "configProtectedData"; public const string RsaProviderName = "RsaProtectedConfigurationProvider"; public static string DefaultProvider => Section.DefaultProvider; public static ProtectedConfigurationProviderCollection Providers => Section.GetAllProviders(); internal static ProtectedConfigurationSection Section => (ProtectedConfigurationSection)ConfigurationManager.GetSection("configProtectedData"); internal static ProtectedConfigurationProvider GetProvider(string name, bool throwOnError) { ProtectedConfigurationProvider protectedConfigurationProvider = Providers[name]; if (protectedConfigurationProvider == null && throwOnError) { throw new Exception($"The protection provider '{name}' was not found."); } return protectedConfigurationProvider; } } public abstract class ProtectedConfigurationProvider : ProviderBase { public abstract XmlNode Decrypt(XmlNode encryptedNode); public abstract XmlNode Encrypt(XmlNode node); } public class ProtectedConfigurationProviderCollection : ProviderCollection { [MonoTODO] public new ProtectedConfigurationProvider this[string name] => (ProtectedConfigurationProvider)base[name]; [MonoTODO] public override void Add(ProviderBase provider) { base.Add(provider); } } public sealed class ProtectedConfigurationSection : ConfigurationSection { private static ConfigurationProperty defaultProviderProp; private static ConfigurationProperty providersProp; private static ConfigurationPropertyCollection properties; private ProtectedConfigurationProviderCollection providers; [ConfigurationProperty("defaultProvider", DefaultValue = "RsaProtectedConfigurationProvider")] public string DefaultProvider { get { return (string)base[defaultProviderProp]; } set { base[defaultProviderProp] = value; } } [ConfigurationProperty("providers")] public ProviderSettingsCollection Providers => (ProviderSettingsCollection)base[providersProp]; protected internal override ConfigurationPropertyCollection Properties => properties; static ProtectedConfigurationSection() { defaultProviderProp = new ConfigurationProperty("defaultProvider", typeof(string), "RsaProtectedConfigurationProvider"); providersProp = new ConfigurationProperty("providers", typeof(ProviderSettingsCollection), null); properties = new ConfigurationPropertyCollection(); properties.Add(defaultProviderProp); properties.Add(providersProp); } internal string EncryptSection(string clearXml, ProtectedConfigurationProvider protectionProvider) { XmlDocument val = (XmlDocument)(object)new ConfigurationXmlDocument(); val.LoadXml(clearXml); return protectionProvider.Encrypt((XmlNode)(object)val.DocumentElement).OuterXml; } internal string DecryptSection(string encryptedXml, ProtectedConfigurationProvider protectionProvider) { XmlDocument val = (XmlDocument)(object)new ConfigurationXmlDocument(); ((XmlNode)val).InnerXml = encryptedXml; return protectionProvider.Decrypt((XmlNode)(object)val.DocumentElement).OuterXml; } internal ProtectedConfigurationProviderCollection GetAllProviders() { if (providers == null) { providers = new ProtectedConfigurationProviderCollection(); foreach (ProviderSettings provider in Providers) { providers.Add(InstantiateProvider(provider)); } } return providers; } private ProtectedConfigurationProvider InstantiateProvider(ProviderSettings ps) { ProtectedConfigurationProvider obj = (Activator.CreateInstance(Type.GetType(ps.Type, throwOnError: true)) as ProtectedConfigurationProvider) ?? throw new Exception("The type specified does not extend ProtectedConfigurationProvider class."); obj.Initialize(ps.Name, ps.Parameters); return obj; } } public class ProtectedProviderSettings : ConfigurationElement { private static ConfigurationProperty providersProp; private static ConfigurationPropertyCollection properties; protected internal override ConfigurationPropertyCollection Properties => properties; [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)] public ProviderSettingsCollection Providers => (ProviderSettingsCollection)base[providersProp]; static ProtectedProviderSettings() { providersProp = new ConfigurationProperty("", typeof(ProviderSettingsCollection), null, null, null, ConfigurationPropertyOptions.IsDefaultCollection); properties = new ConfigurationPropertyCollection(); properties.Add(providersProp); } } public sealed class ProviderSettings : ConfigurationElement { private ConfigNameValueCollection parameters; private static ConfigurationProperty nameProp; private static ConfigurationProperty typeProp; private static ConfigurationPropertyCollection properties; [ConfigurationProperty("name", Options = (ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey))] public string Name { get { return (string)base[nameProp]; } set { base[nameProp] = value; } } [ConfigurationProperty("type", Options = ConfigurationPropertyOptions.IsRequired)] public string Type { get { return (string)base[typeProp]; } set { base[typeProp] = value; } } protected internal override ConfigurationPropertyCollection Properties => properties; public NameValueCollection Parameters { get { if (parameters == null) { parameters = new ConfigNameValueCollection(); } return parameters; } } static ProviderSettings() { nameProp = new ConfigurationProperty("name", typeof(string), null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey); typeProp = new ConfigurationProperty("type", typeof(string), null, ConfigurationPropertyOptions.IsRequired); properties = new ConfigurationPropertyCollection(); properties.Add(nameProp); properties.Add(typeProp); } public ProviderSettings() { } public ProviderSettings(string name, string type) { Name = name; Type = type; } protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) { if (parameters == null) { parameters = new ConfigNameValueCollection(); } parameters[name] = value; parameters.ResetModified(); return true; } protected internal override bool IsModified() { if (parameters == null || !parameters.IsModified) { return base.IsModified(); } return true; } protected internal override void Reset(ConfigurationElement parentElement) { base.Reset(parentElement); if (parentElement is ProviderSettings { parameters: not null } providerSettings) { parameters = new ConfigNameValueCollection(providerSettings.parameters); } else { parameters = null; } } [MonoTODO] protected internal override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode) { base.Unmerge(sourceElement, parentElement, saveMode); } } [ConfigurationCollection(typeof(ProviderSettings), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)] public sealed class ProviderSettingsCollection : ConfigurationElementCollection { private static ConfigurationPropertyCollection props = new ConfigurationPropertyCollection(); public ProviderSettings this[int index] { get { return (ProviderSettings)BaseGet(index); } set { BaseAdd(index, value); } } public new ProviderSettings this[string key] => (ProviderSettings)BaseGet(key); protected internal override ConfigurationPropertyCollection Properties => props; public void Add(ProviderSettings provider) { BaseAdd(provider); } public void Clear() { BaseClear(); } protected override ConfigurationElement CreateNewElement() { return new ProviderSettings(); } protected override object GetElementKey(ConfigurationElement element) { return ((ProviderSettings)element).Name; } public void Remove(string name) { BaseRemove(name); } } public class RegexStringValidator : ConfigurationValidatorBase { private string regex; public RegexStringValidator(string regex) { this.regex = regex; } public override bool CanValidate(Type type) { return type == typeof(string); } public override void Validate(object value) { if (!Regex.IsMatch((string)value, regex)) { throw new ArgumentException("The string must match the regexp `{0}'", regex); } } } [AttributeUsage(AttributeTargets.Property)] public sealed class RegexStringValidatorAttribute : ConfigurationValidatorAttribute { private string regex; private ConfigurationValidatorBase instance; public string Regex => regex; public override ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = new RegexStringValidator(regex); } return instance; } } public RegexStringValidatorAttribute(string regex) { this.regex = regex; } } public sealed class RsaProtectedConfigurationProvider : ProtectedConfigurationProvider { private string cspProviderName; private string keyContainerName; private bool useMachineContainer; private bool useOAEP; private RSACryptoServiceProvider rsa; public string CspProviderName => cspProviderName; public string KeyContainerName => keyContainerName; public RSAParameters RsaPublicKey => GetProvider().ExportParameters(includePrivateParameters: false); public bool UseMachineContainer => useMachineContainer; public bool UseOAEP => useOAEP; public bool UseFIPS { get { ThrowStub.ThrowNotSupportedException(); return default(bool); } } private RSACryptoServiceProvider GetProvider() { if (rsa == null) { CspParameters cspParameters = new CspParameters(); cspParameters.ProviderName = cspProviderName; cspParameters.KeyContainerName = keyContainerName; if (useMachineContainer) { cspParameters.Flags |= CspProviderFlags.UseMachineKeyStore; } rsa = new RSACryptoServiceProvider(cspParameters); } return rsa; } [MonoTODO] public override XmlNode Decrypt(XmlNode encryptedNode) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) ConfigurationXmlDocument configurationXmlDocument = new ConfigurationXmlDocument(); ((XmlDocument)configurationXmlDocument).Load((TextReader)new StringReader(encryptedNode.OuterXml)); EncryptedXml val = new EncryptedXml((XmlDocument)(object)configurationXmlDocument); val.AddKeyNameMapping("Rsa Key", (object)GetProvider()); val.DecryptDocument(); return (XmlNode)(object)((XmlDocument)configurationXmlDocument).DocumentElement; } [MonoTODO] public override XmlNode Encrypt(XmlNode node) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) XmlDocument val = (XmlDocument)(object)new ConfigurationXmlDocument(); val.Load((TextReader)new StringReader(node.OuterXml)); EncryptedXml val2 = new EncryptedXml(val); val2.AddKeyNameMapping("Rsa Key", (object)GetProvider()); return (XmlNode)(object)((EncryptedType)val2.Encrypt(val.DocumentElement, "Rsa Key")).GetXml(); } [MonoTODO] public override void Initialize(string name, NameValueCollection configurationValues) { base.Initialize(name, configurationValues); keyContainerName = configurationValues["keyContainerName"]; cspProviderName = configurationValues["cspProviderName"]; string text = configurationValues["useMachineContainer"]; if (text != null && text.ToLower() == "true") { useMachineContainer = true; } text = configurationValues["useOAEP"]; if (text != null && text.ToLower() == "true") { useOAEP = true; } } [MonoTODO] public void AddKey(int keySize, bool exportable) { throw new NotImplementedException(); } [MonoTODO] public void DeleteKey() { throw new NotImplementedException(); } [MonoTODO] public void ExportKey(string xmlFileName, bool includePrivateParameters) { string value = GetProvider().ToXmlString(includePrivateParameters); StreamWriter streamWriter = new StreamWriter(new FileStream(xmlFileName, FileMode.OpenOrCreate, FileAccess.Write)); streamWriter.Write(value); streamWriter.Close(); } [MonoTODO] public void ImportKey(string xmlFileName, bool exportable) { throw new NotImplementedException(); } } internal class SectionGroupInfo : ConfigInfo { private bool modified; private ConfigInfoCollection sections; private ConfigInfoCollection groups; private static ConfigInfoCollection emptyList = new ConfigInfoCollection(); public ConfigInfoCollection Sections { get { if (sections == null) { return emptyList; } return sections; } } public ConfigInfoCollection Groups { get { if (groups == null) { return emptyList; } return groups; } } public SectionGroupInfo() { Type = typeof(ConfigurationSectionGroup); } public SectionGroupInfo(string groupName, string typeName) { Name = groupName; TypeName = typeName; } public void AddChild(ConfigInfo data) { modified = true; data.Parent = this; if (data is SectionInfo) { if (sections == null) { sections = new ConfigInfoCollection(); } sections[data.Name] = data; } else { if (groups == null) { groups = new ConfigInfoCollection(); } groups[data.Name] = data; } } public void Clear() { modified = true; if (sections != null) { sections.Clear(); } if (groups != null) { groups.Clear(); } } public bool HasChild(string name) { if (sections != null && sections[name] != null) { return true; } if (groups != null) { return groups[name] != null; } return false; } public void RemoveChild(string name) { modified = true; if (sections != null) { sections.Remove(name); } if (groups != null) { groups.Remove(name); } } public SectionInfo GetChildSection(string name) { if (sections != null) { return sections[name] as SectionInfo; } return null; } public SectionGroupInfo GetChildGroup(string name) { if (groups != null) { return groups[name] as SectionGroupInfo; } return null; } public override bool HasDataContent(Configuration config) { object[] array = new object[2] { Sections, Groups }; for (int i = 0; i < array.Length; i++) { ConfigInfoCollection configInfoCollection = (ConfigInfoCollection)array[i]; foreach (string item in configInfoCollection) { if (configInfoCollection[item].HasDataContent(config)) { return true; } } } return false; } public override bool HasConfigContent(Configuration cfg) { if (base.StreamName == cfg.FileName) { return true; } object[] array = new object[2] { Sections, Groups }; for (int i = 0; i < array.Length; i++) { ConfigInfoCollection configInfoCollection = (ConfigInfoCollection)array[i]; foreach (string item in configInfoCollection) { if (configInfoCollection[item].HasConfigContent(cfg)) { return true; } } } return false; } public override void ReadConfig(Configuration cfg, string streamName, XmlReader reader) { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Invalid comparison between Unknown and I4 //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Invalid comparison between Unknown and I4 base.StreamName = streamName; ConfigHost = cfg.ConfigHost; if (reader.LocalName != "configSections") { while (reader.MoveToNextAttribute()) { if (reader.Name == "name") { Name = reader.Value; } else if (reader.Name == "type") { TypeName = reader.Value; Type = null; } else { ThrowException("Unrecognized attribute", reader); } } if (Name == null) { ThrowException("sectionGroup must have a 'name' attribute", reader); } if (Name == "location") { ThrowException("location is a reserved section name", reader); } } if (TypeName == null) { TypeName = "System.Configuration.ConfigurationSectionGroup"; } if (reader.IsEmptyElement) { reader.Skip(); return; } reader.ReadStartElement(); reader.MoveToContent(); while ((int)reader.NodeType != 15) { if ((int)reader.NodeType != 1) { reader.Skip(); continue; } string localName = reader.LocalName; ConfigInfo configInfo = null; switch (localName) { case "remove": ReadRemoveSection(reader); continue; case "clear": if (reader.HasAttributes) { ThrowException("Unrecognized attribute.", reader); } Clear(); reader.Skip(); continue; case "section": configInfo = new SectionInfo(); break; case "sectionGroup": configInfo = new SectionGroupInfo(); break; default: ThrowException("Unrecognized element: " + reader.Name, reader); break; } configInfo.ReadConfig(cfg, streamName, reader); ConfigInfo configInfo2 = Groups[configInfo.Name]; if (configInfo2 == null) { configInfo2 = Sections[configInfo.Name]; } if (configInfo2 != null) { if (configInfo2.GetType() != configInfo.GetType()) { ThrowException("A section or section group named '" + configInfo.Name + "' already exists", reader); } configInfo2.Merge(configInfo); configInfo2.StreamName = streamName; } else { AddChild(configInfo); } } reader.ReadEndElement(); } public override void WriteConfig(Configuration cfg, XmlWriter writer, ConfigurationSaveMode mode) { if (Name != null) { writer.WriteStartElement("sectionGroup"); writer.WriteAttributeString("name", Name); if (TypeName != null && TypeName != "" && TypeName != "System.Configuration.ConfigurationSectionGroup") { writer.WriteAttributeString("type", TypeName); } } else { writer.WriteStartElement("configSections"); } object[] array = new object[2] { Sections, Groups }; for (int i = 0; i < array.Length; i++) { ConfigInfoCollection configInfoCollection = (ConfigInfoCollection)array[i]; foreach (string item in configInfoCollection) { ConfigInfo configInfo = configInfoCollection[item]; if (configInfo.HasConfigContent(cfg)) { configInfo.WriteConfig(cfg, writer, mode); } } } writer.WriteEndElement(); } private void ReadRemoveSection(XmlReader reader) { if (!reader.MoveToNextAttribute() || reader.Name != "name") { ThrowException("Unrecognized attribute.", reader); } string value = reader.Value; if (string.IsNullOrEmpty(value)) { ThrowException("Empty name to remove", reader); } reader.MoveToElement(); if (!HasChild(value)) { ThrowException("No factory for " + value, reader); } RemoveChild(value); reader.Skip(); } public void ReadRootData(XmlReader reader, Configuration config, bool overrideAllowed) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) reader.MoveToContent(); ReadContent(reader, config, overrideAllowed, root: true); } public override void ReadData(Configuration config, XmlReader reader, bool overrideAllowed) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) reader.MoveToContent(); if (!reader.IsEmptyElement) { reader.ReadStartElement(); ReadContent(reader, config, overrideAllowed, root: false); reader.MoveToContent(); reader.ReadEndElement(); } else { reader.Read(); } } private void ReadContent(XmlReader reader, Configuration config, bool overrideAllowed, bool root) { //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Invalid comparison between Unknown and I4 //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 while ((int)reader.NodeType != 15 && (int)reader.NodeType != 0) { if ((int)reader.NodeType != 1) { reader.Skip(); } else if (reader.LocalName == "dllmap") { reader.Skip(); } else if (reader.LocalName == "location") { if (!root) { ThrowException(" elements are only allowed in elements.", reader); } string attribute = reader.GetAttribute("allowOverride"); bool flag = attribute == null || attribute.Length == 0 || bool.Parse(attribute); string attribute2 = reader.GetAttribute("path"); if (attribute2 != null && attribute2.Length > 0) { string xmlContent = reader.ReadOuterXml(); string[] array = attribute2.Split(','); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (config.Locations.Find(text) != null) { ThrowException("Sections must only appear once per config file.", reader); } ConfigurationLocation loc = new ConfigurationLocation(text, xmlContent, config, flag); config.Locations.Add(loc); } } else { ReadData(config, reader, flag); } } else { ConfigInfo configInfo = GetConfigInfo(reader, this); if (configInfo != null) { configInfo.ReadData(config, reader, overrideAllowed); } else { ThrowException("Unrecognized configuration section <" + reader.LocalName + ">", reader); } } } } private ConfigInfo GetConfigInfo(XmlReader reader, SectionGroupInfo current) { ConfigInfo configInfo = null; if (current.sections != null) { configInfo = current.sections[reader.LocalName]; } if (configInfo != null) { return configInfo; } if (current.groups != null) { configInfo = current.groups[reader.LocalName]; } if (configInfo != null) { return configInfo; } if (current.groups == null) { return null; } foreach (string allKey in current.groups.AllKeys) { configInfo = GetConfigInfo(reader, (SectionGroupInfo)current.groups[allKey]); if (configInfo != null) { return configInfo; } } return null; } internal override void Merge(ConfigInfo newData) { if (!(newData is SectionGroupInfo sectionGroupInfo)) { return; } if (sectionGroupInfo.sections != null && sectionGroupInfo.sections.Count > 0) { foreach (string allKey in sectionGroupInfo.sections.AllKeys) { if (sections[allKey] == null) { sections.Add(allKey, sectionGroupInfo.sections[allKey]); } } } if (sectionGroupInfo.groups == null || sectionGroupInfo.sections == null || sectionGroupInfo.sections.Count <= 0) { return; } foreach (string allKey2 in sectionGroupInfo.groups.AllKeys) { if (groups[allKey2] == null) { groups.Add(allKey2, sectionGroupInfo.groups[allKey2]); } } } public void WriteRootData(XmlWriter writer, Configuration config, ConfigurationSaveMode mode) { WriteContent(writer, config, mode, writeElem: false); } public override void WriteData(Configuration config, XmlWriter writer, ConfigurationSaveMode mode) { writer.WriteStartElement(Name); WriteContent(writer, config, mode, writeElem: true); writer.WriteEndElement(); } public void WriteContent(XmlWriter writer, Configuration config, ConfigurationSaveMode mode, bool writeElem) { object[] array = new object[2] { Sections, Groups }; for (int i = 0; i < array.Length; i++) { ConfigInfoCollection configInfoCollection = (ConfigInfoCollection)array[i]; foreach (string item in configInfoCollection) { ConfigInfo configInfo = configInfoCollection[item]; if (configInfo.HasDataContent(config)) { configInfo.WriteData(config, writer, mode); } } } } internal override bool HasValues(Configuration config, ConfigurationSaveMode mode) { if (modified && mode == ConfigurationSaveMode.Modified) { return true; } object[] array = new object[2] { Sections, Groups }; for (int i = 0; i < array.Length; i++) { ConfigInfoCollection configInfoCollection = (ConfigInfoCollection)array[i]; foreach (string item in configInfoCollection) { if (configInfoCollection[item].HasValues(config, mode)) { return true; } } } return false; } internal override void ResetModified(Configuration config) { modified = false; object[] array = new object[2] { Sections, Groups }; for (int i = 0; i < array.Length; i++) { ConfigInfoCollection configInfoCollection = (ConfigInfoCollection)array[i]; foreach (string item in configInfoCollection) { configInfoCollection[item].ResetModified(config); } } } } internal class ConfigInfoCollection : NameObjectCollectionBase { public ICollection AllKeys => Keys; public ConfigInfo this[string name] { get { return (ConfigInfo)BaseGet(name); } set { BaseSet(name, value); } } public ConfigInfo this[int index] { get { return (ConfigInfo)BaseGet(index); } set { BaseSet(index, value); } } public ConfigInfoCollection() : base(StringComparer.Ordinal) { } public void Add(string name, ConfigInfo config) { BaseAdd(name, config); } public void Clear() { BaseClear(); } public string GetKey(int index) { return BaseGetKey(index); } public void Remove(string name) { BaseRemove(name); } public void RemoveAt(int index) { BaseRemoveAt(index); } } internal class SectionInfo : ConfigInfo { private bool allowLocation = true; private bool requirePermission = true; private bool restartOnExternalChanges; private ConfigurationAllowDefinition allowDefinition = ConfigurationAllowDefinition.Everywhere; private ConfigurationAllowExeDefinition allowExeDefinition = ConfigurationAllowExeDefinition.MachineToApplication; public SectionInfo() { } public SectionInfo(string sectionName, SectionInformation info) { Name = sectionName; TypeName = info.Type; allowLocation = info.AllowLocation; allowDefinition = info.AllowDefinition; allowExeDefinition = info.AllowExeDefinition; requirePermission = info.RequirePermission; restartOnExternalChanges = info.RestartOnExternalChanges; } public override object CreateInstance() { object obj = base.CreateInstance(); if (obj is ConfigurationSection configurationSection) { configurationSection.SectionInformation.AllowLocation = allowLocation; configurationSection.SectionInformation.AllowDefinition = allowDefinition; configurationSection.SectionInformation.AllowExeDefinition = allowExeDefinition; configurationSection.SectionInformation.RequirePermission = requirePermission; configurationSection.SectionInformation.RestartOnExternalChanges = restartOnExternalChanges; configurationSection.SectionInformation.SetName(Name); } return obj; } public override bool HasDataContent(Configuration config) { if (config.GetSectionInstance(this, createDefaultInstance: false) == null) { return config.GetSectionXml(this) != null; } return true; } public override bool HasConfigContent(Configuration cfg) { return base.StreamName == cfg.FileName; } public override void ReadConfig(Configuration cfg, string streamName, XmlReader reader) { base.StreamName = streamName; ConfigHost = cfg.ConfigHost; while (reader.MoveToNextAttribute()) { switch (reader.Name) { case "allowLocation": { string value2 = reader.Value; allowLocation = value2 == "true"; if (!allowLocation && value2 != "false") { ThrowException("Invalid attribute value", reader); } break; } case "allowDefinition": { string value5 = reader.Value; try { allowDefinition = (ConfigurationAllowDefinition)Enum.Parse(typeof(ConfigurationAllowDefinition), value5); } catch { ThrowException("Invalid attribute value", reader); } break; } case "allowExeDefinition": { string value4 = reader.Value; try { allowExeDefinition = (ConfigurationAllowExeDefinition)Enum.Parse(typeof(ConfigurationAllowExeDefinition), value4); } catch { ThrowException("Invalid attribute value", reader); } break; } case "type": TypeName = reader.Value; break; case "name": Name = reader.Value; if (Name == "location") { ThrowException("location is a reserved section name", reader); } break; case "requirePermission": { string value3 = reader.Value; bool flag2 = value3 == "true"; if (!flag2 && value3 != "false") { ThrowException("Invalid attribute value", reader); } requirePermission = flag2; break; } case "restartOnExternalChanges": { string value = reader.Value; bool flag = value == "true"; if (!flag && value != "false") { ThrowException("Invalid attribute value", reader); } restartOnExternalChanges = flag; break; } default: ThrowException($"Unrecognized attribute: {reader.Name}", reader); break; } } if (Name == null || TypeName == null) { ThrowException("Required attribute missing", reader); } reader.MoveToElement(); reader.Skip(); } public override void WriteConfig(Configuration cfg, XmlWriter writer, ConfigurationSaveMode mode) { writer.WriteStartElement("section"); writer.WriteAttributeString("name", Name); writer.WriteAttributeString("type", TypeName); if (!allowLocation) { writer.WriteAttributeString("allowLocation", "false"); } if (allowDefinition != ConfigurationAllowDefinition.Everywhere) { writer.WriteAttributeString("allowDefinition", allowDefinition.ToString()); } if (allowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication) { writer.WriteAttributeString("allowExeDefinition", allowExeDefinition.ToString()); } if (!requirePermission) { writer.WriteAttributeString("requirePermission", "false"); } writer.WriteEndElement(); } public override void ReadData(Configuration config, XmlReader reader, bool overrideAllowed) { if (!config.HasFile && !allowLocation) { throw new ConfigurationErrorsException("The configuration section <" + Name + "> cannot be defined inside a element.", reader); } if (!config.ConfigHost.IsDefinitionAllowed(config.ConfigPath, allowDefinition, allowExeDefinition)) { object obj = ((allowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication) ? ((object)allowExeDefinition) : ((object)allowDefinition)); throw new ConfigurationErrorsException("The section <" + Name + "> can't be defined in this configuration file (the allowed definition context is '" + obj?.ToString() + "').", reader); } if (config.GetSectionXml(this) != null) { ThrowException("The section <" + Name + "> is defined more than once in the same configuration file.", reader); } config.SetSectionXml(this, reader.ReadOuterXml()); } public override void WriteData(Configuration config, XmlWriter writer, ConfigurationSaveMode mode) { ConfigurationSection sectionInstance = config.GetSectionInstance(this, createDefaultInstance: false); string text; if (sectionInstance != null) { ConfigurationSection parentElement = ((config.Parent != null) ? config.Parent.GetSectionInstance(this, createDefaultInstance: false) : null); text = sectionInstance.SerializeSection(parentElement, Name, mode); string externalDataXml = sectionInstance.ExternalDataXml; string filePath = config.FilePath; if (!string.IsNullOrEmpty(filePath) && !string.IsNullOrEmpty(externalDataXml)) { using StreamWriter streamWriter = new StreamWriter(Path.Combine(Path.GetDirectoryName(filePath), sectionInstance.SectionInformation.ConfigSource)); streamWriter.Write(externalDataXml); } if (sectionInstance.SectionInformation.IsProtected) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("<{0} configProtectionProvider=\"{1}\">\n", Name, sectionInstance.SectionInformation.ProtectionProvider.Name); stringBuilder.Append(config.ConfigHost.EncryptSection(text, sectionInstance.SectionInformation.ProtectionProvider, ProtectedConfiguration.Section)); stringBuilder.AppendFormat("", Name); text = stringBuilder.ToString(); } } else { text = config.GetSectionXml(this); } if (!string.IsNullOrEmpty(text)) { writer.WriteRaw(text); } } internal override void Merge(ConfigInfo data) { } internal override bool HasValues(Configuration config, ConfigurationSaveMode mode) { ConfigurationSection sectionInstance = config.GetSectionInstance(this, createDefaultInstance: false); if (sectionInstance == null) { return false; } ConfigurationSection parent = ((config.Parent != null) ? config.Parent.GetSectionInstance(this, createDefaultInstance: false) : null); return sectionInstance.HasValues(parent, mode); } internal override void ResetModified(Configuration config) { config.GetSectionInstance(this, createDefaultInstance: false)?.ResetModified(); } } public sealed class SectionInformation { private ConfigurationSection parent; private ConfigurationAllowDefinition allow_definition = ConfigurationAllowDefinition.Everywhere; private ConfigurationAllowExeDefinition allow_exe_definition = ConfigurationAllowExeDefinition.MachineToApplication; private bool allow_location; private bool allow_override; private bool inherit_on_child_apps; private bool restart_on_external_changes; private bool require_permission; private string config_source = string.Empty; private bool force_update; private string name; private string type_name; private string raw_xml; private ProtectedConfigurationProvider protection_provider; internal string ConfigFilePath { get; set; } public ConfigurationAllowDefinition AllowDefinition { get { return allow_definition; } set { allow_definition = value; } } public ConfigurationAllowExeDefinition AllowExeDefinition { get { return allow_exe_definition; } set { allow_exe_definition = value; } } public bool AllowLocation { get { return allow_location; } set { allow_location = value; } } public bool AllowOverride { get { return allow_override; } set { allow_override = value; } } public string ConfigSource { get { return config_source; } set { if (value == null) { value = string.Empty; } config_source = value; } } public bool ForceSave { get { return force_update; } set { force_update = value; } } public bool InheritInChildApplications { get { return inherit_on_child_apps; } set { inherit_on_child_apps = value; } } [MonoTODO] public bool IsDeclarationRequired { get { throw new NotImplementedException(); } } [MonoTODO] public bool IsDeclared => false; [MonoTODO] public bool IsLocked => false; public bool IsProtected => protection_provider != null; public string Name => name; public ProtectedConfigurationProvider ProtectionProvider => protection_provider; [MonoTODO] public bool RequirePermission { get { return require_permission; } set { require_permission = value; } } [MonoTODO] public bool RestartOnExternalChanges { get { return restart_on_external_changes; } set { restart_on_external_changes = value; } } [MonoTODO] public string SectionName => name; public string Type { get { return type_name; } set { if (value == null || value.Length == 0) { throw new ArgumentException("Value cannot be null or empty."); } type_name = value; } } public ConfigurationBuilder ConfigurationBuilder { get { ThrowStub.ThrowNotSupportedException(); return null; } } public OverrideMode OverrideMode { get { ThrowStub.ThrowNotSupportedException(); return default(OverrideMode); } set { ThrowStub.ThrowNotSupportedException(); } } public OverrideMode OverrideModeDefault { get { ThrowStub.ThrowNotSupportedException(); return default(OverrideMode); } set { ThrowStub.ThrowNotSupportedException(); } } public OverrideMode OverrideModeEffective { get { ThrowStub.ThrowNotSupportedException(); return default(OverrideMode); } } [MonoTODO("default value for require_permission")] internal SectionInformation() { allow_definition = ConfigurationAllowDefinition.Everywhere; allow_location = true; allow_override = true; inherit_on_child_apps = true; restart_on_external_changes = true; } public ConfigurationSection GetParentSection() { return parent; } internal void SetParentSection(ConfigurationSection parent) { this.parent = parent; } public string GetRawXml() { return raw_xml; } public void ProtectSection(string protectionProvider) { protection_provider = ProtectedConfiguration.GetProvider(protectionProvider, throwOnError: true); } [MonoTODO] public void ForceDeclaration(bool force) { } public void ForceDeclaration() { ForceDeclaration(force: true); } [MonoTODO] public void RevertToParent() { throw new NotImplementedException(); } public void UnprotectSection() { protection_provider = null; } public void SetRawXml(string rawXml) { raw_xml = rawXml; } [MonoTODO] internal void SetName(string name) { this.name = name; } } public class StringValidator : ConfigurationValidatorBase { private char[] invalidCharacters; private int maxLength; private int minLength; public StringValidator(int minLength) { this.minLength = minLength; maxLength = int.MaxValue; } public StringValidator(int minLength, int maxLength) { this.minLength = minLength; this.maxLength = maxLength; } public StringValidator(int minLength, int maxLength, string invalidCharacters) { this.minLength = minLength; this.maxLength = maxLength; if (invalidCharacters != null) { this.invalidCharacters = invalidCharacters.ToCharArray(); } } public override bool CanValidate(Type type) { return type == typeof(string); } public override void Validate(object value) { if (value != null || minLength > 0) { string text = (string)value; if (text == null || text.Length < minLength) { throw new ArgumentException("The string must be at least " + minLength + " characters long."); } if (text.Length > maxLength) { throw new ArgumentException("The string must be no more than " + maxLength + " characters long."); } if (invalidCharacters != null && text.IndexOfAny(invalidCharacters) != -1) { throw new ArgumentException($"The string cannot contain any of the following characters: '{invalidCharacters}'."); } } } } [AttributeUsage(AttributeTargets.Property)] public sealed class StringValidatorAttribute : ConfigurationValidatorAttribute { private string invalidCharacters; private int maxLength = int.MaxValue; private int minLength; private ConfigurationValidatorBase instance; public string InvalidCharacters { get { return invalidCharacters; } set { invalidCharacters = value; instance = null; } } public int MaxLength { get { return maxLength; } set { maxLength = value; instance = null; } } public int MinLength { get { return minLength; } set { minLength = value; instance = null; } } public override ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = new StringValidator(minLength, maxLength, invalidCharacters); } return instance; } } } public sealed class SubclassTypeValidator : ConfigurationValidatorBase { private Type baseClass; public SubclassTypeValidator(Type baseClass) { this.baseClass = baseClass; } public override bool CanValidate(Type type) { return type == typeof(Type); } public override void Validate(object value) { Type c = (Type)value; if (!baseClass.IsAssignableFrom(c)) { throw new ArgumentException("The value must be a subclass"); } } } [AttributeUsage(AttributeTargets.Property)] public sealed class SubclassTypeValidatorAttribute : ConfigurationValidatorAttribute { private Type baseClass; private ConfigurationValidatorBase instance; public Type BaseClass => baseClass; public override ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = new SubclassTypeValidator(baseClass); } return instance; } } public SubclassTypeValidatorAttribute(Type baseClass) { this.baseClass = baseClass; } } public class TimeSpanMinutesConverter : ConfigurationConverterBase { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { return TimeSpan.FromMinutes(long.Parse((string)data)); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value.GetType() != typeof(TimeSpan)) { throw new ArgumentException(); } return ((long)((TimeSpan)value).TotalMinutes).ToString(); } } public sealed class TimeSpanMinutesOrInfiniteConverter : TimeSpanMinutesConverter { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { if ((string)data == "Infinite") { return TimeSpan.MaxValue; } return base.ConvertFrom(ctx, ci, data); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value.GetType() != typeof(TimeSpan)) { throw new ArgumentException(); } if ((TimeSpan)value == TimeSpan.MaxValue) { return "Infinite"; } return base.ConvertTo(ctx, ci, value, type); } } public class TimeSpanSecondsConverter : ConfigurationConverterBase { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { if (!(data is string)) { throw new ArgumentException("data"); } if (!long.TryParse((string)data, out var result)) { throw new ArgumentException("data"); } return TimeSpan.FromSeconds(result); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value.GetType() != typeof(TimeSpan)) { throw new ArgumentException(); } return ((long)((TimeSpan)value).TotalSeconds).ToString(); } } public sealed class TimeSpanSecondsOrInfiniteConverter : TimeSpanSecondsConverter { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { if ((string)data == "Infinite") { return TimeSpan.MaxValue; } return base.ConvertFrom(ctx, ci, data); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value.GetType() != typeof(TimeSpan)) { throw new ArgumentException(); } if ((TimeSpan)value == TimeSpan.MaxValue) { return "Infinite"; } return base.ConvertTo(ctx, ci, value, type); } } public class TimeSpanValidator : ConfigurationValidatorBase { private bool rangeIsExclusive; private TimeSpan minValue; private TimeSpan maxValue; private long resolutionInSeconds; public TimeSpanValidator(TimeSpan minValue, TimeSpan maxValue) : this(minValue, maxValue, rangeIsExclusive: false, 0L) { } public TimeSpanValidator(TimeSpan minValue, TimeSpan maxValue, bool rangeIsExclusive) : this(minValue, maxValue, rangeIsExclusive, 0L) { } public TimeSpanValidator(TimeSpan minValue, TimeSpan maxValue, bool rangeIsExclusive, long resolutionInSeconds) { this.minValue = minValue; this.maxValue = maxValue; this.rangeIsExclusive = rangeIsExclusive; this.resolutionInSeconds = resolutionInSeconds; } public override bool CanValidate(Type type) { return type == typeof(TimeSpan); } public override void Validate(object value) { TimeSpan timeSpan = (TimeSpan)value; if (!rangeIsExclusive) { if (timeSpan < minValue || timeSpan > maxValue) { throw new ArgumentException("The value must be in the range " + minValue.ToString() + " - " + maxValue); } } else if (timeSpan >= minValue && timeSpan <= maxValue) { throw new ArgumentException("The value must not be in the range " + minValue.ToString() + " - " + maxValue); } if (resolutionInSeconds != 0L && timeSpan.Ticks % (10000000 * resolutionInSeconds) != 0L) { throw new ArgumentException("The value must have a resolution of " + TimeSpan.FromTicks(10000000 * resolutionInSeconds)); } } } [AttributeUsage(AttributeTargets.Property)] public sealed class TimeSpanValidatorAttribute : ConfigurationValidatorAttribute { private bool excludeRange; private string maxValueString = "10675199.02:48:05.4775807"; private string minValueString = "-10675199.02:48:05.4775808"; public const string TimeSpanMaxValue = "10675199.02:48:05.4775807"; public const string TimeSpanMinValue = "-10675199.02:48:05.4775808"; private ConfigurationValidatorBase instance; public string MaxValueString { get { return maxValueString; } set { maxValueString = value; instance = null; } } public string MinValueString { get { return minValueString; } set { minValueString = value; instance = null; } } public TimeSpan MaxValue => TimeSpan.Parse(maxValueString); public TimeSpan MinValue => TimeSpan.Parse(minValueString); public bool ExcludeRange { get { return excludeRange; } set { excludeRange = value; instance = null; } } public override ConfigurationValidatorBase ValidatorInstance { get { if (instance == null) { instance = new TimeSpanValidator(MinValue, MaxValue, excludeRange); } return instance; } } } public sealed class TypeNameConverter : ConfigurationConverterBase { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { return Type.GetType((string)data); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value == null) { return null; } if (!(value is Type)) { throw new ArgumentException("value"); } return ((Type)value).AssemblyQualifiedName; } } public delegate void ValidatorCallback(object value); public sealed class WhiteSpaceTrimStringConverter : ConfigurationConverterBase { public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) { return ((string)data).Trim(); } public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) { if (value == null) { return ""; } if (!(value is string)) { throw new ArgumentException("value"); } return ((string)value).Trim(); } } } namespace System.Configuration.Provider { public abstract class ProviderBase { private bool alreadyInitialized; private string _description; private string _name; public virtual string Name => _name; public virtual string Description => _description; public virtual void Initialize(string name, NameValueCollection config) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException("Provider name cannot be null or empty.", "name"); } if (alreadyInitialized) { throw new InvalidOperationException("This provider instance has already been initialized."); } alreadyInitialized = true; _name = name; if (config != null) { _description = config["description"]; config.Remove("description"); } if (string.IsNullOrEmpty(_description)) { _description = _name; } } } public class ProviderCollection : ICollection, IEnumerable { private Hashtable lookup; private bool readOnly; private ArrayList values; public int Count => values.Count; public bool IsSynchronized => false; public object SyncRoot => this; public ProviderBase this[string name] { get { object obj = lookup[name]; if (obj == null) { return null; } return values[(int)obj] as ProviderBase; } } public ProviderCollection() { lookup = new Hashtable(10, StringComparer.InvariantCultureIgnoreCase); values = new ArrayList(); } public virtual void Add(ProviderBase provider) { if (readOnly) { throw new NotSupportedException(); } if (provider == null || provider.Name == null) { throw new ArgumentNullException(); } int num = values.Add(provider); try { lookup.Add(provider.Name, num); } catch { values.RemoveAt(num); throw; } } public void Clear() { if (readOnly) { throw new NotSupportedException(); } values.Clear(); lookup.Clear(); } public void CopyTo(ProviderBase[] array, int index) { values.CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { values.CopyTo(array, index); } public IEnumerator GetEnumerator() { return values.GetEnumerator(); } public void Remove(string name) { if (readOnly) { throw new NotSupportedException(); } object obj = lookup[name]; if (obj == null || !(obj is int num)) { throw new ArgumentException(); } if (num >= values.Count) { throw new ArgumentException(); } values.RemoveAt(num); lookup.Remove(name); ArrayList arrayList = new ArrayList(); foreach (DictionaryEntry item in lookup) { if ((int)item.Value > num) { arrayList.Add(item.Key); } } foreach (string item2 in arrayList) { lookup[item2] = (int)lookup[item2] - 1; } } public void SetReadOnly() { readOnly = true; } } [Serializable] public class ProviderException : Exception { public ProviderException() { } protected ProviderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public ProviderException(string message) : base(message) { } public ProviderException(string message, Exception innerException) : base(message, innerException) { } } } namespace System.Configuration.Internal { public class DelegatingConfigHost : IInternalConfigHost, IInternalConfigurationBuilderHost { private IInternalConfigHost host; protected IInternalConfigHost Host { get { return host; } set { host = value; } } public virtual bool IsRemote => host.IsRemote; public virtual bool SupportsChangeNotifications => host.SupportsChangeNotifications; public virtual bool SupportsLocation => host.SupportsLocation; public virtual bool SupportsPath => host.SupportsPath; public virtual bool SupportsRefresh => host.SupportsRefresh; protected IInternalConfigurationBuilderHost ConfigBuilderHost { get { ThrowStub.ThrowNotSupportedException(); return null; } } protected DelegatingConfigHost() { } public virtual object CreateConfigurationContext(string configPath, string locationSubPath) { return host.CreateConfigurationContext(configPath, locationSubPath); } public virtual object CreateDeprecatedConfigContext(string configPath) { return host.CreateDeprecatedConfigContext(configPath); } public virtual string DecryptSection(string encryptedXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfigSection) { return host.DecryptSection(encryptedXml, protectionProvider, protectedConfigSection); } public virtual void DeleteStream(string streamName) { host.DeleteStream(streamName); } public virtual string EncryptSection(string clearTextXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfigSection) { return host.EncryptSection(clearTextXml, protectionProvider, protectedConfigSection); } public virtual string GetConfigPathFromLocationSubPath(string configPath, string locationSubPath) { return host.GetConfigPathFromLocationSubPath(configPath, locationSubPath); } public virtual Type GetConfigType(string typeName, bool throwOnError) { return host.GetConfigType(typeName, throwOnError); } public virtual string GetConfigTypeName(Type t) { return host.GetConfigTypeName(t); } public virtual void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady) { host.GetRestrictedPermissions(configRecord, out permissionSet, out isHostReady); } public virtual string GetStreamName(string configPath) { return host.GetStreamName(configPath); } public virtual string GetStreamNameForConfigSource(string streamName, string configSource) { return host.GetStreamNameForConfigSource(streamName, configSource); } public virtual object GetStreamVersion(string streamName) { return host.GetStreamVersion(streamName); } public virtual IDisposable Impersonate() { return host.Impersonate(); } public virtual void Init(IInternalConfigRoot configRoot, params object[] hostInitParams) { host.Init(configRoot, hostInitParams); } public virtual void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) { host.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath, configRoot, hostInitConfigurationParams); } public virtual bool IsAboveApplication(string configPath) { return host.IsAboveApplication(configPath); } public virtual bool IsConfigRecordRequired(string configPath) { return host.IsConfigRecordRequired(configPath); } public virtual bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) { return host.IsDefinitionAllowed(configPath, allowDefinition, allowExeDefinition); } public virtual bool IsInitDelayed(IInternalConfigRecord configRecord) { return host.IsInitDelayed(configRecord); } public virtual bool IsFile(string streamName) { return host.IsFile(streamName); } public virtual bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord) { return host.IsFullTrustSectionWithoutAptcaAllowed(configRecord); } public virtual bool IsLocationApplicable(string configPath) { return host.IsLocationApplicable(configPath); } public virtual bool IsSecondaryRoot(string configPath) { return host.IsSecondaryRoot(configPath); } public virtual bool IsTrustedConfigPath(string configPath) { return host.IsTrustedConfigPath(configPath); } public virtual Stream OpenStreamForRead(string streamName) { return host.OpenStreamForRead(streamName); } public virtual Stream OpenStreamForRead(string streamName, bool assertPermissions) { return host.OpenStreamForRead(streamName, assertPermissions); } public virtual Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { return host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext); } public virtual Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext, bool assertPermissions) { return host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext, assertPermissions); } public virtual bool PrefetchAll(string configPath, string streamName) { return host.PrefetchAll(configPath, streamName); } public virtual bool PrefetchSection(string sectionGroupName, string sectionName) { return host.PrefetchSection(sectionGroupName, sectionName); } public virtual void RequireCompleteInit(IInternalConfigRecord configRecord) { host.RequireCompleteInit(configRecord); } public virtual object StartMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { return host.StartMonitoringStreamForChanges(streamName, callback); } public virtual void StopMonitoringStreamForChanges(string streamName, StreamChangeCallback callback) { host.StopMonitoringStreamForChanges(streamName, callback); } public virtual void VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) { host.VerifyDefinitionAllowed(configPath, allowDefinition, allowExeDefinition, errorInfo); } public virtual void WriteCompleted(string streamName, bool success, object writeContext) { host.WriteCompleted(streamName, success, writeContext); } public virtual void WriteCompleted(string streamName, bool success, object writeContext, bool assertPermissions) { host.WriteCompleted(streamName, success, writeContext, assertPermissions); } public virtual ConfigurationSection ProcessConfigurationSection(ConfigurationSection configSection, ConfigurationBuilder builder) { ThrowStub.ThrowNotSupportedException(); return null; } public virtual XmlNode ProcessRawXml(XmlNode rawXml, ConfigurationBuilder builder) { ThrowStub.ThrowNotSupportedException(); return null; } } public interface IConfigErrorInfo { string Filename { get; } int LineNumber { get; } } public interface IConfigSystem { IInternalConfigHost Host { get; } IInternalConfigRoot Root { get; } void Init(Type typeConfigHost, params object[] hostInitParams); } [ComVisible(false)] public interface IConfigurationManagerHelper { void EnsureNetConfigLoaded(); } [ComVisible(false)] public interface IConfigurationManagerInternal { string ApplicationConfigUri { get; } string ExeLocalConfigDirectory { get; } string ExeLocalConfigPath { get; } string ExeProductName { get; } string ExeProductVersion { get; } string ExeRoamingConfigDirectory { get; } string ExeRoamingConfigPath { get; } string MachineConfigPath { get; } bool SetConfigurationSystemInProgress { get; } bool SupportsUserConfig { get; } string UserConfigFilename { get; } } [ComVisible(false)] public interface IInternalConfigClientHost { string GetExeConfigPath(); string GetLocalUserConfigPath(); string GetRoamingUserConfigPath(); bool IsExeConfig(string configPath); bool IsLocalUserConfig(string configPath); bool IsRoamingUserConfig(string configPath); } [ComVisible(false)] public interface IInternalConfigConfigurationFactory { Configuration Create(Type typeConfigHost, params object[] hostInitConfigurationParams); string NormalizeLocationSubPath(string subPath, IConfigErrorInfo errorInfo); } [ComVisible(false)] public interface IInternalConfigHost { bool IsRemote { get; } bool SupportsChangeNotifications { get; } bool SupportsLocation { get; } bool SupportsPath { get; } bool SupportsRefresh { get; } object CreateConfigurationContext(string configPath, string locationSubPath); object CreateDeprecatedConfigContext(string configPath); string DecryptSection(string encryptedXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfigSection); void DeleteStream(string streamName); string EncryptSection(string clearTextXml, ProtectedConfigurationProvider protectionProvider, ProtectedConfigurationSection protectedConfigSection); string GetConfigPathFromLocationSubPath(string configPath, string locationSubPath); Type GetConfigType(string typeName, bool throwOnError); string GetConfigTypeName(Type t); void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady); string GetStreamName(string configPath); string GetStreamNameForConfigSource(string streamName, string configSource); object GetStreamVersion(string streamName); IDisposable Impersonate(); void Init(IInternalConfigRoot configRoot, params object[] hostInitParams); void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams); bool IsAboveApplication(string configPath); bool IsConfigRecordRequired(string configPath); bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition); bool IsFile(string streamName); bool IsFullTrustSectionWithoutAptcaAllowed(IInternalConfigRecord configRecord); bool IsInitDelayed(IInternalConfigRecord configRecord); bool IsLocationApplicable(string configPath); bool IsSecondaryRoot(string configPath); bool IsTrustedConfigPath(string configPath); Stream OpenStreamForRead(string streamName); Stream OpenStreamForRead(string streamName, bool assertPermissions); Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext); Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext, bool assertPermissions); bool PrefetchAll(string configPath, string streamName); bool PrefetchSection(string sectionGroupName, string sectionName); void RequireCompleteInit(IInternalConfigRecord configRecord); object StartMonitoringStreamForChanges(string streamName, StreamChangeCallback callback); void StopMonitoringStreamForChanges(string streamName, StreamChangeCallback callback); void VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo); void WriteCompleted(string streamName, bool success, object writeContext); void WriteCompleted(string streamName, bool success, object writeContext, bool assertPermissions); } [ComVisible(false)] public interface IInternalConfigRecord { string ConfigPath { get; } bool HasInitErrors { get; } string StreamName { get; } object GetLkgSection(string configKey); object GetSection(string configKey); void RefreshSection(string configKey); void Remove(); void ThrowIfInitErrors(); } [ComVisible(false)] public interface IInternalConfigRoot { bool IsDesignTime { get; } event InternalConfigEventHandler ConfigChanged; event InternalConfigEventHandler ConfigRemoved; IInternalConfigRecord GetConfigRecord(string configPath); object GetSection(string section, string configPath); string GetUniqueConfigPath(string configPath); IInternalConfigRecord GetUniqueConfigRecord(string configPath); void Init(IInternalConfigHost host, bool isDesignTime); void RemoveConfig(string configPath); } [ComVisible(false)] public interface IInternalConfigSettingsFactory { void CompleteInit(); void SetConfigurationSystem(IInternalConfigSystem internalConfigSystem, bool initComplete); } [ComVisible(false)] public interface IInternalConfigSystem { bool SupportsUserConfig { get; } object GetSection(string configKey); void RefreshConfig(string sectionName); } public sealed class InternalConfigEventArgs : EventArgs { private string configPath; public string ConfigPath { get { return configPath; } set { configPath = value; } } public InternalConfigEventArgs(string configPath) { this.configPath = configPath; } } public delegate void InternalConfigEventHandler(object sender, InternalConfigEventArgs e); public delegate void StreamChangeCallback(string streamName); } namespace System.Configuration { public abstract class ConfigurationBuilder : ProviderBase { protected ConfigurationBuilder() { ThrowStub.ThrowNotSupportedException(); } public virtual ConfigurationSection ProcessConfigurationSection(ConfigurationSection configSection) { ThrowStub.ThrowNotSupportedException(); return null; } public virtual XmlNode ProcessRawXml(XmlNode rawXml) { ThrowStub.ThrowNotSupportedException(); return null; } } public enum OverrideMode { Allow = 1, Deny = 2, Inherit = 0 } } namespace System.Configuration.Internal { [ComVisible(false)] public interface IInternalConfigurationBuilderHost { ConfigurationSection ProcessConfigurationSection(ConfigurationSection configSection, ConfigurationBuilder builder); XmlNode ProcessRawXml(XmlNode rawXml, ConfigurationBuilder builder); } } namespace System.Configuration { [DefaultMember("Item")] public class ConfigurationBuilderCollection : ProviderCollection { public ConfigurationBuilderCollection() { ThrowStub.ThrowNotSupportedException(); } } public class ConfigurationBuilderSettings : ConfigurationElement { public ProviderSettingsCollection Builders { get { ThrowStub.ThrowNotSupportedException(); return null; } } public ConfigurationBuilderSettings() { ThrowStub.ThrowNotSupportedException(); } } public sealed class ConfigurationBuildersSection : ConfigurationSection { public ProviderSettingsCollection Builders { get { ThrowStub.ThrowNotSupportedException(); return null; } } public ConfigurationBuildersSection() { ThrowStub.ThrowNotSupportedException(); } public ConfigurationBuilder GetBuilderFromName(string builderName) { ThrowStub.ThrowNotSupportedException(); return null; } } } namespace Unity { internal sealed class ThrowStub : ObjectDisposedException { public static void ThrowNotSupportedException() { throw new PlatformNotSupportedException(); } } }