private void InternalSave(string fileName, string section, ConfigurationSection configurationSection, string protectionProvider)
        {
            var fileMap = new ExeConfigurationFileMap {
                ExeConfigFilename = fileName
            };
            var 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();

            UpdateCache(true);
        }
Ejemplo n.º 2
0
        public void AddGetAndRemoveASection()
        {
            IConfigurationSource source = ConfigurationSourceFactory.Create("sqlSource");

            Assert.AreEqual(typeof(SqlConfigurationSource), source.GetType());

            DummySection dummySection1 = new DummySection();

            dummySection1.Value = 10;

            source.Add(CreateParameter(), localSection, dummySection1);

            ConfigurationSection newSection = source.GetSection(localSection);

            Assert.AreEqual(typeof(DummySection), newSection.GetType());

            DummySection dummySection2 = newSection as DummySection;

            Assert.AreEqual(dummySection1, dummySection2);

            source.Remove(CreateParameter(), localSection);

            newSection = source.GetSection(localSection);
            Assert.AreEqual(null, newSection);
        }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public void Apply(ConfigurationSection section)
        {
            Ensure.ArgumentNotNull(section, "section");
            Ensure.ArgumentTypeAssignableFrom(typeof(CustomConfigurationSection), section.GetType(), "section");

            this.section = (CustomConfigurationSection)section;
        }
            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;
            }
Ejemplo n.º 5
0
        /// <summary>
        /// Walks through the config file extracting the data we need for the model.
        /// </summary>
        /// <param name="tcpHostingConfiguration"></param>
        private static void ReadConfiguration(Configuration tcpHostingConfiguration)
        {
            ConfigurationSectionGroup sg = tcpHostingConfiguration.SectionGroups[ServiceModelTag];
            ConfigurationSection      cs = sg.Sections[NetTcpTag];

            //avoid taking a dependency on System.ServiceModel,
            //use reflection to get the property collections we need.
            System.Reflection.PropertyInfo pi = cs.GetType().GetProperty(AllowAccountsTag);
            ConfigurationElementCollection allowedAccounts = (ConfigurationElementCollection)pi.GetValue(cs, null);

            //enumerates over System.ServiceModel.Activation.Configuration.SecurityIdentifierElement
            List <String> currentSids = new List <string>();

            foreach (ConfigurationElement securityIdentiferElement in allowedAccounts)
            {
                SecurityIdentifier sid = (SecurityIdentifier)securityIdentiferElement.GetType().GetProperty(SecurityIdentifierTag).GetValue(securityIdentiferElement, null);
                if (!currentSids.Contains(sid.ToString()))
                {
                    currentSids.Add(sid.ToString());
                }
            }

            foreach (string sid in currentSids)
            {
                if (!AllowAccounts.Contains(sid))
                {
                    AllowAccounts.Add(sid);
                }
            }
        }
Ejemplo n.º 6
0
        private void LoadSectionValues(string sectionName)
        {
            // Get the section
            ConfigurationSection section = ConfigurationManager.GetSection(sectionName) as ConfigurationSection;

            // Process all it's properties
            foreach (PropertyInfo property in section.GetType().GetProperties())
            {
                // Only process configuration properties
                ConfigurationPropertyAttribute attribute = GetPropertyAttribute(property);
                if (attribute == null)
                {
                    continue;
                }

                // Get the name
                string name = String.Format("{0}.{1}", sectionName, attribute.Name);

                // Get the value
                object value    = property.GetValue(section, null);
                string valueStr = value.ToString();

                // And store it away
                Cfg[name]    = value;
                Values[name] = valueStr;
            }
        }
Ejemplo n.º 7
0
        public void ValidateConfigurationSectionFactory()
        {
            ConfigurationSection configSection = ConfigurationSectionFactory.GetSection(StorageAccountConfigurationSettings.SectionName);

            Assert.IsNotNull(configSection, "Config section is null");
            Assert.AreEqual <Type>(typeof(StorageAccountConfigurationSettings), configSection.GetType(), "Config section is of a wrong type");

            configSection = ConfigurationSectionFactory.GetSection(typeof(RetryPolicyConfigurationSettings).FullName);

            Assert.IsNotNull(configSection, "Config section is null");
            Assert.AreEqual <Type>(typeof(RetryPolicyConfigurationSettings), configSection.GetType(), "Config section is of a wrong type");

            configSection = ConfigurationSectionFactory.GetSection(typeof(ApplicationDiagnosticSettings).AssemblyQualifiedName);

            Assert.IsNotNull(configSection, "Config section is null");
            Assert.AreEqual <Type>(typeof(ApplicationDiagnosticSettings), configSection.GetType(), "Config section is of a wrong type");
        }
Ejemplo n.º 8
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;
                }
            }
        }
Ejemplo n.º 9
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));
        }
Ejemplo n.º 10
0
    public List <ElementItemHeaderInfo> GetElements(
        string sectionName,
        string elementName,
        string virtualPath,
        string site,
        string locationSubPath,
        string server)
    {
        List <ElementItemHeaderInfo> elementList =
            new List <ElementItemHeaderInfo>();

        Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                virtualPath, site, locationSubPath, server);

        ConfigurationSection cs = config.GetSection(sectionName);

        Type sectionType = cs.GetType();

        System.Reflection.PropertyInfo reflectionElement =
            sectionType.GetProperty(elementName);
        Object elementObject = reflectionElement.GetValue(cs, null);

        Type elementType = elementObject.GetType();

        System.Reflection.PropertyInfo reflectionProperty =
            elementType.GetProperty("Count");

        if (reflectionProperty != null)
        {
            int elementCount =
                Convert.ToInt32(reflectionProperty.GetValue(
                                    elementObject, null));
            for (int i = 0; i < elementCount; i++)
            {
                ElementItemHeaderInfo ei = new ElementItemHeaderInfo();
                ei.ItemName = String.Format(
                    "Item {0} of {1}", i + 1, elementCount);
                ei.Index       = i;
                ei.Name        = elementName;
                ei.SectionName = sectionName;
                elementList.Add(ei);
            }
        }
        else
        {
            ElementItemHeaderInfo ei = new ElementItemHeaderInfo();
            ei.Name        = elementName;
            ei.ItemName    = "Item 1 of 1";
            ei.SectionName = sectionName;
            elementList.Add(ei);
        }
        return(elementList);
    }
Ejemplo n.º 11
0
    public static void Main()
    {
        try {
            Configuration c = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            ConfigurationSectionGroup g = c.SectionGroups ["foo"];
            ConfigurationSection      s = g.Sections ["mojoEncryption"];
            Console.WriteLine(s.GetType());
        } catch (Exception e) {
            Console.WriteLine(e);
        }
    }
Ejemplo n.º 12
0
        public void GetsNotificationWhenUpdatingAndRemovingSections()
        {
            ConfigurationChangeWatcher.SetDefaultPollDelayInMilliseconds(50);
            IConfigurationSource source = ConfigurationSourceFactory.Create("sqlSource");

            Assert.AreEqual(typeof(SqlConfigurationSource), source.GetType());

            DummySection dummySection1 = new DummySection();

            dummySection1.Value = 10;

            source.Add(CreateParameter(), localSection, dummySection1);
            bool sourceChanged = false;
            SqlConfigurationSource sqlSource = source as SqlConfigurationSource;

            sqlSource.AddSectionChangeHandler(localSection, delegate(object o, ConfigurationChangedEventArgs args)
            {
                sourceChanged = true;
            });

            ConfigurationSection newSection = source.GetSection(localSection);

            Assert.AreEqual(typeof(DummySection), newSection.GetType());

            DummySection dummySection2 = newSection as DummySection;

            Assert.AreEqual(dummySection1, dummySection2);

            //update the section
            dummySection2.Value = 15;
            sqlSource.Add(CreateParameter(), localSection, dummySection2);

            Thread.Sleep(500);

            Assert.IsTrue(sourceChanged);
            sourceChanged = false;

            //remove the section
            sqlSource.Remove(CreateParameter(), localSection);

            Thread.Sleep(500);

            Assert.IsTrue(sourceChanged);
            sourceChanged = false;

            newSection = sqlSource.GetSection(localSection);
            Assert.AreEqual(null, newSection);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets the settings.
        /// </summary>
        /// <param name="configurationSection">The configuration section.</param>
        /// <returns></returns>
        private KeyValueConfigurationCollection GetSettings(ConfigurationSection configurationSection)
        {
            KeyValueConfigurationCollection result = null;

            if (configurationSection.GetType() == typeof(AppSettingsSection))
            {
                AppSettingsSection appSettingsSection = (AppSettingsSection)configurationSection;
                result = appSettingsSection.Settings;
            }
            else
            {
                throw new NotImplementedException();
            }

            return(result);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 从配置组集合中获取一个配置组
        /// </summary>
        /// <typeparam name="T">要获取的配置组类型</typeparam>
        /// <param name="groups">配置组集合</param>
        /// <param name="groupName">要获取的配置组名称</param>
        /// <param name="createWhenNonExist">不存在时创建</param>
        /// <param name="replaceWhenTypeConflict">获取到的配置组类型与指定类型不一致时是否覆盖</param>
        /// <returns>指定的配置组</returns>
        public static ConfigurationSection GetConfigurationSection(ConfigurationSectionGroup fatherConfigGroup, string sectionName, Type sectionType, bool createWhenNonExist, bool replaceWhenTypeConflict)
        {
            if (object.ReferenceEquals(null, fatherConfigGroup) || object.ReferenceEquals(null, sectionType) || object.ReferenceEquals(null, sectionName) || sectionName.Length == 0)
            {
                return(null);
            }

            ConfigurationSection section = null;
            bool typeConflict            = false;

            try
            {
                section = fatherConfigGroup.Sections[sectionName];

                if (!object.ReferenceEquals(null, section))
                {
                    if (section.GetType().Equals(sectionType))
                    {
                        return(section);
                    }
                    else
                    {
                        typeConflict = true;
                        section      = null;
                    }
                }
            }
            catch
            {
                typeConflict = true;
            }

            //根据参数创建新配置项
            if (createWhenNonExist || (typeConflict && replaceWhenTypeConflict))
            {
                RemoveConfigUnit(fatherConfigGroup, sectionName);
                section = CreateInstance(sectionType) as ConfigurationSection;
                if (!object.ReferenceEquals(null, section))
                {
                    fatherConfigGroup.Sections.Add(sectionName, section);
                }
            }

            return(section);
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Updates the configuration file to match the model
        /// </summary>
        /// <param name="tcpHostingConfiguration">The configuration file to update</param>
        public static void WriteConfiguration(Configuration tcpHostingConfiguration)
        {
            ConfigurationSectionGroup sg = tcpHostingConfiguration.SectionGroups[ServiceModelTag];
            ConfigurationSection      cs = sg.Sections[NetTcpTag];

            //avoid taking a dependency on System.ServiceModel,
            //use reflection to get the property collections we need.
            System.Reflection.PropertyInfo pi = cs.GetType().GetProperty(AllowAccountsTag);
            ConfigurationElementCollection allowedAccounts = (ConfigurationElementCollection)pi.GetValue(cs, null);

            //enumerates over System.ServiceModel.Activation.Configuration.SecurityIdentifierElement
            List <String> currentSids = new List <string>();

            foreach (ConfigurationElement securityIdentiferElement in allowedAccounts)
            {
                SecurityIdentifier sid = (SecurityIdentifier)securityIdentiferElement.GetType().GetProperty(SecurityIdentifierTag).GetValue(securityIdentiferElement, null);
                if (!currentSids.Contains(sid.ToString()))
                {
                    currentSids.Add(sid.ToString());
                }
            }

            //now add the sids that are missing
            //add, contains, remove
            SecurityIdentifierCollectionHelperClass helper = new SecurityIdentifierCollectionHelperClass(allowedAccounts);

            foreach (String sid in AllowAccounts)
            {
                if (!currentSids.Contains(sid))
                {
                    helper.Add(sid);
                }
                else
                {
                    currentSids.Remove(sid);
                }
            }

            foreach (String sid in currentSids)
            {
                helper.Remove(sid);
            }
        }
        /// <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);
        }
Ejemplo n.º 18
0
    public List <ElementItemInfo> GetProperties(
        string sectionName,
        string elementName,
        int index,
        string virtualPath,
        string site,
        string locationSubPath,
        string server)
    {
        List <ElementItemInfo> elementItemList =
            new List <ElementItemInfo>();

        Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                virtualPath, site, locationSubPath, server);

        ConfigurationSection cs = config.GetSection(sectionName);

        Type sectionType = cs.GetType();

        System.Reflection.PropertyInfo reflectionElement =
            sectionType.GetProperty(elementName);
        Object elementObject = reflectionElement.GetValue(cs, null);

        Type elementType = elementObject.GetType();

        System.Reflection.PropertyInfo reflectionProperty =
            elementType.GetProperty("Count");

        int elementCount = reflectionProperty == null ? 0 :
                           Convert.ToInt32(
            reflectionProperty.GetValue(elementObject, null));

        if (elementCount > 0)
        {
            int i = 0;
            ConfigurationElementCollection elementItems =
                elementObject as ConfigurationElementCollection;
            foreach (ConfigurationElement elementItem in elementItems)
            {
                if (i == index)
                {
                    elementObject = elementItem;
                }
                i++;
            }
        }

        Type reflectionItemType = elementObject.GetType();

        PropertyInfo[] elementProperties =
            reflectionItemType.GetProperties();

        foreach (System.Reflection.PropertyInfo rpi in elementProperties)
        {
            if (rpi.Name != "SectionInformation" &&
                rpi.Name != "LockAttributes" &&
                rpi.Name != "LockAllAttributesExcept" &&
                rpi.Name != "LockElements" &&
                rpi.Name != "LockAllElementsExcept" &&
                rpi.Name != "LockItem" &&
                rpi.Name != "Item" &&
                rpi.Name != "ElementInformation" &&
                rpi.Name != "CurrentConfiguration")
            {
                ElementItemInfo eii = new ElementItemInfo();
                eii.Name     = rpi.Name;
                eii.TypeName = rpi.PropertyType.ToString();
                string uniqueID =
                    rpi.Name + index.ToString();
                eii.UniqueID = uniqueID.Replace("/", "");
                ParameterInfo[] indexParms = rpi.GetIndexParameters();
                if (rpi.PropertyType == typeof(IList) ||
                    rpi.PropertyType == typeof(ICollection) ||
                    indexParms.Length > 0)
                {
                    eii.Value = "List";
                }
                else
                {
                    object propertyValue =
                        rpi.GetValue(elementObject, null);
                    eii.Value = propertyValue == null ? "" :
                                propertyValue.ToString();
                }
                elementItemList.Add(eii);
            }
        }
        return(elementItemList);
    }
        /// <summary>
        /// Overrides the <paramref name="configurationObject"/>'s and its internal configuration elements' properties
        /// with the Group Policy values from the registry, if any.
        /// </summary>
        /// <param name="configurationObject">The configuration section that must be managed.</param>
        /// <param name="readGroupPolicies"><see langword="true"/> if Group Policy overrides must be applied; otherwise,
        /// <see langword="false"/>.</param>
        /// <param name="machineKey">The <see cref="IRegistryKey"/> which holds the Group Policy overrides for the
        /// configuration section at the machine level, or <see langword="null"/>
        /// if there is no such registry key.</param>
        /// <param name="userKey">The <see cref="IRegistryKey"/> which holds the Group Policy overrides for the
        /// configuration section at the user level, or <see langword="null"/>
        /// if there is no such registry key.</param>
        /// <returns><see langword="true"/> if the policy settings do not disable the configuration section, otherwise
        /// <see langword="false"/>.</returns>
        /// <exception cref="ArgumentException">when the type of <paramref name="configurationObject"/> is not
        /// the type <typeparamref name="T"/>.</exception>
        public sealed override bool OverrideWithGroupPolicies(ConfigurationSection configurationObject,
                                                              bool readGroupPolicies, IRegistryKey machineKey, IRegistryKey userKey)
        {
            T configurationSection = configurationObject as T;

            if (configurationSection == null)
            {
                throw new ArgumentException(
                          String.Format(CultureInfo.CurrentCulture, Resources.ConfigurationElementOfWrongType, typeof(T).FullName, configurationObject.GetType().FullName),
                          "configurationObject");
            }

            if (!OverrideWithGroupPoliciesForConfigurationSection(configurationSection,
                                                                  readGroupPolicies, machineKey, userKey))
            {
                return(false);
            }

            OverrideWithGroupPoliciesForConfigurationElements(configurationSection,
                                                              readGroupPolicies, machineKey, userKey);

            return(true);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 从XmlReaer加载配置节。此配置节不使用缓存
        /// </summary>
        /// <param name="section">配置节的实例</param>
        /// <param name="reader">XmlReader对象</param>
        /// <param name="sectionName">配置节名称</param>
        /// <param name="checkNullSection">如果配置节为空,是否抛出异常</param>
        /// <returns></returns>
        public static bool LoadSection(this ConfigurationSection section, XmlReader reader, string sectionName, bool checkNullSection = false)
        {
            section.NullCheck("section");
            reader.NullCheck("reader");
            sectionName.CheckStringIsNullOrEmpty("sectionName");

            bool result = false;

            if (reader.ReadToNextSibling(sectionName))
            {
                MethodInfo mi = typeof(ConfigurationSection).GetMethod("DeserializeElement", BindingFlags.Instance | BindingFlags.NonPublic);

                mi.NullCheck <ConfigurationException>("Without DeserializeElement method in type {0}.", section.GetType().FullName);

                mi.Invoke(section, new object[] { reader, false });

                result = true;
            }
            else
            {
                if (checkNullSection)
                {
                    section.CheckSectionNotNull(sectionName);
                }
            }

            return(result);
        }
Ejemplo n.º 21
0
 private static bool IsShredSettingsClass(ConfigurationSection section)
 {
     return(_shredSettingsTypes.Contains(section.GetType()));
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Overrides the <paramref name="configurationObject"/>'s and its internal configuration elements' properties
        /// with the Group Policy values from the registry, if any, and creates the <see cref="ConfigurationSetting"/>
        /// instances that describe the configuration.
        /// </summary>
        /// <param name="configurationObject">The configuration section that must be managed.</param>
        /// <param name="readGroupPolicies"><see langword="true"/> if Group Policy overrides must be applied; otherwise,
        /// <see langword="false"/>.</param>
        /// <param name="machineKey">The <see cref="IRegistryKey"/> which holds the Group Policy overrides for the
        /// configuration section at the machine level, or <see langword="null"/>
        /// if there is no such registry key.</param>
        /// <param name="userKey">The <see cref="IRegistryKey"/> which holds the Group Policy overrides for the
        /// configuration section at the user level, or <see langword="null"/>
        /// if there is no such registry key.</param>
        /// <param name="generateWmiObjects"><see langword="true"/> if WMI objects must be generated; otherwise,
        /// <see langword="false"/>.</param>
        /// <param name="wmiSettings">A collection to where the generated WMI objects are to be added.</param>
        /// <returns><see langword="true"/> if the policy settings do not disable the configuration section, otherwise
        /// <see langword="false"/>.</returns>
        /// <exception cref="ArgumentException">when the type of <paramref name="configurationObject"/> is not
        /// the type <typeparamref name="T"/>.</exception>
        protected internal sealed override bool OverrideWithGroupPoliciesAndGenerateWmiObjects(ConfigurationSection configurationObject,
                                                                                               bool readGroupPolicies, IRegistryKey machineKey, IRegistryKey userKey,
                                                                                               bool generateWmiObjects, ICollection <ConfigurationSetting> wmiSettings)
        {
            T configurationSection = configurationObject as T;

            if (configurationSection == null)
            {
                throw new ArgumentException(
                          String.Format(CultureInfo.CurrentUICulture, Resources.ConfigurationElementOfWrongType, typeof(T).FullName, configurationObject.GetType().FullName),
                          "configurationObject");
            }

            if (!OverrideWithGroupPoliciesAndGenerateWmiObjectsForConfigurationSection(configurationSection,
                                                                                       readGroupPolicies, machineKey, userKey,
                                                                                       generateWmiObjects, wmiSettings))
            {
                return(false);
            }

            OverrideWithGroupPoliciesAndGenerateWmiObjectsForConfigurationElements(configurationSection,
                                                                                   readGroupPolicies, machineKey, userKey,
                                                                                   generateWmiObjects, wmiSettings);

            return(true);
        }
Ejemplo n.º 23
0
    public List <ElementInfo> GetProperties(
        string sectionName,
        string virtualPath,
        string site,
        string locationSubPath,
        string server)
    {
        List <ElementInfo> sectionList = new List <ElementInfo>();

        Configuration config =
            WebConfigurationManager.OpenWebConfiguration(
                virtualPath, site, locationSubPath, server);

        ConfigurationSection cs = config.GetSection(sectionName);
        Type sectionType        = cs.GetType();

        PropertyInfo[] sectionProperties = sectionType.GetProperties();

        foreach (PropertyInfo rpi in sectionProperties)
        {
            if (rpi.Name != "SectionInformation" &&
                rpi.Name != "LockAttributes" &&
                rpi.Name != "LockAllAttributesExcept" &&
                rpi.Name != "LockElements" &&
                rpi.Name != "LockAllElementsExcept" &&
                rpi.Name != "LockItem" &&
                rpi.Name != "ElementInformation" &&
                rpi.Name != "CurrentConfiguration")
            {
                ElementInfo ei = new ElementInfo();
                ei.Name     = rpi.Name;
                ei.TypeName = rpi.PropertyType.ToString();

                if (rpi.PropertyType.BaseType ==
                    typeof(ConfigurationElement))
                {
                    ei.NameUrl = "Element.aspx?Section=" +
                                 sectionName + "&Element=" + rpi.Name;
                    ei.Value = "Element";
                }
                else if (rpi.PropertyType.BaseType ==
                         typeof(ConfigurationElementCollection))
                {
                    ei.NameUrl = "Element.aspx?Section=" +
                                 sectionName + "&Element=" + rpi.Name;
                    ei.Value = "Element Collection";
                }
                else
                {
                    ParameterInfo[] indexParms = rpi.GetIndexParameters();
                    if (rpi.PropertyType == typeof(IList) ||
                        rpi.PropertyType == typeof(ICollection) ||
                        indexParms.Length > 0)
                    {
                        ei.Value = "Collection";
                    }
                    else
                    {
                        object propertyValue = rpi.GetValue(cs, null);
                        ei.Value = propertyValue == null ? "" :
                                   propertyValue.ToString();
                    }
                }
                sectionList.Add(ei);
            }
        }
        return(sectionList);
    }
Ejemplo n.º 24
0
        public void ReadConfigSectionsFromFile()
        {
            using (var temp = new TempConfig(DiagnosticsTestData.Sample))
            {
                var config = ConfigurationManager.OpenExeConfiguration(temp.ExePath);

                ConfigurationSection section = config.GetSection("system.diagnostics");
                Assert.NotNull(section);
                Assert.Equal("SystemDiagnosticsSection", section.GetType().Name);

                ConfigurationElementCollection collection;
                ConfigurationElement[]         items;

                // Verify Switches
                collection = (ConfigurationElementCollection)GetPropertyValue("Switches");
                Assert.Equal("SwitchElementsCollection", collection.GetType().Name);
                Assert.Equal(1, collection.Count);
                items = new ConfigurationElement[1];
                collection.CopyTo(items, 0);
                Assert.Equal("sourceSwitch", items[0].ElementInformation.Properties["name"].Value.ToString());
                Assert.Equal("Error", items[0].ElementInformation.Properties["value"].Value.ToString());

                // Verify SharedListeners
                collection = (ConfigurationElementCollection)GetPropertyValue("SharedListeners");
                Assert.Equal("SharedListenerElementsCollection", collection.GetType().Name);
                Assert.Equal(1, collection.Count);
                items = new ConfigurationElement[1];
                collection.CopyTo(items, 0);
                Assert.Equal("myListener", items[0].ElementInformation.Properties["name"].Value.ToString());
                Assert.Equal("System.Diagnostics.TextWriterTraceListener", items[0].ElementInformation.Properties["type"].Value.ToString());
                Assert.Equal("myListener.log", items[0].ElementInformation.Properties["initializeData"].Value.ToString());

                // Verify Sources
                collection = (ConfigurationElementCollection)GetPropertyValue("Sources");
                Assert.Equal("SourceElementsCollection", GetPropertyValue("Sources").GetType().Name);
                Assert.Equal(1, collection.Count);
                items = new ConfigurationElement[1];
                collection.CopyTo(items, 0);
                Assert.Equal("TraceSourceApp", items[0].ElementInformation.Properties["name"].Value.ToString());
                Assert.Equal("sourceSwitch", items[0].ElementInformation.Properties["switchName"].Value.ToString());
                Assert.Equal("System.Diagnostics.SourceSwitch", items[0].ElementInformation.Properties["switchType"].Value);

                ConfigurationElementCollection listeners = (ConfigurationElementCollection)items[0].ElementInformation.Properties["listeners"].Value;
                Assert.Equal("ListenerElementsCollection", listeners.GetType().Name);
                Assert.Equal(2, listeners.Count);
                ConfigurationElement[] listenerItems = new ConfigurationElement[2];
                listeners.CopyTo(listenerItems, 0);
                Assert.Equal("console", listenerItems[0].ElementInformation.Properties["name"].Value.ToString());
                Assert.Equal("System.Diagnostics.ConsoleTraceListener", listenerItems[0].ElementInformation.Properties["type"].Value.ToString());
                Assert.Equal("myListener", listenerItems[1].ElementInformation.Properties["name"].Value.ToString());

                ConfigurationElement filter = (ConfigurationElement)listenerItems[0].ElementInformation.Properties["filter"].Value;
                Assert.Equal("FilterElement", filter.GetType().Name);
                Assert.Equal("System.Diagnostics.EventTypeFilter", filter.ElementInformation.Properties["type"].Value.ToString());
                Assert.Equal("Error", filter.ElementInformation.Properties["initializeData"].Value.ToString());

                object GetPropertyValue(string propertyName) => section.GetType().
                GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance).
                GetValue(section);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="metadata"></param>
        /// <param name="entity"></param>
        /// <param name="writer"></param>
        /// <param name="context"></param>
        protected override void DoToXml(object parent, PropertyDescriptor metadata, object entity, XmlTextWriter writer, XmlSerializerContext context)
        {
            ConfigurationSection section = (ConfigurationSection)entity;

            if (section == null)
            {
                return;
            }

            Type   entityType  = section.GetType();
            string elementName = metadata.GetElementNameForType(entityType, context, true);

            if (!context.Settings.UniqueSerializationForInstance || !context.Stack.ContainsInstance(entity))
            {
                //agrego la lista a las entidades registradas
                long   id       = context.Stack.AddInstance(entity);
                string valueStr = (string)SerializeMethod.Invoke(section, new object[] { null, elementName, ConfigurationSaveMode.Full });

                //escribo el nombre del elemento...
                writer.WriteStartElement(elementName);

                //recorro el contenido
                StringReader  stringReader = new StringReader(valueStr);
                XmlTextReader reader       = new XmlTextReader(stringReader);

                try
                {
                    reader.MoveToContent();
                    //recorro todos los attributos y los escribo en el destino
                    if (reader.MoveToFirstAttribute())
                    {
                        writer.WriteAttributeString(reader.LocalName, reader.Value);
                        while (reader.MoveToNextAttribute())
                        {
                            writer.WriteAttributeString(reader.LocalName, reader.Value);
                        }
                    }

                    //me fijo si hay que escribir el id
                    //escribo el id del objeto si corresponde
                    if (context.Settings.UniqueSerializationForInstance)
                    {
                        writer.WriteAttributeString(XmlSerializerSettings.ObjectIdAttributeName, id.ToString());
                    }

                    //agrego el tipo de la entidad como ultimo atributo
                    ObjectPropertyDescriptor descriptor = metadata.GetPropertyDescriptor <ObjectPropertyDescriptor>(entityType, context);
                    base.WriteTypeDefinition(descriptor, entityType, context, writer);

                    reader.MoveToContent();
                    string str = reader.ReadInnerXml();
                    if (!string.IsNullOrEmpty(str))
                    {
                        writer.WriteRaw(str);
                    }
                }
                finally
                {
                    stringReader.Close();
                    reader.Close();
                }

                //cierro el tag
                writer.WriteEndElement();
            }
            else
            {
                writer.WriteStartElement(elementName);

                //me fijo si ya existe en el context
                long id = context.Stack.GetInstanceReferenceId(entity);
                writer.WriteAttributeString(XmlSerializerSettings.ObjectReferenceAttributeName, id.ToString());

                writer.WriteEndElement();
            }
        }
        // Helper method trampoline - figure out the appropriate concrete generic
        // method to call based on the type of the configuration section and call it.
        private void OnSectionChanged(ConfigurationSection section, IServiceLocator container)
        {
            var concreteMethod = genericSectionChangedMethod.MakeGenericMethod(section.GetType());

            concreteMethod.Invoke(this, new object[] { section, container });
        }
Ejemplo n.º 27
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));
        }
        static XmlSerializer()
        {
            // The following options are available:
            // MONO_XMLSERIALIZER_DEBUG: when set to something != "no", it will
            //       it will print the name of the generated file, and it won't
            //       be deleted.
            // MONO_XMLSERIALIZER_THS: The code generator threshold. It can be:
            //       no: does not use the generator, always the interpreter.
            //       0: always use the generator, wait until the generation is done.
            //       any number: use the interpreted serializer until the specified
            //       number of serializations is reached. At this point the generation
            //       of the serializer will start in the background. The interpreter
            //       will be used while the serializer is being generated.
            //
            //       XmlSerializer will fall back to the interpreted serializer if
            //       the code generation somehow fails. This can be avoided for
            //       debugging pourposes by adding the "nofallback" option.
            //       For example: MONO_XMLSERIALIZER_THS=0,nofallback

#if NET_2_1
            string db = null;
            string th = null;
            generationThreshold  = -1;
            backgroundGeneration = false;
#else
            string db = Environment.GetEnvironmentVariable("MONO_XMLSERIALIZER_DEBUG");
            string th = Environment.GetEnvironmentVariable("MONO_XMLSERIALIZER_THS");

            if (th == null)
            {
                generationThreshold  = 50;
                backgroundGeneration = true;
            }
            else
            {
                int i = th.IndexOf(',');
                if (i != -1)
                {
                    if (th.Substring(i + 1) == "nofallback")
                    {
                        generatorFallback = false;
                    }
                    th = th.Substring(0, i);
                }

                if (th.ToLower(CultureInfo.InvariantCulture) == "no")
                {
                    generationThreshold = -1;
                }
                else
                {
                    generationThreshold  = int.Parse(th, CultureInfo.InvariantCulture);
                    backgroundGeneration = (generationThreshold != 0);
                }
            }
#endif
            deleteTempFiles = (db == null || db == "no");
#if !NET_2_1 && CONFIGURATION_DEP
            // DiagnosticsSection
            ConfigurationSection table = (ConfigurationSection)ConfigurationSettings.GetConfig("system.diagnostics");
            var bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
            if (table != null)
            {
                // SwitchElementsCollection
                var pi = table.GetType().GetProperty("Switches", bf);
                var switchesElement = (ConfigurationElementCollection)pi.GetValue(table, null);
                foreach (ConfigurationElement e in switchesElement)
                {
                    // SwitchElement
                    if (e.GetType().GetProperty("Name", bf).GetValue(e, null) as string == "XmlSerialization.Compilation")
                    {
                        if (e.GetType().GetProperty("Value", bf).GetValue(e, null) as string == "1")
                        {
                            deleteTempFiles = false;
                        }
                        break;
                    }
                }
            }
#endif
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Executes the custom runtime task component to process the input message and returns the result message.
        /// </summary>
        /// <param name="pContext">A reference to <see cref="Microsoft.BizTalk.Component.Interop.IPipelineContext"/> object that contains the current pipeline context.</param>
        /// <param name="pInMsg">A reference to <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object that contains the message to process.</param>
        /// <returns>A reference to the returned <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object which will contain the output message.</returns>
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            Guard.ArgumentNotNull(pContext, "pContext");
            Guard.ArgumentNotNull(pInMsg, "pInMsg");

            var callToken = TraceManager.PipelineComponent.TraceIn();

            // It is OK to load the entire message into XML DOM. The size of these requests is anticipated to be very small.
            XDocument request = XDocument.Load(pInMsg.BodyPart.GetOriginalDataStream());

            string sectionName     = (from childNode in request.Root.Descendants() where childNode.Name.LocalName == WellKnownContractMember.MessageParameters.SectionName select childNode.Value).FirstOrDefault <string>();
            string applicationName = (from childNode in request.Root.Descendants() where childNode.Name.LocalName == WellKnownContractMember.MessageParameters.ApplicationName select childNode.Value).FirstOrDefault <string>();
            string machineName     = (from childNode in request.Root.Descendants() where childNode.Name.LocalName == WellKnownContractMember.MessageParameters.MachineName select childNode.Value).FirstOrDefault <string>();

            TraceManager.PipelineComponent.TraceInfo(TraceLogMessages.GetConfigSectionRequest, sectionName, applicationName, machineName);

            IConfigurationSource            configSource    = ApplicationConfiguration.Current.Source;
            IApplicationConfigurationSource appConfigSource = configSource as IApplicationConfigurationSource;
            ConfigurationSection            configSection   = appConfigSource != null?appConfigSource.GetSection(sectionName, applicationName, machineName) : configSource.GetSection(sectionName);

            if (configSection != null)
            {
                IBaseMessagePart  responsePart = BizTalkUtility.CreateResponsePart(pContext.GetMessageFactory(), pInMsg);
                XmlWriterSettings settings     = new XmlWriterSettings();

                MemoryStream dataStream = new MemoryStream();
                pContext.ResourceTracker.AddResource(dataStream);

                settings.CloseOutput       = false;
                settings.CheckCharacters   = false;
                settings.ConformanceLevel  = ConformanceLevel.Fragment;
                settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;

                using (XmlWriter configDataWriter = XmlWriter.Create(dataStream, settings))
                {
                    configDataWriter.WriteResponseStartElement("r", WellKnownContractMember.MethodNames.GetConfigurationSection, WellKnownNamespace.ServiceContracts.General);
                    configDataWriter.WriteResultStartElement("r", WellKnownContractMember.MethodNames.GetConfigurationSection, WellKnownNamespace.ServiceContracts.General);

                    SerializableConfigurationSection serializableSection = configSection as SerializableConfigurationSection;

                    if (serializableSection != null)
                    {
                        serializableSection.WriteXml(configDataWriter);
                    }
                    else
                    {
                        MethodInfo info       = configSection.GetType().GetMethod(WellKnownContractMember.MethodNames.SerializeSection, BindingFlags.NonPublic | BindingFlags.Instance);
                        string     serialized = (string)info.Invoke(configSection, new object[] { configSection, sectionName, ConfigurationSaveMode.Full });

                        configDataWriter.WriteRaw(serialized);
                    }

                    configDataWriter.WriteEndElement();
                    configDataWriter.WriteEndElement();
                    configDataWriter.Flush();
                }

                dataStream.Seek(0, SeekOrigin.Begin);
                responsePart.Data = dataStream;
            }
            else
            {
                throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, ExceptionMessages.ConfigurationSectionNotFound, sectionName, ApplicationConfiguration.Current.Source.GetType().FullName));
            }

            TraceManager.PipelineComponent.TraceOut(callToken);
            return(pInMsg);
        }
Ejemplo n.º 30
0
        private ConfigurationSection RetrieveSection(string sectionName)
        {
            var callToken = TraceManager.DebugComponent.TraceIn(sectionName);

            try
            {
                using (ReliableServiceBusClient <IOnPremiseConfigurationServiceChannel> configServiceClient = new ReliableServiceBusClient <IOnPremiseConfigurationServiceChannel>(this.sbEndpointInfo, this.retryPolicy))
                {
                    var startScopeInvokeService = TraceManager.DebugComponent.TraceStartScope(Resources.ScopeOnPremiseConfigurationSourceInvokeService, callToken);

                    try
                    {
                        // Invoke the WCF service in a reliable fashion and retrieve the specified configuration section.
                        XmlElement configSectionXml = configServiceClient.RetryPolicy.ExecuteAction <XmlElement>(() =>
                        {
                            return(configServiceClient.Client.GetConfigurationSection(sectionName, CloudEnvironment.CurrentRoleName, CloudEnvironment.CurrentRoleMachineName));
                        });

                        if (configSectionXml != null)
                        {
                            // Instantiate a configuration object that correspond to the specified section.
                            ConfigurationSection configSection = ConfigurationSectionFactory.GetSection(sectionName);

                            // Gotcha: configuration section deserializer requires a well-formed XML document including processing instruction.
                            XmlDocument configXml = FrameworkUtility.CreateXmlDocument();
                            configXml.AppendChild(configXml.ImportNode(configSectionXml, true));

                            // Configure XML reader settings to disable validation and ignore certain XML entities.
                            XmlReaderSettings settings = new XmlReaderSettings
                            {
                                CloseInput                   = true,
                                IgnoreWhitespace             = true,
                                IgnoreComments               = true,
                                ValidationType               = ValidationType.None,
                                IgnoreProcessingInstructions = true
                            };

                            // Create a reader to consume the XML data.
                            using (XmlReader reader = XmlReader.Create(new StringReader(configXml.OuterXml), settings))
                            {
                                // Attempt to cast the configuration section object into SerializableConfigurationSection for further check.
                                SerializableConfigurationSection serializableSection = configSection as SerializableConfigurationSection;

                                // Check if the the configuration section natively supports serialization/de-serialization.
                                if (serializableSection != null)
                                {
                                    // Yes, it's supported. Invoke the ReadXml method to consume XML and turn it into object model.
                                    serializableSection.ReadXml(reader);
                                }
                                else
                                {
                                    // No, it's unsupported. Need to do something different, starting with positioning the XML reader to the first available node.
                                    reader.Read();

                                    // Invoke the DeserializeSection method via reflection. This is the only way as the method is internal.
                                    MethodInfo info = configSection.GetType().GetMethod(WellKnownContractMember.MethodNames.DeserializeSection, BindingFlags.NonPublic | BindingFlags.Instance);
                                    info.Invoke(configSection, new object[] { reader });
                                }

                                reader.Close();
                            }

                            if (SourceChanged != null)
                            {
                                SourceChanged(this, new ConfigurationSourceChangedEventArgs(this, new string[] { sectionName }));
                            }

                            return(configSection);
                        }
                        else
                        {
                            // The specified section is not supported by the remote configuration source. We should not throw an exception and rely on the caller to handle an empty section.
                            return(null);
                        }
                    }
                    finally
                    {
                        TraceManager.DebugComponent.TraceEndScope(Resources.ScopeOnPremiseConfigurationSourceInvokeService, startScopeInvokeService, callToken);
                    }
                }
            }
            catch (Exception ex)
            {
                TraceManager.DebugComponent.TraceError(ex, callToken);
                throw;
            }
            finally
            {
                TraceManager.DebugComponent.TraceOut(callToken);
            }
        }