Inheritance: ConfigurationElement
コード例 #1
0
        private static IConfigurationSection ReadSection(string sectionName, System.Configuration.ConfigurationSection section)
        {
            if (section == null)
            {
                return(null);
            }

            var handlerType = Type.GetType(section.SectionInformation.Type, false);

            if (handlerType == null)
            {
                throw new ConfigurationErrorsException(SR.GetString(SRKind.UnableReadConfiguration, sectionName),
                                                       new TypeLoadException(section.SectionInformation.Type, null));
            }

            var handler = handlerType.New <IConfigurationSectionHandler>();
            var doc     = new XmlDocument();
            var xml     = section.SectionInformation.GetRawXml();

            try
            {
                doc.LoadXml(xml);
                return(handler.Create(null, null, doc.ChildNodes[0]) as IConfigurationSection);
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(SR.GetString(SRKind.UnableReadConfiguration, sectionName), ex);
            }
        }
コード例 #2
0
        private static void SaveSection(System.Configuration.Configuration config, ConfigurationSection section)
        {
            // Save the section.
            section.SectionInformation.ForceSave = true;

            config.Save(ConfigurationSaveMode.Full);
        }
コード例 #3
0
		/// <summary>
		/// 得到Section的相关文件
		/// </summary>
		/// <param name="config"></param>
		/// <param name="section"></param>
		/// <returns></returns>
		public static string GetSectionRelativeFile(this System.Configuration.Configuration config, ConfigurationSection section)
		{
			string result = string.Empty;

			if (config != null && section != null)
			{
				string configSource = section.SectionInformation.ConfigSource;

				if (configSource.IsNullOrEmpty())
				{
					ConfigurationSection sectionInConfig = GetSectionRecursively(config, section.SectionInformation.SectionName);

					if (sectionInConfig != null)
						configSource = sectionInConfig.SectionInformation.ConfigSource;
				}

				if (configSource.IsNotEmpty() && config.FilePath.IsNotEmpty())
				{
					string configDir = Path.GetDirectoryName(config.FilePath);

					result = Path.Combine(configDir, configSource);
				}
			}

			return result;
		}
コード例 #4
0
        /// <summary>
        /// Adds a <see cref="ConfigurationSection"/> to the configuration source location specified by 
        /// <paramref name="saveParameter"/> and saves the configuration source.
        /// </summary>
        /// <remarks>
        /// If a configuration section with the specified name already exists in the location specified by 
        /// <paramref name="saveParameter"/> it will be replaced.
        /// </remarks>
        /// <param name="saveParameter">The <see cref="IConfigurationParameter"/> that represents the location where 
        /// to save the updated configuration. Must be an instance of <see cref="FileConfigurationParameter"/>.</param>
        /// <param name="sectionName">The name by which the <paramref name="configurationSection"/> should be added.</param>
        /// <param name="configurationSection">The configuration section to add.</param>
        public void Add(IConfigurationParameter saveParameter, string sectionName, ConfigurationSection configurationSection)
        {
            FileConfigurationParameter parameter = saveParameter as FileConfigurationParameter;
            if (null == parameter) throw new ArgumentException(string.Format(Resources.Culture, Resources.ExceptionUnexpectedType, typeof(FileConfigurationParameter).Name), "saveParameter");

            Save(parameter.FileName, sectionName, configurationSection);
        }
コード例 #5
0
        ///<summary>
        /// Clones a <see cref="ConfigurationSection"/>
        ///</summary>
        ///<param name="section">The <see cref="ConfigurationSection"/> to clone.</param>
        ///<returns>A new, cloned <see cref="ConfigurationSection"/>.</returns>
        public ConfigurationSection Clone(ConfigurationSection section)
        {
            if (section == null) throw new ArgumentNullException("section");

            var clonedSection = (ConfigurationSection)Activator.CreateInstance(section.GetType());
            return (ConfigurationSection)CloneElement(section, clonedSection);
        }
        /// <summary>
        /// Checks whether the result of a call to <see cref="IConfigurationSource.GetSection(string)"/> should be deferred to a subordinate source.<br/>
        /// If the call should be deferred, returns the <see cref="ConfigurationSection"/> intance from the approriate source.<br/>
        /// If the call should not be deferred returns <paramref name="configurationSection"/>.
        /// </summary>
        /// <param name="sectionName">The name of the section that was retrieved from configuration.</param>
        /// <param name="configurationSection">The section that was retrieved from configuration.</param>
        /// <returns>The resulting <see cref="ConfigurationSection"/> instance.</returns>
        /// <seealso cref="IConfigurationSource.GetSection(string)"/>
        /// <exception cref="ConfigurationSourceErrorsException">Thrown if a section does not exist in a registered source.</exception>
        protected override ConfigurationSection DoCheckGetSection(string sectionName, ConfigurationSection configurationSection)
        {
            string sourceNameForSection;
            if (!sectionRedirectTable.TryGetValue(sectionName, out sourceNameForSection))
            {
                return configurationSection;
            }

            //if no source is specified we can return.
            if (string.IsNullOrEmpty(sourceNameForSection))
            {
                return configurationSection;
            }

            IConfigurationSource subordinateSource = GetSubordinateSource(sourceNameForSection);

            EnsurePropagatingSectionChangeEvents(sourceNameForSection, sectionName);

            var section = subordinateSource.GetSection(sectionName);

            if (section == null)
                throw new ConfigurationSourceErrorsException(
                    string.Format(CultureInfo.CurrentCulture,
                    Resources.ExceptionRedirectedConfigurationSectionNotFound,
                    sectionName,
                    sourceNameForSection));

            return section;
        }
        public override bool OverrideWithGroupPolicies(ConfigurationSection configurationObject,
            bool readGroupPolicies, IRegistryKey machineKey, IRegistryKey userKey)
        {
            called = true;
            this.configurationObject = configurationObject;
            this.readGroupPolicies = readGroupPolicies;
            this.machineKey = machineKey;
            this.userKey = userKey;

            IRegistryKey policyKey = GetPolicyKey(machineKey, userKey);
            if (policyKey != null)
            {
                if (!policyKey.GetBoolValue(PolicyValueName).Value)
                {
                    return false;
                }

                TestsConfigurationSection section = configurationObject as TestsConfigurationSection;
                if (section != null)
                {
                    try
                    {
                        section.Value = policyKey.GetStringValue(ValuePropertyName);
                    }
                    catch (RegistryAccessException)
                    { }
                }
            }

            return true;
        }
コード例 #8
0
 public static void Save(ConfigurationSection configSection)
 {
     System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     configuration.Sections.Remove(configSection.SectionInformation.Name);
     configuration.Sections.Add(configSection.SectionInformation.Name, configSection);
     configuration.Save();
 }
コード例 #9
0
 public void Add(string sectionName, ConfigurationSection configurationSection)
 {
     if (CompositeConfigurationSource.CheckAddSection(sectionName, configurationSection)) return;
     
     contents.Add(sectionName, configurationSection);
     
 }
コード例 #10
0
		/// <summary>
		/// Opens the security settings configuration section, builds the design time nodes and adds them to the application node.
		/// </summary>
		/// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
		/// <param name="rootNode">The root node of the application.</param>
		/// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
		protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, ConfigurationSection section)
		{
			if (null != section)
            {
				rootNode.AddNode(new SecuritySettingsNodeBuilder(serviceProvider, (SecuritySettings)section).Build());
			}
		}
コード例 #11
0
        // Add a new section to the collection. This will result in a new declaration and definition.
        // It is an error if the section already exists.
        public void Add(string name, ConfigurationSection section)
        {
            VerifyIsAttachedToConfigRecord();

            _configRecord.AddConfigurationSection(_configSectionGroup.SectionGroupName, name, section);
            BaseAdd(name, name);
        }
コード例 #12
0
        /// <summary>
        /// Checks whether a call to <see cref="IConfigurationSource.GetSection(string)"/> should be extended.<br/>
        /// If the call should be extended performs the extended behavior and returns the modified <see cref="ConfigurationSection"/> intance.<br/>
        /// If the call should not be extended returns <paramref name="configurationSection"/>.
        /// </summary>
        /// <param name="sectionName">The name of the section that was retrieved from configuration.</param>
        /// <param name="configurationSection">The section that was retrieved from configuration.</param>
        /// <returns>The resulting <see cref="ConfigurationSection"/> instance.</returns>
        /// <seealso cref="IConfigurationSource.GetSection(string)"/>
        public ConfigurationSection CheckGetSection(string sectionName, ConfigurationSection configurationSection)
        {
            //design time managers occasionally call with sectionName == "".
            //this should be fixed in designtime managers
            if (string.IsNullOrEmpty(sectionName)) //   throw new ArgumentException(Resources.ExceptionStringNullOrEmpty, "sectionName");
            {
                return configurationSection;
            }

            //if we are already loading we should return.
            if (RecursionLock.InsideHandlerOperation)
            {
                return configurationSection;
            }

            //this is a section we depend on internally
            if (sectionName == ConfigurationSourceSection.SectionName)
            {
                return configurationSection;
            }

            lock (LockObject)
            {
                using (new RecursionLock())
                {
                    EnsureInitialized();

                    return DoCheckGetSection(sectionName, configurationSection);
                }
            }
        }
        /// <inheritdoc />
        public void Apply(ConfigurationSection section)
        {
            Ensure.ArgumentNotNull(section, "section");
            Ensure.ArgumentTypeAssignableFrom(typeof(CustomConfigurationSection), section.GetType(), "section");

            this.section = (CustomConfigurationSection)section;
        }
コード例 #14
0
        /// <summary>
        /// Set Property Filters constructor via ConfigurationSection from configuration file
        /// </summary>
        /// <param name="section">ConfigurationSection from configuration file</param>
        public PropertyFilter(ConfigurationSection section) : this()
        {
            //initialize fields
            if (section != null)
            {
                foreach (KeyValueConfigurationElement keyVal in ((AppSettingsSection)section).Settings)
                {
                    if (!string.IsNullOrEmpty(keyVal.Value))
                    {
                        switch (keyVal.Key.ToUpper())
                        {
                            case "EQUALTO":
                                EqualTo.AddRange(keyVal.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(s => s.ToUpper()));
                                break;
                            case "STARTWITH":
                                StartWith.AddRange(keyVal.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(s => s.ToUpper()));
                                break;
                            case "CONTAIN":
                                Contain.AddRange(keyVal.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(s => s.ToUpper()));
                                break;
                            case "PROPERTYSETSEQUALTO":
                                PropertySetsEqualTo.AddRange(keyVal.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(s => s.ToUpper()));
                                break;
                            default:
#if DEBUG
                                Debug.WriteLine(string.Format("Invalid Key - {0}", keyVal.Key.ToUpper()));
#endif
                                break;
                        }
                    }
                }
            }
        }
コード例 #15
0
 /// <summary>
 /// Opens the instrumenation section, builds the design time nodes and adds them to the application node.
 /// </summary>
 /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
 /// <param name="rootNode">The root node of the application.</param>
 /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
 protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, ConfigurationSection section)
 {
     if (null != section)
     {
         rootNode.AddNode(new InstrumentationNode((InstrumentationConfigurationSection)section));
     }
 }
コード例 #16
0
 /// <summary>
 /// Opens the oracle connection configuration section, builds the design time nodes and adds them to the application node.
 /// </summary>
 /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
 /// <param name="rootNode">The root node of the application.</param>
 /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
 protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, ConfigurationSection section)
 {
     if (null != section)
     {
         OracleConnectionNodeBuilder builder = new OracleConnectionNodeBuilder(serviceProvider, (OracleConnectionSettings)section);
         builder.Build();
     }
 }
		/// <summary>
		/// Opens the configuration sources section, builds the design time nodes and adds them to the application node.
		/// </summary>
		/// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
		/// <param name="rootNode">The root node of the application.</param>
		/// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
		protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, ConfigurationSection section)
		{			
			if (null != section)
			{
				ConfigurationSourceSectionNodeBuilder builder = new ConfigurationSourceSectionNodeBuilder(serviceProvider, (ConfigurationSourceSection)section);
				rootNode.AddNode(builder.Build());
			}				
		}
コード例 #18
0
 private void CreateConfigurationSection(string configurationName, ConfigurationSection configurationSection)
 {
     if (_Configuration.Sections[configurationName] == null)
     {
         _Configuration.Sections.Add(configurationName, configurationSection);
         _Configuration.Save(ConfigurationSaveMode.Full, true);
     }
 }
コード例 #19
0
        /// <summary>
        /// Initializes the configured switches for <see cref="LogManager"/>.
        /// </summary>
        /// <param name="diagnosticsSection">The system.diagnostics configuration section.</param>
        internal LogManager(ConfigurationSection diagnosticsSection)
        {
            SourceSwitch defaultSwitch;

            configuredSources = GetConfiguredSources(diagnosticsSection);
            configuredSwitches = GetConfiguredSwitches(diagnosticsSection);
            defaultLevel = configuredSwitches.TryGetValue("default", out defaultSwitch) ? defaultSwitch.Level : SourceLevels.Warning;
        }
コード例 #20
0
		/// <summary>
		/// Opens the caching configuration from an application configuration file.
		/// </summary>
		/// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
		/// <param name="rootNode">The <see cref="ConfigurationApplicationNode"/> of the hierarchy.</param>
		/// <param name="section">The caching configuration section or null if no section was found.</param>
		protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, ConfigurationSection section)
		{
			if (null != section)
			{
				CacheManagerSettingsNodeBuilder builder = new CacheManagerSettingsNodeBuilder(serviceProvider, (CacheManagerSettings)section);
				rootNode.AddNode(builder.Build());
			}
		}
コード例 #21
0
 /// <summary>
 /// Opens the exception handling settings configuration section, builds the design time nodes and adds them to the application node.
 /// </summary>
 /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
 /// <param name="rootNode">The root node of the application.</param>
 /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
 protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, ConfigurationSection section)
 {
     if (null != section)
     {
         ExceptionHandlingSettingsNodeBuilder builder = new ExceptionHandlingSettingsNodeBuilder(serviceProvider, (ExceptionHandlingSettings)section);
         rootNode.AddNode(builder.Build());
     }
 }
コード例 #22
0
		private static ClientSettingsSection CastToClientSection(ConfigurationSection section)
		{
			if (section is ClientSettingsSection)
				return (ClientSettingsSection)section;

			throw new NotSupportedException(String.Format(
				"The specified ConfigurationSection must be of Type ClientSettingsSection: {0}.", section.GetType().FullName));
		}
コード例 #23
0
 protected override void BeforeSave(ConfigurationSection sectionToSave)
 {
     base.BeforeSave(sectionToSave);
     CacheManagerSettings cacheManagerToSave = (CacheManagerSettings)sectionToSave;
     if (!cacheManagerToSave.BackingStores.Any(x => x.Name == NullBackingStoreName))
     {
         cacheManagerToSave.BackingStores.Add(new CacheStorageData { Type = typeof(NullBackingStore), Name = NullBackingStoreName });
     }
 }
コード例 #24
0
        public void CopyTo(ConfigurationSection[] array, int index)
        {
            if (array == null) throw new ArgumentNullException(nameof(array));

            int c = Count;
            if (array.Length < c + index) throw new ArgumentOutOfRangeException(nameof(index));

            for (int i = 0, j = index; i < c; i++, j++) array[j] = Get(i);
        }
コード例 #25
0
 public void Add(IConfigurationParameter addParameter, string sectionName, ConfigurationSection configurationSection)
 {
     FileConfigurationParameter parameter = addParameter as FileConfigurationParameter;
     if (parameter == null)
     {
         throw new ArgumentException(string.Format(Resources.Culture, Resources.ExceptionUnexpectedType, new object[] { typeof(FileConfigurationParameter).Name }), "saveParameter");
     }
     this.Save(parameter.FileName, sectionName, configurationSection);
 }
コード例 #26
0
ファイル: Profiles.cs プロジェクト: shilinxu/honglt-myproject
        private ConfigurationSection ApplySection(string name, ConfigurationSection section, Type type)
        {
            section = configFile.GetSection(name); if (section == null)
            {
                section = (ConfigurationSection)System.Activator.CreateInstance(type);
                configFile.Sections.Add(name, section);
            }

            return section;
        }
コード例 #27
0
 public void Save(string fileName, string section, ConfigurationSection configurationSection)
 {
     ValidateArgumentsAndFileExists(fileName, section, configurationSection);
     ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap {
         ExeConfigFilename = fileName
     };
     System.Configuration.Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
     configuration.Sections.Remove(section);
     configuration.Sections.Add(section, configurationSection);
     configuration.Save();
 }
コード例 #28
0
        public LoggingSectionViewModel(IUnityContainer builder, string sectionName, ConfigurationSection section)
            : base(builder, sectionName, section)
        {
            if (section as LoggingSettings == null) throw new ArgumentException("section");

            loggingSettings = section as LoggingSettings;

            loggingSettings.SpecialTraceSources.AllEventsTraceSource.Name = "All Events";
            loggingSettings.SpecialTraceSources.ErrorsTraceSource.Name = "Logging Errors & Warnings";
            loggingSettings.SpecialTraceSources.NotProcessedTraceSource.Name = "Unprocessed Category";
        }
コード例 #29
0
        public void GetLastestPropertiesValues(ConfigurationSection configurationSection)
        {
            foreach (PropertyInformation item in configurationSection.ElementInformation.Properties)
            {
                var value = item.Value;
                if (item.Name.Equals("testValue"))
                    value = "!!!! TEST WORKS !!";

                this.PropertyLoaded(this, new Tuple<string, object>(item.Name, value));
            }
        }
コード例 #30
0
ファイル: AppConfig.cs プロジェクト: BrianGoff/BITS
 /// <summary>
 /// Handles the conversion of the XmlNodeSectionHandler to an XmlNode
 /// </summary>
 /// <param name="section">The section to prepare</param>
 /// <returns>XmlNode if the passed section is an XmlNodeSectionHandler</returns>
 private static object PrepareConfigurationSection(ConfigurationSection section)
 {
     if (section is SectionHandlers.XmlNodeSectionHandler)
     {
         return ((SectionHandlers.XmlNodeSectionHandler)section).XmlNode;
     }
     else
     {
         return section;
     }
 }
コード例 #31
0
 protected override void BeforeSave(ConfigurationSection sectionToSave)
 {
     AppSettingsSection appSettingsSectionToSave = (AppSettingsSection)sectionToSave;
     appSettingsSectionToSave.Settings.Clear();
     foreach(var keyValueConfigurationElement in base.DescendentElements(x=>x.ConfigurationType == typeof(KeyValueConfigurationElement)))
     {
         string key = (string)keyValueConfigurationElement.Property("Key").Value;
         string value =  (string)keyValueConfigurationElement.Property("Value").Value;
         
         appSettingsSectionToSave.Settings.Add(key, value);
     }
 }
コード例 #32
0
        public override ConfigurationSection ProcessConfigurationSection(ConfigurationSection configSection)
        {
            switch (configSection)
            {
            case AppSettingsSection appSettingsSection:
                return(ProcessAppSettingsSection(appSettingsSection));

            case ConnectionStringsSection connectionStringsSection:
                return(ProcessConnectionStringsSection(connectionStringsSection));

            default:
                return(base.ProcessConfigurationSection(configSection));
            }
        }
コード例 #33
0
        // update the configuration options in <system.webServer> section
        public void SystemWebServer()
        {
            System.Configuration.ConfigurationSection webServerSecton = config.GetSection("system.webServer");

            // some extra settings for Win7
            String extraWin7Nodes = "";

            if (_Win7Security)
            {
                extraWin7Nodes = @"<authentication>
                    <windowsAuthentication useKernelMode='true'>
                        <extendedProtection tokenChecking='None' />
                    </windowsAuthentication>
                </authentication>";
            }
            // update the handler versions
            webServerSecton.SectionInformation.SetRawXml(string.Format(webServerSecton.SectionInformation.GetRawXml(), _AssemblyVersion, extraWin7Nodes));
        }
コード例 #34
0
        // update the compiler information in <system.codedom> section
        public void SystemCodeDom()
        {
            // update the compiler versions
            System.Configuration.ConfigurationSection systemCodeDomSection = config.GetSection("system.codedom") as System.Configuration.ConfigurationSection;
            XElement codeDom = XElement.Parse(systemCodeDomSection.SectionInformation.GetRawXml());

            XElement compilers = new XElement("compilers");

            codeDom.Add(compilers);
            XElement compiler = new XElement("compiler");

            compilers.Add(compiler);
            compiler.Add(new XAttribute("language", "c#;cs;csharp"));
            compiler.Add(new XAttribute("extension", ".cs"));
            compiler.Add(new XAttribute("type", "Microsoft.CSharp.CSharpCodeProvider, System, Version=" + _CompilerAssemblyVersion + ", Culture=neutral, PublicKeyToken=b77a5c561934e089"));
            XElement providerOption = new XElement("providerOption");

            compiler.Add(providerOption);
            providerOption.Add(new XAttribute("name", "CompilerVersion"));
            providerOption.Add(new XAttribute("value", "v" + _CompilerVersion));

            // if _TrustLevel is not "Full", do not specify compilerOptions or waringLevel
            if (_TrustLevel.ToLower().Equals("full"))
            {
                string compilerOptions = _CompilerOptions;

                if (!Versioning.Server.SupportsV2Features)
                {
                    compilerOptions += " /Define:ASTORIA_PRE_V2";
                }

                compiler.Add(new XAttribute("compilerOptions", compilerOptions));
                compiler.Add(new XAttribute("warningLevel", 4));
            }

            systemCodeDomSection.SectionInformation.SetRawXml(codeDom.ToString());
        }
コード例 #35
0
        override protected object GetRuntimeObject(object result)
        {
            object runtimeObject;
            ConfigurationSection section = result as ConfigurationSection;

            if (section == null)
            {
                runtimeObject = result;
            }
            else
            {
                // Call into config section while impersonating process or UNC identity
                // so that the section could read files from disk if needed
                try {
                    using (Impersonate()) {
                        // If this configRecord is trusted, ignore user code on stack
                        if (_flags[IsTrusted])
                        {
                            runtimeObject = GetRuntimeObjectWithFullTrust(section);
                        }
                        else
                        {
                            // Run configuration section handlers as if user code was on the stack
                            runtimeObject = GetRuntimeObjectWithRestrictedPermissions(section);
                        }
                    }
                }
                catch (Exception e) {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Config_exception_in_config_section_handler, section.SectionInformation.SectionName), e);
                }
                catch {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Config_exception_in_config_section_handler, section.SectionInformation.SectionName));
                }
            }

            return(runtimeObject);
        }
コード例 #36
0
        private object GetRuntimeObjectWithRestrictedPermissions(ConfigurationSection section)
        {
            object runtimeObject;
            bool   flag = false;

            try
            {
                PermissionSet restrictedPermissions = base.GetRestrictedPermissions();
                if (restrictedPermissions != null)
                {
                    restrictedPermissions.PermitOnly();
                    flag = true;
                }
                runtimeObject = section.GetRuntimeObject();
            }
            finally
            {
                if (flag)
                {
                    CodeAccessPermission.RevertPermitOnly();
                }
            }
            return(runtimeObject);
        }
コード例 #37
0
 public void Add(string name, ConfigurationSection section)
 {
     this.VerifyIsAttachedToConfigRecord();
     this._configRecord.AddConfigurationSection(this._configSectionGroup.SectionGroupName, name, section);
     base.BaseAdd(name, name);
 }
 /// <summary>
 /// Initializes the DGTEL.SampleAB.
 /// </summary>
 /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
 /// <param name="rootNode">The root node of the application.</param>
 /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource"/>.</param>
 protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, System.Configuration.ConfigurationSection section)
 {
     if (null != section)
     {
         ApplicationBlockSettingsNodeBuilder builder = new ApplicationBlockSettingsNodeBuilder(serviceProvider, (ApplicationBlockSettings)section);
         rootNode.AddNode(builder.Build());
     }
 }
コード例 #39
0
 internal void SetParentSection(ConfigurationSection parent)
 {
     this.parent = parent;
 }
コード例 #40
0
        /// <summary>
        /// Opens the appSettings section, builds the design time nodes and adds them to the application node.
        /// </summary>
        /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
        /// <param name="rootNode">The root node of the application.</param>
        /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
        protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, System.Configuration.ConfigurationSection section)
        {
            if (null != section)
            {
                AppSettingsNodeBuilder builder = new AppSettingsNodeBuilder(serviceProvider, (AppSettingsSection)section);
                AppSettingsNode        node    = builder.Build();
                SetProtectionProvider(section, node);

                rootNode.AddNode(node);
            }
        }
コード例 #41
0
        private void SaveProperties(ExeConfigurationFileMap exeMap, SettingsPropertyValueCollection collection, ConfigurationUserLevel level, SettingsContext context, bool checkUserLevel)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            UserSettingsGroup userGroup = config.GetSectionGroup("userSettings") as UserSettingsGroup;
            bool isRoaming = (level == ConfigurationUserLevel.PerUserRoaming);

#if true // my reimplementation
            if (userGroup == null)
            {
                userGroup = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", userGroup);
            }
            ApplicationSettingsBase asb       = context.CurrentSettings;
            string class_name                 = NormalizeInvalidXmlChars((asb != null ? asb.GetType() : typeof(ApplicationSettingsBase)).FullName);
            ClientSettingsSection userSection = null;
            ConfigurationSection  cnf         = userGroup.Sections.Get(class_name);
            userSection = cnf as ClientSettingsSection;
            if (userSection == null)
            {
                userSection = new ClientSettingsSection();
                userGroup.Sections.Add(class_name, userSection);
            }

            bool hasChanges = false;

            if (userSection == null)
            {
                return;
            }

            foreach (SettingsPropertyValue value in collection)
            {
                if (checkUserLevel && value.Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                {
                    continue;
                }
                // The default impl does not save the ApplicationScopedSetting properties
                if (value.Property.Attributes.Contains(typeof(ApplicationScopedSettingAttribute)))
                {
                    continue;
                }

                hasChanges = true;
                SettingElement element = userSection.Settings.Get(value.Name);
                if (element == null)
                {
                    element = new SettingElement(value.Name, value.Property.SerializeAs);
                    userSection.Settings.Add(element);
                }
                if (element.Value.ValueXml == null)
                {
                    element.Value.ValueXml = new XmlDocument().CreateElement("value");
                }
                switch (value.Property.SerializeAs)
                {
                case SettingsSerializeAs.Xml:
                    element.Value.ValueXml.InnerXml = (value.SerializedValue as string) ?? string.Empty;
                    break;

                case SettingsSerializeAs.String:
                    element.Value.ValueXml.InnerText = value.SerializedValue as string;
                    break;

                case SettingsSerializeAs.Binary:
                    element.Value.ValueXml.InnerText = value.SerializedValue != null?Convert.ToBase64String(value.SerializedValue as byte []) : string.Empty;

                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            if (hasChanges)
            {
                config.Save(ConfigurationSaveMode.Minimal, true);
            }
#else // original impl. - likely buggy to miss some properties to save
            foreach (ConfigurationSection configSection in userGroup.Sections)
            {
                ClientSettingsSection userSection = configSection as ClientSettingsSection;
                if (userSection != null)
                {
/*
 *                                      userSection.Settings.Clear();
 *
 *                                      foreach (SettingsPropertyValue propertyValue in collection)
 *                                      {
 *                                              if (propertyValue.IsDirty)
 *                                              {
 *                                                      SettingElement element = new SettingElement(propertyValue.Name, SettingsSerializeAs.String);
 *                                                      element.Value.ValueXml = new XmlDocument();
 *                                                      element.Value.ValueXml.InnerXml = (string)propertyValue.SerializedValue;
 *                                                      userSection.Settings.Add(element);
 *                                              }
 *                                      }
 */
                    foreach (SettingElement element in userSection.Settings)
                    {
                        if (collection [element.Name] != null)
                        {
                            if (collection [element.Name].Property.Attributes.Contains(typeof(SettingsManageabilityAttribute)) != isRoaming)
                            {
                                continue;
                            }

                            element.SerializeAs             = SettingsSerializeAs.String;
                            element.Value.ValueXml.InnerXml = (string)collection [element.Name].SerializedValue;                                ///Value = XmlElement
                        }
                    }
                }
            }
            config.Save(ConfigurationSaveMode.Minimal, true);
#endif
        }
 public void Add(string name, ConfigurationSection section)
 {
 }
コード例 #43
0
        object IInternalConfigSystem.GetSection(string configKey)
        {
            ConfigurationSection s = Configuration.GetSection(configKey);

            return(s != null?s.GetRuntimeObject() : null);
        }
コード例 #44
0
 /// <summary>
 /// Initializes the $Caption$.
 /// </summary>
 /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
 /// <param name="rootNode">The root node of the application.</param>
 /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource"/>.</param>
 protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, System.Configuration.ConfigurationSection section)
 {
     base.OpenCore(serviceProvider, rootNode, section);
     // TODO: This code is useful every time you add a new node to the $Name$ Design-Time. If the new node constains references to other existent nodes, <see cref="IConfigurationUIHierarchy"> is useful to find and them. Then you should verify if it is the node that you are searching for and assign it to the new node.
     //IConfigurationUIHierarchy hierarchy = ServiceHelper.GetCurrentHierarchy(serviceProvider);
     //foreach ($Name$Node node in hierarchy.FindNodesByType(typeof($Name$Node)))
     //{
     //    foreach (ReferentNodeType referentNode in hierarchy.FindNodesByType(typeof(ReferentNodeType)))
     //    {
     //        if (referentNode.Name == node.referentNodeName)
     //        {
     //            node.ReferentNode = referentNode;
     //            break;
     //        }
     //    }
     //}
 }
コード例 #45
0
 public virtual ConfigurationSection ProcessConfigurationSection(ConfigurationSection configSection)
 {
     return(configSection);
 }
コード例 #46
0
            private object CreateSectionImpl(
                RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord,
                SectionInput sectionInput, object parentConfig, ConfigXmlReader reader)
            {
                object config;

                if (_sectionCtor != null)
                {
                    ConfigurationSection configSection = (ConfigurationSection)TypeUtil.InvokeCtorWithReflectionPermission(_sectionCtor);

                    configSection.SectionInformation.SetRuntimeConfigurationInformation(configRecord, factoryRecord, sectionRecord);

                    configSection.CallInit();

                    ConfigurationSection parentSection = (ConfigurationSection)parentConfig;
                    configSection.Reset(parentSection);

                    if (reader != null)
                    {
                        configSection.DeserializeSection(reader);
                    }

                    if (configRecord != null && sectionInput != null && sectionInput.ConfigBuilder != null)
                    {
                        configSection = configRecord.CallHostProcessConfigurationSection(configSection, sectionInput.ConfigBuilder);
                    }

                    // throw if there are any cached errors
                    ConfigurationErrorsException errors = configSection.GetErrors();
                    if (errors != null)
                    {
                        throw errors;
                    }

                    // don't allow changes to sections at runtime
                    configSection.SetReadOnly();

                    // reset the modified bit
                    configSection.ResetModified();

                    config = configSection;
                }
                else
                {
                    if (reader != null)
                    {
                        XmlNode xmlNode = ErrorInfoXmlDocument.CreateSectionXmlNode(reader);

                        CheckForLockAttributes(factoryRecord.ConfigKey, xmlNode);

                        // In v1, our old section handler expects a context that contains the virtualPath from the configPath
                        object configContext = configRecord.Host.CreateDeprecatedConfigContext(configRecord.ConfigPath);

                        config = _sectionHandler.Create(parentConfig, configContext, xmlNode);
                    }
                    else
                    {
                        config = null;
                    }
                }

                return(config);
            }
コード例 #47
0
 internal void SetConfigurationSection(SectionInfo config, ConfigurationSection sec)
 {
     elementData [config] = sec;
 }
コード例 #48
0
ファイル: Program.cs プロジェクト: dpoarch/Translate-LOGS
        private static void ExecuteTranslate(string[] args)
        {
            //Make sure the translate is not already runnin
            if (!isAlreadyRunning(args))
            {
                //Populate the plugins passed in that need to be run
                PopulatePlugins(args);

                //Load the current configuration
                System.Configuration.Configuration Appconfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                // Get the collection of the translate plugin groups.
                ConfigurationSectionGroup PluginConfiguration = Appconfig.GetSectionGroup("TranslatePlugins");

                //Load the plugins and execute them
                for (int i = 0; i < PluginConfiguration.Sections.Count; i++)
                {
                    System.Configuration.ConfigurationSection TransConfigSection = PluginConfiguration.Sections[i];

                    TranslateConfig transConfig    = new TranslateConfig(TransConfigSection.SectionInformation.Name);
                    string[]        AssemInfo      = transConfig.ExecutionName.Split(',');
                    string          CurrentPlugin  = AssemInfo[0].Trim();
                    string          PluginFullName = AssemInfo[1].Trim();

                    //Check to see if we need to execute this plugin
                    string Config = CurrentPlugin;
                    if (!_PluningsToRun.Contains(CurrentPlugin.ToLower()))
                    {
                        if (!_PluningsToRun.Contains(TransConfigSection.SectionInformation.Name.ToLower()))
                        {
                            continue;
                        }
                        else
                        {
                            Config = TransConfigSection.SectionInformation.Name;
                        }
                    }

                    //Load the assembly
                    Assembly assembly  = Assembly.Load(CurrentPlugin);
                    Type     ClassType = assembly.GetType(PluginFullName);
                    object   transItem;
                    try
                    {
                        transItem = Activator.CreateInstance(ClassType);
                    }
                    catch (Exception ex)
                    {
                        Logger log = Logger.Create();
                        log.LogMessage("Unhandled exception while trying to create an instance of " + PluginFullName + "\r\n" + ex.StackTrace);
                        continue;
                    }

                    //Check to make sure the plugin is the correct type
                    if (transItem is TranslateItem)
                    {
                        TranslateItem transPlugin = (TranslateItem)transItem;
                        //Execute the translate for this plugin
                        try
                        {
                            transPlugin.ExecuteTranslate(Config);
                        }
                        catch (Exception ex)
                        {
                            Logger log = Logger.Create();
                            log.LogMessage("Unhandled exception during translate " + ex.Message + "\r\n" + ex.StackTrace);
                        }
                    }
                    else
                    {
                        Logger log = Logger.Create();
                        log.LogMessage("Invalid Plugin Loaded. Plugin needs to be of type " + typeof(TranslateItem).FullName);
                    }
                }
            }
            else
            {
                Logger log = Logger.Create();
                log.LogMessage("Translate Already Running.");
                log.LogMessage("Exiting.");
                System.Threading.Thread.Sleep(5000);
            }
        }
コード例 #49
0
 /// <summary>
 /// Initializes the WCF.
 /// </summary>
 /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
 /// <param name="rootNode">The root node of the application.</param>
 /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.IConfigurationSource"/>.</param>
 protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, System.Configuration.ConfigurationSection section)
 {
     base.OpenCore(serviceProvider, rootNode, section);
 }
コード例 #50
0
 private object GetRuntimeObjectWithFullTrust(ConfigurationSection section)
 {
     return(section.GetRuntimeObject());
 }
コード例 #51
0
        // public methods
        public ConfigurationSection GetSection(string sectionName)
        {
            ConfigurationSection section = (ConfigurationSection)_configRecord.GetSection(sectionName);

            return(section);
        }
コード例 #52
0
 public void Add(string name, ConfigurationSection section)
 {
     config.CreateSection(group, name, section);
 }
        /// <summary>
        /// Initializes the security caching store and adds it to the exception settings.
        /// </summary>
        /// <param name="serviceProvider">The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</param>
        /// <param name="rootNode">The root node of the application.</param>
        /// <param name="section">The <see cref="ConfigurationSection"/> that was opened from the <see cref="IConfigurationSource"/>.</param>
        protected override void OpenCore(IServiceProvider serviceProvider, ConfigurationApplicationNode rootNode, System.Configuration.ConfigurationSection section)
        {
            IConfigurationUIHierarchy hierarchy = ServiceHelper.GetCurrentHierarchy(serviceProvider);

            foreach (CachingStoreProviderNode securityCacheNode in hierarchy.FindNodesByType(typeof(CachingStoreProviderNode)))
            {
                foreach (CacheManagerNode cacheManagerNode in hierarchy.FindNodesByType(typeof(CacheManagerNode)))
                {
                    if (cacheManagerNode.Name == securityCacheNode.cacheManagerName)
                    {
                        securityCacheNode.CacheManager = cacheManagerNode;
                        break;
                    }
                }
            }
            base.OpenCore(serviceProvider, rootNode, section);
        }
コード例 #54
0
 public MockInitializeSectionViewModel(IUnityContainer builder, string sectionName, ConfigurationSection section)
     : base(builder, sectionName, section)
 {
 }