internal void AddConfigurationSection(string group, string name, ConfigurationSection configSection)
 {
     if (base.IsLocationConfig)
     {
         throw new InvalidOperationException(System.Configuration.SR.GetString("Config_add_configurationsection_in_location_config"));
     }
     BaseConfigurationRecord.VerifySectionName(name, null, false);
     if (configSection == null)
     {
         throw new ArgumentNullException("configSection");
     }
     if (configSection.SectionInformation.Attached)
     {
         throw new InvalidOperationException(System.Configuration.SR.GetString("Config_add_configurationsection_already_added"));
     }
     string configKey = BaseConfigurationRecord.CombineConfigKey(group, name);
     if (base.FindFactoryRecord(configKey, true) != null)
     {
         throw new ArgumentException(System.Configuration.SR.GetString("Config_add_configurationsection_already_exists"));
     }
     if (!string.IsNullOrEmpty(configSection.SectionInformation.ConfigSource))
     {
         this.ChangeConfigSource(configSection.SectionInformation, null, null, configSection.SectionInformation.ConfigSource);
     }
     if (this._sectionFactories != null)
     {
         this._sectionFactories.Add(configKey, new FactoryId(configKey, group, name));
     }
     string type = configSection.SectionInformation.Type;
     if (type == null)
     {
         type = base.Host.GetConfigTypeName(configSection.GetType());
     }
     FactoryRecord factoryRecord = new FactoryRecord(configKey, group, name, type, configSection.SectionInformation.AllowLocation, configSection.SectionInformation.AllowDefinition, configSection.SectionInformation.AllowExeDefinition, configSection.SectionInformation.OverrideModeDefaultSetting, configSection.SectionInformation.RestartOnExternalChanges, configSection.SectionInformation.RequirePermission, this._flags[0x2000], false, base.ConfigStreamInfo.StreamName, -1) {
         Factory = System.Configuration.TypeUtil.GetConstructorWithReflectionPermission(configSection.GetType(), typeof(ConfigurationSection), true),
         IsFactoryTrustedWithoutAptca = System.Configuration.TypeUtil.IsTypeFromTrustedAssemblyWithoutAptca(configSection.GetType())
     };
     base.EnsureFactories()[configKey] = factoryRecord;
     SectionRecord sectionRecord = base.EnsureSectionRecordUnsafe(configKey, false);
     sectionRecord.Result = configSection;
     sectionRecord.ResultRuntimeObject = configSection;
     if (this._removedSections != null)
     {
         this._removedSections.Remove(configKey);
     }
     configSection.SectionInformation.AttachToConfigurationRecord(this, factoryRecord, sectionRecord);
     string rawXml = configSection.SectionInformation.RawXml;
     if (!string.IsNullOrEmpty(rawXml))
     {
         configSection.SectionInformation.RawXml = null;
         configSection.SectionInformation.SetRawXml(rawXml);
     }
 }
 protected virtual Stream SerializeTargetSectionIntoTemporaryStream(ConfigurationSection targetSection)
 {
     var tempStream = new MemoryStream();
     using (var xmlWriter = XmlWriter.Create(tempStream, new XmlWriterSettings { OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment }))
     {
         string sectionTagName = (string)targetSection.GetType().GetProperty("ElementTagName", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(targetSection, null);
         xmlWriter.WriteStartElement(sectionTagName);
         var serializingResult = (bool)targetSection.GetType().GetMethod("SerializeElement", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(targetSection, new object[] { xmlWriter, false });
         if (!serializingResult) throw new ExternalXmlFileConfigSectionLocatorException("Unable to serialize target section!");
         xmlWriter.WriteEndElement();
     }
     return tempStream;
 }
Esempio n. 3
0
        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 <location> element.");
            }

            if (!system.Host.IsDefinitionAllowed(configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition))
            {
                object ctx = 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 '" + ctx + "').");
            }

            if (sec.SectionInformation.Type == null)
            {
                sec.SectionInformation.Type = system.Host.GetConfigTypeName(sec.GetType());
            }

            SectionInfo section = new SectionInfo(name, sec.SectionInformation);

            section.StreamName = streamName;
            section.ConfigHost = system.Host;
            group.AddChild(section);
            elementData [section] = sec;
            sec.Configuration     = this;
        }
        /// <inheritdoc />
        public void Apply(ConfigurationSection section)
        {
            Ensure.ArgumentNotNull(section, "section");
            Ensure.ArgumentTypeAssignableFrom(typeof(CustomConfigurationSection), section.GetType(), "section");

            this.section = (CustomConfigurationSection)section;
        }
        ///<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);
        }
Esempio n. 6
0
		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 <location> element."); 

			if (!system.Host.IsDefinitionAllowed (configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition)) {
				object ctx = 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 '" + ctx + "').");
			}

			if (sec.SectionInformation.Type == null)
				sec.SectionInformation.Type = system.Host.GetConfigTypeName (sec.GetType ());

			SectionInfo section = new SectionInfo (name, sec.SectionInformation);
			section.StreamName = streamName;
			section.ConfigHost = system.Host;
			group.AddChild (section);
			elementData [section] = sec;
			sec.Configuration = this;
		}
Esempio n. 7
0
        /// <summary>
        /// Replaces an existing section with the name provided with a new one.
        /// </summary>
        /// <param name="section">The definintion of the section.</param>
        /// <param name="configuration">The configuration it's being replaced within.</param>
        private static bool SetConfigurationSection(ConfigurationSection section, System.Configuration.Configuration configuration)
        {
            ConfigurationSection existingSection = configuration.GetSection(section.SectionInformation.SectionName);

            // Remove the existing section if it exists.
            if (existingSection != null &&
                existingSection.GetType() == section.GetType())
            {
                foreach (string key in existingSection.ElementInformation.Properties.Keys)
                    existingSection.ElementInformation.Properties[key].Value =
                        section.ElementInformation.Properties[key].Value;
                configuration.Save(ConfigurationSaveMode.Modified);
                return true;
            }
            return false;
        }
        private void InternalSave(string fileName, string section, ConfigurationSection configurationSection, string protectionProvider)
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = fileName;
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            if (typeof(ConnectionStringsSection) == configurationSection.GetType())
            {
                config.Sections.Remove(section);
                UpdateConnectionStrings(section, configurationSection, config, protectionProvider);
            }
            else if (typeof(AppSettingsSection) == configurationSection.GetType())
            {
                UpdateApplicationSettings(section, configurationSection, config, protectionProvider);
            }
            else
            {
                config.Sections.Remove(section);
                config.Sections.Add(section, configurationSection);
                ProtectConfigurationSection(configurationSection, protectionProvider);
            }

            config.Save();

            UpdateImplementation(fileName);
        }
Esempio n. 9
0
		private static ClientSettingsSection CastToClientSection(ConfigurationSection section)
		{
		    var castToClientSection = section as ClientSettingsSection;
		    if (castToClientSection != null)
		        return castToClientSection;

			throw new NotSupportedException(String.Format(
				"The specified ConfigurationSection must be of Type ClientSettingsSection: {0}.", section.GetType().FullName));
		}
Esempio n. 10
0
		private static void MigrateSection(ConfigurationSection sourceSection, ConfigurationSectionGroupPath groupPath, Configuration destinationConfiguration)
		{
			if (sourceSection.GetType().IsDefined(typeof(SharedSettingsMigrationDisabledAttribute), false))
				return; //disabled

			var destinationGroup = groupPath.GetSectionGroup(destinationConfiguration, true);

			var destinationSection = destinationGroup.Sections[sourceSection.SectionInformation.Name];
			if (destinationSection == null)
			{
				destinationSection = (ConfigurationSection)Activator.CreateInstance(sourceSection.GetType(), true);
				destinationGroup.Sections.Add(sourceSection.SectionInformation.Name, destinationSection);
			}

			var customMigrator = sourceSection as IMigrateSettings;
			foreach (PropertyInformation sourceProperty in sourceSection.ElementInformation.Properties)
			{
				var destinationProperty = destinationSection.ElementInformation.Properties[sourceProperty.Name];
				if (destinationProperty == null)
					continue;

				if (customMigrator != null)
				{
					var migrationValues = new SettingsPropertyMigrationValues(
						sourceProperty.Name, MigrationScope.Shared, destinationProperty.Value, sourceProperty.Value);

					customMigrator.MigrateSettingsProperty(migrationValues);
					if (!Equals(migrationValues.CurrentValue, destinationProperty.Value))
					{
						destinationSection.SectionInformation.ForceSave = true; 
						destinationProperty.Value = migrationValues.CurrentValue;
					}
				}
				else
				{
					destinationSection.SectionInformation.ForceSave = true;
					destinationProperty.Value = sourceProperty.Value;
				}
			}
		}
Esempio n. 11
0
		private static bool IsShredSettingsClass(ConfigurationSection section)
		{
			return _shredSettingsTypes.Contains(section.GetType());
		}
        //
        // Add a new configuration section to this config file.
        // This adds both the section declaration and definition to the config file.
        //
        // Called from ConfigurationSectionCollection.Add().
        // Note this method DOES NOT update the associated ConfigurationSectionCollection.
        //
        internal void AddConfigurationSection(string group, string name, ConfigurationSection configSection) {

            // <configSections> is not permitted within a <location> tag.
            if (IsLocationConfig) {
                throw new InvalidOperationException(SR.GetString(SR.Config_add_configurationsection_in_location_config));
            }

            VerifySectionName(name, null, false);

            if (configSection == null) {
                throw new ArgumentNullException("configSection");
            }

            // Ensure the section is not already part of the configuration hierarchy.
            if (configSection.SectionInformation.Attached) {
                throw new InvalidOperationException(SR.GetString(SR.Config_add_configurationsection_already_added));
            }

            string configKey = BaseConfigurationRecord.CombineConfigKey(group, name);

            // Ensure the section is not already declared.
            FactoryRecord factoryRecord = FindFactoryRecord(configKey, true);
            if (factoryRecord != null) {
                throw new ArgumentException(SR.GetString(SR.Config_add_configurationsection_already_exists));
            }

            // Add the configSource if needed.
            if (!String.IsNullOrEmpty(configSection.SectionInformation.ConfigSource)) {
                ChangeConfigSource(configSection.SectionInformation, null, null, configSection.SectionInformation.ConfigSource);
            }

            // Add to list of all sections.
            if (_sectionFactories != null) {
                _sectionFactories.Add(configKey, new FactoryId(configKey, group, name));
            }

            // Get the type name.
            string typeName = configSection.SectionInformation.Type;
            if (typeName == null) {
                typeName = Host.GetConfigTypeName(configSection.GetType());
            }

            // Add a factory record for the section.
            factoryRecord = new FactoryRecord(configKey,
                    group,
                    name,
                    typeName,
                    configSection.SectionInformation.AllowLocation,
                    configSection.SectionInformation.AllowDefinition,
                    configSection.SectionInformation.AllowExeDefinition,
                    configSection.SectionInformation.OverrideModeDefaultSetting,
                    configSection.SectionInformation.RestartOnExternalChanges,
                    configSection.SectionInformation.RequirePermission,
                    _flags[IsTrusted],
                    false,  // isUndeclared
                    ConfigStreamInfo.StreamName,
                    -1);

            // Construct a factory for the section
            factoryRecord.Factory = TypeUtil.GetConstructorWithReflectionPermission(
                    configSection.GetType(), typeof(ConfigurationSection), true);

            factoryRecord.IsFactoryTrustedWithoutAptca = TypeUtil.IsTypeFromTrustedAssemblyWithoutAptca(configSection.GetType());

            EnsureFactories()[configKey] = factoryRecord;

            // Add a section record for the section.
            // Since we are adding a new definition, it cannot be locked.
            SectionRecord sectionRecord = EnsureSectionRecordUnsafe(configKey, false);
            sectionRecord.Result = configSection;
            sectionRecord.ResultRuntimeObject = configSection;

            // Undo any previous removals of the section.
            if (_removedSections != null) {
                _removedSections.Remove(configKey);
            }

            // Attach the section to the configuration record.
            configSection.SectionInformation.AttachToConfigurationRecord(this, factoryRecord, sectionRecord);

            //
            // If there is rawXml, set it now. Note this will override any other changes to the section
            // definition made after the call to SetXml.
            //
            string rawXml = configSection.SectionInformation.RawXml;
            if (!String.IsNullOrEmpty(rawXml)) {
                configSection.SectionInformation.RawXml = null;
                configSection.SectionInformation.SetRawXml(rawXml);
            }
        }
            public ConfigurationSectionMerge(ConfigurationSection parentSection, ConfigurationSection localSection)
            {
                if (parentSection.GetType() != localSection.GetType())
                {
                    string message = String.Format(CultureInfo.CurrentCulture,
                        Resources.ExceptionIncompaitbleMergeElementType,
                        localSection.GetType(),
                        parentSection.GetType());


                    throw new ConfigurationSourceErrorsException(message);
                }

                this.parentSection = parentSection;
                this.localSection = localSection;

            }
Esempio n. 14
0
        /// <summary>
        /// This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
        /// Adds or replaces <paramref name="configurationSection"/> under name <paramref name="section"/> in the configuration 
        /// file named <paramref name="fileName" /> and saves the configuration file.
        /// </summary>
        /// <param name="fileName">The name of the configuration file.</param>
        /// <param name="section">The name for the section.</param>
        /// <param name="configurationSection">The configuration section to add or replace.</param>
        public void Save(string fileName, string section, ConfigurationSection configurationSection)
        {
            ValidateArgumentsAndFileExists(fileName, section, configurationSection);
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = fileName;
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            config.Sections.Remove(section);
            if (typeof(ConnectionStringsSection) == configurationSection.GetType())
            {
                UpdateConnectionStrings(section, configurationSection, config);
            }
            else
            {
                config.Sections.Add(section, configurationSection);
            }
            config.Save();

            UpdateImplementation(fileName);
        }