Inheritance: ConfigurationSection
Exemple #1
0
        /// <summary>
        /// Initializes properties based on the specified
        /// property file locations.
        /// </summary>
        private void InitVariables()
        {
            variables = new NameValueCollection();
            foreach (string sectionName in sectionNames)
            {
                object section = ConfigurationUtils.GetSection(sectionName);
                if (section is NameValueCollection)
                {
                    variables.Add((NameValueCollection)section);
                }
#if NET_2_0
                else if (section is System.Configuration.ClientSettingsSection)
                {
                    System.Configuration.ClientSettingsSection clientSettingsSection = (System.Configuration.ClientSettingsSection)section;
                    foreach (SettingElement setting in clientSettingsSection.Settings)
                    {
                        variables.Add(setting.Name, setting.Value.ValueXml.InnerText);
                    }
                }
#endif
                else
                {
                    throw new ArgumentException("Section [" + sectionName +
                                                "] is not handled by the NameValueSectionHandler.");
                }
            }
        }
            public static void WriteSettingElement(Configuration config, ConfigurationSectionGroup sectionGroup, SettingsSerializeAs sas, string name, string value, string namespaceclass)
            {
                ConfigurationSection sec = sectionGroup.Sections.Get(namespaceclass);

                System.Configuration.ClientSettingsSection clisec = sec as ClientSettingsSection;
                if (clisec == null)
                {
                    //创建节
                    clisec = new ClientSettingsSection();
                    sectionGroup.Sections.Add(namespaceclass, clisec);
                }

                SettingElement secEle = clisec.Settings.Get(name);

                if (secEle == null)
                {
                    secEle = new SettingElement(name, sas);
                    clisec.Settings.Add(secEle);
                }
                secEle.Value.ValueXml = new XmlDocument().CreateElement("value");
                if (sas == SettingsSerializeAs.Xml)
                {
                    XmlDocument xmdoc = new XmlDocument();
                    xmdoc.LoadXml(value);
                    secEle.Value.ValueXml.InnerXml = xmdoc.DocumentElement.OuterXml;
                }
                else
                {
                    secEle.Value.ValueXml.InnerText = value;
                }
            }
 private ClientSettingsSection DeclareUserSection(System.Configuration.Configuration config, string sectionName)
 {
     ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("userSettings");
     if (sectionGroup == null)
     {
         sectionGroup = new UserSettingsGroup();
         config.SectionGroups.Add("userSettings", sectionGroup);
     }
     bool flag = false;
     ConfigurationSection section = sectionGroup.Sections[sectionName];
     if (section == null)
     {
         section = new ClientSettingsSection();
         flag = true;
     }
     else if (section is DefaultSection)
     {
         section = this.ReadClientSettingsSection(section);
         if (section != null)
         {
             sectionGroup.Sections.Remove(sectionName);
             flag = true;
         }
     }
     if (flag)
     {
         section.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
         section.SectionInformation.RequirePermission = false;
         sectionGroup.Sections.Add(sectionName, section);
     }
     return (section as ClientSettingsSection);
 }
Exemple #4
0
        // Declares the section handler of a given section in its section group, if a declaration isn't already
        // present.
        private static void DeclareSection(Configuration config, string sectionName)
        {
            ConfigurationSectionGroup settingsGroup = config.GetSectionGroup(UserSettingsGroupName);

            if (settingsGroup == null)
            {
                //Declare settings group
                ConfigurationSectionGroup group = new UserSettingsGroup();
                config.SectionGroups.Add(UserSettingsGroupName, group);
            }

            settingsGroup = config.GetSectionGroup(UserSettingsGroupName);

            Debug.Assert(settingsGroup != null, "Failed to declare settings group");

            if (settingsGroup != null)
            {
                ConfigurationSection section = settingsGroup.Sections[sectionName];
                if (section == null)
                {
                    section = new ClientSettingsSection();
                    section.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
                    section.SectionInformation.RequirePermission  = false;
                    settingsGroup.Sections.Add(sectionName, section);
                }
            }
        }
Exemple #5
0
        internal static IDictionary ReadSettingsFromFile(string configFileName, string sectionName, bool isUserScoped)
        {
            IDictionary dictionary = new Hashtable();

            if (!isUserScoped || ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                string str = isUserScoped ? "userSettings/" : "applicationSettings/";
                ExeConfigurationFileMap fileMap   = new ExeConfigurationFileMap();
                ConfigurationUserLevel  userLevel = isUserScoped ? ConfigurationUserLevel.PerUserRoaming : ConfigurationUserLevel.None;
                if (isUserScoped)
                {
                    fileMap.ExeConfigFilename         = ConfigurationManagerInternalFactory.Instance.ApplicationConfigUri;
                    fileMap.RoamingUserConfigFilename = configFileName;
                }
                else
                {
                    fileMap.ExeConfigFilename = configFileName;
                }
                ClientSettingsSection section = ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel).GetSection(str + sectionName) as ClientSettingsSection;
                if (section == null)
                {
                    return(dictionary);
                }
                foreach (SettingElement element in section.Settings)
                {
                    dictionary[element.Name] = new StoredSetting(element.SerializeAs, element.Value.ValueXml);
                }
            }
            return(dictionary);
        }
        private void LoadProperties(ExeConfigurationFileMap exeMap, SettingsPropertyCollection collection, ConfigurationUserLevel level, string sectionGroupName, bool allowOverwrite, string groupName)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            ConfigurationSectionGroup sectionGroup = config.GetSectionGroup(sectionGroupName);

            if (sectionGroup != null)
            {
                foreach (ConfigurationSection configSection in sectionGroup.Sections)
                {
                    if (configSection.SectionInformation.Name != groupName)
                    {
                        continue;
                    }

                    ClientSettingsSection clientSection = configSection as ClientSettingsSection;
                    if (clientSection == null)
                    {
                        continue;
                    }

                    foreach (SettingElement element in clientSection.Settings)
                    {
                        LoadPropertyValue(collection, element, allowOverwrite);
                    }
                    // Only the first one seems to be processed by MS
                    break;
                }
            }
        }
		public void EditAfterAdd ()
		{
			Config cfg = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
			UserSettingsGroup u = new UserSettingsGroup ();
			cfg.SectionGroups.Add ("userSettings", u);
			ClientSettingsSection c = new ClientSettingsSection ();
			u.Sections.Add ("mine", c);
		}
Exemple #8
0
        protected virtual void Write <T>(SysConf.ClientSettingsSection section, string key, T value = default(T))
        {
            var settingElement = section.Settings.Get(key);

            if (settingElement != null)
            {
                ((SysConf.SettingValueElement)(settingElement.ElementInformation.Properties["value"].Value)).ValueXml.InnerText = value.ToString();
            }
        }
Exemple #9
0
        protected override void Write <T>(SysConf.ClientSettingsSection section, string key, T value = default(T))
        {
            if (section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
            }

            _accessedSections.Add(section);

            base.Write(section, key, value);
        }
Exemple #10
0
        protected override T Read <T>(SysConf.ClientSettingsSection section, string key, T value = default(T))
        {
            if (section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
            }

            _accessedSections.Add(section);

            return(base.Read(section, key, value));
        }
Exemple #11
0
        internal void RevertToParent(string sectionName, bool isRoaming)
        {
            if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                throw new ConfigurationErrorsException(System.SR.GetString("UserSettingsNotSupported"));
            }
            System.Configuration.Configuration userConfig = this.GetUserConfig(isRoaming);
            ClientSettingsSection section = this.GetConfigSection(userConfig, sectionName, false);

            if (section != null)
            {
                section.SectionInformation.RevertToParent();
                userConfig.Save();
            }
        }
Exemple #12
0
        private ClientSettingsSection GetConfigSection(System.Configuration.Configuration config, string sectionName, bool declare)
        {
            string str = "userSettings/" + sectionName;
            ClientSettingsSection section = null;

            if (config != null)
            {
                section = config.GetSection(str) as ClientSettingsSection;
                if ((section == null) && declare)
                {
                    this.DeclareSection(config, sectionName);
                    section = config.GetSection(str) as ClientSettingsSection;
                }
            }
            return(section);
        }
 private void DeclareSection(System.Configuration.Configuration config, string sectionName)
 {
     if (config.GetSectionGroup("userSettings") == null)
     {
         ConfigurationSectionGroup group2 = new UserSettingsGroup();
         config.SectionGroups.Add("userSettings", group2);
     }
     ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("userSettings");
     if ((sectionGroup != null) && (sectionGroup.Sections[sectionName] == null))
     {
         ConfigurationSection section = new ClientSettingsSection {
             SectionInformation = { AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser, RequirePermission = false }
         };
         sectionGroup.Sections.Add(sectionName, section);
     }
 }
Exemple #14
0
        private void DeclareSection(System.Configuration.Configuration config, string sectionName)
        {
            if (config.GetSectionGroup("userSettings") == null)
            {
                ConfigurationSectionGroup group2 = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", group2);
            }
            ConfigurationSectionGroup sectionGroup = config.GetSectionGroup("userSettings");

            if ((sectionGroup != null) && (sectionGroup.Sections[sectionName] == null))
            {
                ConfigurationSection section = new ClientSettingsSection {
                    SectionInformation = { AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser, RequirePermission = false }
                };
                sectionGroup.Sections.Add(sectionName, section);
            }
        }
Exemple #15
0
        internal static void RevertToParent(string sectionName, bool isRoaming)
        {
            if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                throw new ConfigurationErrorsException(SR.UserSettingsNotSupported);
            }

            Configuration         config  = GetUserConfig(isRoaming);
            ClientSettingsSection section = GetConfigSection(config, sectionName, false);

            // If the section is null, there is nothing to revert.
            if (section != null)
            {
                section.SectionInformation.RevertToParent();
                config.Save();
            }
        }
Exemple #16
0
        internal static void WriteSettings(string sectionName, bool isRoaming, IDictionary newSettings)
        {
            if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                throw new ConfigurationErrorsException(SR.UserSettingsNotSupported);
            }

            Configuration         config  = GetUserConfig(isRoaming);
            ClientSettingsSection section = GetConfigSection(config, sectionName, true);

            if (section != null)
            {
                SettingElementCollection sec = section.Settings;
                foreach (DictionaryEntry entry in newSettings)
                {
                    SettingElement se = sec.Get((string)entry.Key);

                    if (se == null)
                    {
                        se      = new SettingElement();
                        se.Name = (string)entry.Key;
                        sec.Add(se);
                    }

                    StoredSetting ss = (StoredSetting)entry.Value;
                    se.SerializeAs    = ss.SerializeAs;
                    se.Value.ValueXml = ss.Value;
                }

                try
                {
                    config.Save();
                }
                catch (ConfigurationErrorsException ex)
                {
                    // We wrap this in an exception with our error message and throw again.
                    throw new ConfigurationErrorsException(SR.Format(SR.SettingsSaveFailed, ex.Message), ex);
                }
            }
            else
            {
                throw new ConfigurationErrorsException(SR.SettingsSaveFailedNoSection);
            }
        }
Exemple #17
0
        private static ClientSettingsSection GetConfigSection(Configuration config, string sectionName, bool declare)
        {
            string fullSectionName        = UserSettingsGroupPrefix + sectionName;
            ClientSettingsSection section = null;

            if (config != null)
            {
                section = config.GetSection(fullSectionName) as ClientSettingsSection;

                if (section == null && declare)
                {
                    // Looks like the section isn't declared - let's declare it and try again.
                    DeclareSection(config, sectionName);
                    section = config.GetSection(fullSectionName) as ClientSettingsSection;
                }
            }

            return(section);
        }
Exemple #18
0
        internal IDictionary ReadSettings(string sectionName, bool isUserScoped)
        {
            IDictionary dictionary = new Hashtable();

            if (!isUserScoped || ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                string str = isUserScoped ? "userSettings/" : "applicationSettings/";
                ConfigurationManager.RefreshSection(str + sectionName);
                ClientSettingsSection section = ConfigurationManager.GetSection(str + sectionName) as ClientSettingsSection;
                if (section == null)
                {
                    return(dictionary);
                }
                foreach (SettingElement element in section.Settings)
                {
                    dictionary[element.Name] = new StoredSetting(element.SerializeAs, element.Value.ValueXml);
                }
            }
            return(dictionary);
        }
Exemple #19
0
        private void LoadProperies(ExeConfigurationFileMap exeMap, SettingsPropertyCollection collection, ConfigurationUserLevel level, string sectionGroupName, bool allowOverwrite)
        {
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap, level);

            ConfigurationSectionGroup sectionGroup = config.GetSectionGroup(sectionGroupName);

            if (sectionGroup != null)
            {
                foreach (ConfigurationSection configSection in sectionGroup.Sections)
                {
                    ClientSettingsSection clientSection = configSection as ClientSettingsSection;
                    if (clientSection != null)
                    {
                        foreach (SettingElement element in clientSection.Settings)
                        {
                            LoadPropertyValue(collection, element, allowOverwrite);
                        }
                    }
                }
            }
        }
    static Settings()
    {
      //load DB based settings...
      using (Proc ControlCentral_s = new Proc("ControlCentral_s")) _DBSettings = ControlCentral_s.ExecuteNameValueCollection();

      //load "app.config" file based settings...
      //it should be noted that *saving* *directly* to the app.config file is a well known no-no... from a security standpoing which isn't really elaborated on much that i can find
      //but that winds up meaning that the *Application* scoped settings accessible via {appname}.Properties.Settings.Default are code gen'd as read only properties.
      //there's lots of folks whining about wanting to *write* to these properties for various reasons out in the forums...
      //the main reason here is that we want the printer mappings to be settable by all users but at the application wide level not user based... 
      //i.e. we don't want every user to be required to select the same printers that everybody on this machine will be using
      //i feel like i basically get the security implications that the administrator/installer must open read/write ACL on the Program Files\{app} folder and app.config file
      //probalby because you can throw config info in those files which opens up even more access or something like that
      //anyway, i'm still going for it until i read more about it... found the following code here: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/13428050-4fde-4c34-90f8-5255f4123a20/
      
      ConfigurationSectionGroup applicationSectionGroup = appConfig.GetSectionGroup("applicationSettings");
      applicationSettingsSection = applicationSectionGroup.Sections[ReflectionHelpers.CurrentAppName + ".Properties.Settings"] as ClientSettingsSection;
      applicationSettingsSection.SectionInformation.ForceSave = true; //crucial, otherwise just doesn't save, even though documentation indicates that it supposedly means save even if there aren't changes
      App = new SettingElementCollectionWrapper(applicationSettingsSection.Settings);

    }
Exemple #21
0
        internal static IDictionary ReadSettingsFromFile(string configFileName, string sectionName, bool isUserScoped)
        {
            IDictionary settings = new Hashtable();

            if (isUserScoped && !ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                return(settings);
            }

            string prefix = isUserScoped ? UserSettingsGroupPrefix : ApplicationSettingsGroupPrefix;
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

            // NOTE: When isUserScoped is true, we don't care if configFileName represents a roaming file or
            //       a local one. All we want is three levels of configuration. So, we use the PerUserRoaming level.
            ConfigurationUserLevel userLevel = isUserScoped ? ConfigurationUserLevel.PerUserRoaming : ConfigurationUserLevel.None;

            if (isUserScoped)
            {
                fileMap.ExeConfigFilename         = ConfigurationManagerInternalFactory.Instance.ApplicationConfigUri;
                fileMap.RoamingUserConfigFilename = configFileName;
            }
            else
            {
                fileMap.ExeConfigFilename = configFileName;
            }

            Configuration         config  = ConfigurationManager.OpenMappedExeConfiguration(fileMap, userLevel);
            ClientSettingsSection section = config.GetSection(prefix + sectionName) as ClientSettingsSection;

            if (section != null)
            {
                foreach (SettingElement setting in section.Settings)
                {
                    settings[setting.Name] = new StoredSetting(setting.SerializeAs, setting.Value.ValueXml);
                }
            }

            return(settings);
        }
Exemple #22
0
        internal void WriteSettings(string sectionName, bool isRoaming, IDictionary newSettings)
        {
            if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                throw new ConfigurationErrorsException(System.SR.GetString("UserSettingsNotSupported"));
            }
            System.Configuration.Configuration userConfig = this.GetUserConfig(isRoaming);
            ClientSettingsSection section = this.GetConfigSection(userConfig, sectionName, true);

            if (section != null)
            {
                SettingElementCollection settings = section.Settings;
                foreach (DictionaryEntry entry in newSettings)
                {
                    SettingElement element = settings.Get((string)entry.Key);
                    if (element == null)
                    {
                        element = new SettingElement {
                            Name = (string)entry.Key
                        };
                        settings.Add(element);
                    }
                    StoredSetting setting = (StoredSetting)entry.Value;
                    element.SerializeAs    = setting.SerializeAs;
                    element.Value.ValueXml = setting.Value;
                }
                try
                {
                    userConfig.Save();
                    return;
                }
                catch (ConfigurationErrorsException exception)
                {
                    throw new ConfigurationErrorsException(System.SR.GetString("SettingsSaveFailed", new object[] { exception.Message }), exception);
                }
            }
            throw new ConfigurationErrorsException(System.SR.GetString("SettingsSaveFailedNoSection"));
        }
Exemple #23
0
        protected virtual T Read <T>(SysConf.ClientSettingsSection section, string key, T value = default(T))
        {
            var settingElement = section.Settings.Get(key);

            if (settingElement != null)
            {
                try
                {
                    var innerValue = ((SysConf.SettingValueElement)(settingElement.ElementInformation.Properties["value"].Value)).ValueXml.InnerText;

                    return((T)Convert.ChangeType(innerValue, typeof(T)));
                }
                catch (Exception)
                {
                    if (value.Equals(default(T)))
                    {
                        throw;
                    }
                }
            }

            return(value);
        }
        // Declares the section handler of a given section in its section group, if a declaration isn't already
        // present. 
        private void DeclareSection(Configuration config, string sectionName) {
            ConfigurationSectionGroup settingsGroup = config.GetSectionGroup(UserSettingsGroupName);
            
            if (settingsGroup == null) {
                //Declare settings group
                ConfigurationSectionGroup group = new UserSettingsGroup();
                config.SectionGroups.Add(UserSettingsGroupName, group);
            }

            settingsGroup = config.GetSectionGroup(UserSettingsGroupName);

            Debug.Assert(settingsGroup != null, "Failed to declare settings group");

            if (settingsGroup != null) {
                ConfigurationSection section = settingsGroup.Sections[sectionName];
                if (section == null) {
                    section = new ClientSettingsSection();
                    section.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
                    section.SectionInformation.RequirePermission = false;
                    settingsGroup.Sections.Add(sectionName, section);
                }
            }
        }
Exemple #25
0
        internal static IDictionary ReadSettings(string sectionName, bool isUserScoped)
        {
            IDictionary settings = new Hashtable();

            if (isUserScoped && !ConfigurationManagerInternalFactory.Instance.SupportsUserConfig)
            {
                return(settings);
            }

            string prefix = isUserScoped ? UserSettingsGroupPrefix : ApplicationSettingsGroupPrefix;

            ConfigurationManager.RefreshSection(prefix + sectionName);
            ClientSettingsSection section = ConfigurationManager.GetSection(prefix + sectionName) as ClientSettingsSection;

            if (section != null)
            {
                foreach (SettingElement setting in section.Settings)
                {
                    settings[setting.Name] = new StoredSetting(setting.SerializeAs, setting.Value.ValueXml);
                }
            }

            return(settings);
        }
        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 (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 = StripXmlHeader(value.SerializedValue as string);
                    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);
            }
        }
        private ClientSettingsSection GetUserSettings(out Configuration config, bool tryAlternates)
        {
            config = null;
            string[] files;
            if (tryAlternates)
                files = new string[] { this.FileName, this.BackupFileName };
            else
                files = new string[] { this.FileName };

            for (int i = 0; i < files.Length; i++)
            {
                string p = files[i];
                if(tryAlternates)
                    if (!System.IO.File.Exists(p)) continue;

                try
                {
                    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                    fileMap.ExeConfigFilename = p;
                    config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                    ConfigurationSection configSection = config.GetSection(USER_SETTINGS_SECTION_NAME);
                    ClientSettingsSection clientSettings = null;
                    if (configSection != null)
                    {
                        clientSettings = (ClientSettingsSection)configSection;
                    }
                    else
                    {
                        clientSettings = new ClientSettingsSection();
                        config.Sections.Add(USER_SETTINGS_SECTION_NAME, clientSettings);
                    }

                    // make a backup copy just in case
                    MakeBackup();

                    return clientSettings;
                }
                catch
                {
                    // file is corrupt
                    if (!tryAlternates)
                    {
                        System.IO.File.Delete(p);
                        return GetUserSettings(out config, tryAlternates);
                    }
                    else
                        continue;
                }
            }
            return null;
        }
            /// <summary>
            /// Inits the specified configuration.
            /// </summary>
            /// <param name="configuration">The configuration.</param>
            /// <param name="sectionName">The name of the section containing the settings.</param>
            /// <exception cref="ArgumentNullException"><paramref name="configuration"/> is <c>null</c>.</exception>
            /// <param name="sectionName">The name of the section containing the settings.</param>
            internal Provider(System.Configuration.Configuration configuration, string sectionName)
            {
                if (configuration == null)
                {
                    throw new ArgumentNullException("configuration");
                }

                if (string.IsNullOrEmpty(sectionName))
                {
                    throw new ArgumentNullException("sectionName");
                }

                _configuration = configuration;

                _sectionName = sectionName;

                var sectionGroup = configuration.GetSectionGroup("applicationSettings");

                _applicationSection = sectionGroup == null ? null : sectionGroup.Sections[_sectionName] as ClientSettingsSection;

                sectionGroup = configuration.GetSectionGroup("userSettings");

                _userSection = sectionGroup == null ? null : sectionGroup.Sections[_sectionName] as ClientSettingsSection;

                // The provider MUST have a name
                Initialize(GetType().Name, null);
            }
		public void EditBeforeAdd ()
		{
			UserSettingsGroup u = new UserSettingsGroup ();
			ClientSettingsSection c = new ClientSettingsSection ();
			u.Sections.Add ("mine", c);
		}
        public static void Init()
        {
            SimpleDotNet.ReportUrl = @"http://code.google.com/p/simple-assembly-explorer/issues/list?can=2";

            string configFile = Path.ChangeExtension(Application.ExecutablePath, ".exe.config");
            if (!File.Exists(configFile))
            {
                throw new ApplicationException(String.Format("Application config file is missing: {0}.", Path.GetFileName(configFile)));
            }

            if (!File.Exists("user.config"))
            {
                using (StreamWriter sw = new StreamWriter("user.config"))
                {
                    sw.WriteLine("<SimpleAssemblyExplorer.Properties.Settings>");
                    sw.WriteLine("</SimpleAssemblyExplorer.Properties.Settings>");
                }
            }

            _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            _css = (ClientSettingsSection)_config.SectionGroups["saeSettings"].Sections[0];

            AddProperty(Consts.ShowAbout, true, typeof(bool));
            AddProperty(Consts.CheckUpdatePeriod, 14, typeof(int));
            AddProperty(Consts.CheckUpdateEnabled, true, typeof(bool));
            AddProperty(Consts.CheckUpdateLastDate, new DateTime(2007, 1, 1), typeof(DateTime));
            AddProperty(Consts.ClassEditorAutoSaveBookmarkEnabled, true, typeof(bool));
            AddProperty(Consts.ClassEditorAutoOpenDroppedAssemblyEnabled, true, typeof(bool));
			AddProperty(Consts.ClassEditorRichTextBoxFont, String.Empty, typeof(String));
            AddProperty(Consts.ClassEditorBamlTranslator, 0, typeof(int));
            AddProperty(Consts.LastPath, String.Empty, typeof(String));
            AddProperty(Consts.LastSaveDir, String.Empty, typeof(String));
            AddProperty(Consts.LastBinDir, String.Empty, typeof(String));
            AddProperty(Consts.LastRegex, String.Empty, typeof(String));
            AddProperty(Consts.MarkBlocks, true, typeof(bool));
            AddProperty(Consts.SNOutputDir, String.Empty, typeof(String));
            AddProperty(Consts.DeobfProfile, 0, typeof(int));
            AddProperty(Consts.DeobfOutputDir, String.Empty, typeof(String));
            AddProperty(Consts.DeobfFlowOptionBranchLoopCount, 2, typeof(int));
            AddProperty(Consts.DeobfFlowOptionMaxMoveCount, 0, typeof(int));
            AddProperty(Consts.DeobfFlowOptionMaxRefCount, 2, typeof(int));
            AddProperty(Consts.DeobfFlowOptionBranchDirection, 0, typeof(int));            
            AddProperty(Consts.DasmOutputDir, String.Empty, typeof(String));
            AddProperty(Consts.DasmAdditionalOptions, String.Empty, typeof(String));
            AddProperty(Consts.AsmAdditionalOptions, String.Empty, typeof(String));
            AddProperty(Consts.PEVerifyAdditionalOptions, String.Empty, typeof(String));
            AddProperty(Consts.SNAdditionalOptions, String.Empty, typeof(String));
            AddProperty(Consts.AsmOutputDir, String.Empty, typeof(String));
            AddProperty(Consts.ClassEditorSaveAsDir, String.Empty, typeof(String));
            AddProperty(Consts.ClassEditorLastSearch, String.Empty, typeof(String));            
            AddProperty(Consts.StrongKeyFile, String.Empty, typeof(String));
            AddProperty(Consts.ProfilerAppFile, String.Empty, typeof(String));
            AddProperty(Consts.ProfilerAppArgument, String.Empty, typeof(String));
            AddProperty(Consts.ProfilerAppFilter, String.Empty, typeof(String));
            AddProperty(Consts.ProfilerAppLogPath, String.Empty, typeof(String));
            AddProperty(Consts.ProfilerAppTraceEvent, false, typeof(bool));
            AddProperty(Consts.ProfilerAppTraceParameter, true, typeof(bool));
            AddProperty(Consts.ProfilerAppIncludeSystem, false, typeof(bool));
            AddProperty(Consts.ProfilerASPNetFilter, String.Empty, typeof(String));
            AddProperty(Consts.ProfilerASPNetLogPath, String.Empty, typeof(String));
            AddProperty(Consts.ProfilerASPNetTraceEvent, false, typeof(bool));
            AddProperty(Consts.ProfilerASPNetTraceParameter, true, typeof(bool));
            AddProperty(Consts.ProfilerASPNetIncludeSystem, false, typeof(bool));
            AddProperty(Consts.RecentPluginList, 10, typeof(int));
            AddProperty(Consts.RecentPlugins, null, typeof(StringCollection));
        }
        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;
                ClientSettingsSection   cs  = new ClientSettingsSection();
                string class_name           = NormalizeInvalidXmlChars((asb != null ? asb.GetType() : typeof(ApplicationSettingsBase)).FullName);
                userGroup.Sections.Add(class_name, cs);
            }

            bool hasChanges = false;

            foreach (ConfigurationSection section in userGroup.Sections)
            {
                ClientSettingsSection userSection = section as ClientSettingsSection;
                if (userSection == null)
                {
                    continue;
                }

                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
        }
		private static SettingElement GetSettingElement(ClientSettingsSection clientSection, PropertyInfo property, bool create)
		{
			SettingElement element = clientSection.Settings.Get(property.Name);
			if (element == null && create)
			{
				element = new SettingElement(property.Name, SettingsClassMetaDataReader.GetSerializeAs(property));
				clientSection.Settings.Add(element);
			}

			return element;
		}
       /// <summary>
       /// 
       /// </summary>
       /// <param name="pConfiguration">Configuration del app.config</param>
       /// <param name="pSectionName">Seccion</param>
        /// <param name="pSectionGroupName">Grupo</param>
       internal static void AddSection(Configuration pConfiguration, String pSectionName,String pSectionGroupName,String pSettingTemplateName)
       {
           ConfigurationSectionGroup wConfigurationSectionGroup =null;
           SettingElement wSettingElement = null;
           XmlDocument doc = new XmlDocument();
           XmlNode xmlValue = doc.CreateNode(XmlNodeType.Element, "value", String.Empty);
           ConfigurationSectionCollection wSections = null;
           if (pSectionGroupName.Length == 0)
           {
               AddSectionFromAssembly(pConfiguration, pSectionName);
               return;
           }
           else
           {
               wConfigurationSectionGroup = pConfiguration.GetSectionGroup(pSectionGroupName);
               if (wConfigurationSectionGroup == null)
                   wConfigurationSectionGroup = AddSectionGroup(pConfiguration, pSectionGroupName);
               wSections = wConfigurationSectionGroup.Sections;
               
           }

           if (wSections.Get(pSectionName) != null) return;

           ClientSettingsSection wClientSettingsSection = new ClientSettingsSection();
           wClientSettingsSection.SectionInformation.RequirePermission = false;
           wClientSettingsSection.SectionInformation.ForceSave = true;
           
           #region Settings


           Dictionary<String, String> wSettings = TemplateProvider.GetSettingDic(pSettingTemplateName);

           if (wSettings != null)
           {
               foreach (KeyValuePair<string, string> seting in wSettings)
               {
                   wSettingElement = new SettingElement();
                   wSettingElement.Name = seting.Key;
                   xmlValue.InnerXml = seting.Value;
                   wSettingElement.Value.ValueXml = xmlValue.Clone();
                   wClientSettingsSection.Settings.Add(wSettingElement);
               }


           }
           #endregion
           wSections.Add(pSectionName, wClientSettingsSection);
           
       }
        /// <summary>
        /// Gets the <see cref="SettingElementCollection"/> for the specified section name within
        /// the specified configuration.
        /// </summary>
        /// <param name="config">The <see cref="Configuration"/> object.</param>
        /// <param name="sectionName">The settings section name.</param>
        /// <returns>
        /// A <see cref="SettingElementCollection"/> for the section, or an empty section if not found.
        /// </returns>
        private static SettingElementCollection GetSettingElementCollection(Configuration config, string sectionName)
        {
            var userSettings = config.GetSectionGroup("userSettings");
            if (userSettings == null)
            {
                userSettings = new UserSettingsGroup();
                config.SectionGroups.Add("userSettings", userSettings);
            }

            var section = userSettings.Sections.Get(sectionName) as ClientSettingsSection;
            if (section == null)
            {
                section = new ClientSettingsSection();
                userSettings.Sections.Add(sectionName, section);
            }

            return section.Settings;
        }
		private static bool UpdateSection(ClientSettingsSection section, IEnumerable<PropertyInfo> properties, IDictionary<string, string> newValues)
		{
			bool modified = false;

			foreach (PropertyInfo property in properties)
			{
				string newValue;
				if (!newValues.TryGetValue(property.Name, out newValue))
					continue;

				SettingElement element = GetSettingElement(section, property, false);
				if (newValue == null)
				{
					if (element != null)
					{
						section.Settings.Remove(element);
						modified = true;
					}

					continue;
				}

				if (element != null)
				{
					string currentValue = GetElementValue(element);
					if (Equals(newValue, currentValue))
						continue;
				}
				else
				{
					element = GetSettingElement(section, property, true);
				}

				modified = true;
				SetElementValue(element, newValue);
			}

			return modified;
		}
		private static bool UpdateSection(ClientSettingsSection clientSection, IEnumerable<PropertyInfo> properties, IDictionary<string, string> newValues)
		{
			bool modified = false;
			
			foreach (PropertyInfo property in properties)
			{
				string newValue;
				if (!newValues.TryGetValue(property.Name, out newValue))
					continue;

				SettingElement element = GetSettingElement(clientSection, property, false);
				string currentValue = element == null ? null : GetElementValue(element);

				string defaultValue = SettingsClassMetaDataReader.GetDefaultValue(property, false);

				bool newValueIsDefault = newValue == null || Equals(newValue, defaultValue);
				bool currentValueIsDefault = currentValue == null || Equals(currentValue, defaultValue);
				if (currentValueIsDefault && newValueIsDefault || Equals(currentValue, newValue))
					continue;

				element = GetSettingElement(clientSection, property, true);
				if (newValueIsDefault)
					newValue = defaultValue; //store defaults because it's convenient for editing.

				SetElementValue(element, newValue);
				modified = true;
			}

			return modified;
		}
		//TODO (CR Sept 2010): instead of automatically storing all the defaults, should we 
		//just store what we're given and also delete stuff when we're given null?  Then
		//we could just return what's there in the "get" method rather than removing the defaults.
		private static ClientSettingsSection CreateDefaultSection(IEnumerable<PropertyInfo> properties)
		{
			var section = new ClientSettingsSection();
			section.SectionInformation.RequirePermission = false;

			foreach (PropertyInfo property in properties)
			{
				var element = new SettingElement(property.Name, SettingsClassMetaDataReader.GetSerializeAs(property));
				var valueElement = new SettingValueElement();
				element.Value = valueElement;
				
				string value = SettingsClassMetaDataReader.GetDefaultValue(property, false);
				SetElementValue(element, value);
				section.Settings.Add(element);
			}

			return section;
		}
 public void Add(string name, ClientSettingsSection section)
 {
     this.sectionGroup.Sections.Add(name, section);
 }
 private void DeserializeFromXmlElement(SettingsProperty property, SettingsPropertyValue spv, ClientSettingsSection clientSettings)
 {
     if (clientSettings != null)
     {
         SettingElement se = clientSettings.Settings.Get(spv.Name);
         if (se != null)
         {
             string innerXml = se.Value.ValueXml.InnerXml;
             if (se.SerializeAs == SettingsSerializeAs.String)
             {
                 innerXml = this.Escaper.Unescape(innerXml);
             }
             spv.SerializedValue = innerXml;
             innerXml = null;
         }
         else if (property.DefaultValue != null)
         {
             spv.SerializedValue = property.DefaultValue;
         }
         else
         {
             spv.PropertyValue = null;
         }
     }
 }
		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 (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 = StripXmlHeader (value.SerializedValue as string);
					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);
		}
 private ClientSettingsSection ReadClientSettingsSection(ConfigurationSection section)
 {
     ClientSettingsSection section2 = section as ClientSettingsSection;
     if ((section2 == null) && (section is DefaultSection))
     {
         MethodInfo info = typeof(ClientSettingsSection).GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance, null, new System.Type[] { typeof(XmlReader) }, null);
         if (info == null)
         {
             return section2;
         }
         section2 = new ClientSettingsSection();
         using (XmlReader reader = XmlReader.Create(new StringReader(section.SectionInformation.GetRawXml())))
         {
             info.Invoke(section2, new object[] { reader });
         }
     }
     return section2;
 }
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Gets the section <paramref name="sectionName"/> in the section group "userSettings".
        /// </summary>
        /// ------------------------------------------------------------------------------------
        private static ClientSettingsSection GetSection(Configuration config, string sectionName,
			string sectionGroup = "userSettings")
        {
            var userSettingsGroup = config.GetSectionGroup(sectionGroup);
            if (userSettingsGroup == null)
            {
                userSettingsGroup = new ConfigurationSectionGroup();
                config.SectionGroups.Add(sectionGroup, userSettingsGroup);
            }
            var section = userSettingsGroup.Sections[sectionName] as ClientSettingsSection;
            if (section == null)
            {
                section = new ClientSettingsSection();
                userSettingsGroup.Sections.Add(sectionName, section);
            }
            return section;
        }
		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;
				ClientSettingsSection cs = new ClientSettingsSection ();
				string class_name = NormalizeInvalidXmlChars ((asb != null ? asb.GetType () : typeof (ApplicationSettingsBase)).FullName);
				userGroup.Sections.Add (class_name, cs);
			}

			bool hasChanges = false;

			foreach (ConfigurationSection section in userGroup.Sections) {
				ClientSettingsSection userSection = section as ClientSettingsSection;
				if (userSection == null)
					continue;

				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
		}
Exemple #44
0
        } // SaveAs

        // ----------------------------------------------------------------------
        public void Import(UserConfig importUserConfig, bool overwriteSettings)
        {
            if (importUserConfig == null)
            {
                throw new ArgumentNullException("importUserConfig");
            }

            foreach (ConfigurationSectionGroup importSectionGroup in importUserConfig.configuration.SectionGroups)
            {
                UserSettingsGroup importUserSettingsGroup = importSectionGroup as UserSettingsGroup;
                if (importUserSettingsGroup == null)
                {
                    continue;
                }

                UserSettingsGroup userSettingsGroup = configuration.SectionGroups[importSectionGroup.Name] as UserSettingsGroup;
                if (userSettingsGroup == null)
                {
                    userSettingsGroup = new UserSettingsGroup();
                    configuration.SectionGroups.Add(importSectionGroup.Name, userSettingsGroup);
                }

                foreach (ConfigurationSection importSection in importSectionGroup.Sections)
                {
                    ClientSettingsSection importClientSettingsSection = importSection as ClientSettingsSection;
                    if (importClientSettingsSection == null)
                    {
                        continue;
                    }

                    ClientSettingsSection clientSettingsSection = userSettingsGroup.Sections[importSection.SectionInformation.Name] as ClientSettingsSection;
                    if (clientSettingsSection == null)
                    {
                        clientSettingsSection = new ClientSettingsSection();
                        userSettingsGroup.Sections.Add(importSection.SectionInformation.Name, clientSettingsSection);
                    }

                    foreach (SettingElement importSettingElement in importClientSettingsSection.Settings)
                    {
                        bool newSetting = false;

                        SettingElement settingElement = clientSettingsSection.Settings.Get(importSettingElement.Name);
                        if (settingElement == null)
                        {
                            newSetting = true;
                            settingElement = new SettingElement();
                            settingElement.Name = importSettingElement.Name;
                            settingElement.SerializeAs = importSettingElement.SerializeAs;
                            clientSettingsSection.Settings.Add(settingElement);
                        }

                        if (!newSetting && !overwriteSettings)
                        {
                            continue;
                        }

                        SettingValueElement settingValueElement = new SettingValueElement();
                        settingValueElement.ValueXml = importSettingElement.Value.ValueXml;
                        settingElement.SerializeAs = importSettingElement.SerializeAs;
                        settingElement.Value = settingValueElement;
                        clientSettingsSection.Settings.Add(settingElement);
                    }
                }
            }
        } // Import
Exemple #45
0
        /// <summary>
        /// Save Last.fm.API library settings
        /// </summary>
        /// <returns>Indicate if settings was saved successful</returns>
        public static bool Save()
        {
            if (!contextChanged)
            {
                return false;
            }

            switch (_configType)
            {
                case ConfigurationType.AppConfig:
                    return Instance.SaveConfig();
                case ConfigurationType.FromFile:
                    return Instance.SaveFile(File.Exists(configFileName) ? configFileName : ConfigFileName);
                default:
                    switch (Instance.AutoSaveSettings)
                    {
                        case AutoSaveSettingsMode.ToAppConfig:
                            {
                                string exeFile = Environment.GetCommandLineArgs()[0];
                                Configuration config = ConfigurationManager.OpenExeConfiguration(exeFile);
                                ConfigurationSection appSettings = config.Sections.Get(ConfigSectionName);
                                ClientSettingsSection newAppSettings = new ClientSettingsSection();
                                if (null == appSettings)
                                {
                                    config.Sections.Add(ConfigSectionName, newAppSettings);
                                }
                                else
                                {
                                    newAppSettings = (ClientSettingsSection)appSettings;
                                }

                                foreach (KeyValuePair<string, PropertyInfo> property in publicProperties)
                                {
                                    SettingElement element = null;
                                    Instance.ChangeValue(property.Value, property.Key, ref element);
                                    newAppSettings.Settings.Add(element);
                                }

                                try
                                {
                                    config.Save(ConfigurationSaveMode.Full);
                                }
                                catch (Exception)
                                {
                                    return false;
                                }

                                _configType = ConfigurationType.AppConfig;
                                return true;
                            }
                        case AutoSaveSettingsMode.ToXmlFile:
                            bool bRes = Instance.SaveFile(ConfigFileName);
                            if (bRes)
                            {
                                _configType = ConfigurationType.FromFile;
                            }

                            return bRes;
                        default:
                            return false;
                    }
            }
        }
        private bool Initialize()
        {
            IConfiguration configuration = GetConfiguration(SettingsLocation);

            if (configuration == null) { return false; }

            _configuration = configuration;
            IConfigurationSectionGroup userGroup = this._configuration.GetSectionGroup(UserSettingsGroupName);
            if (userGroup == null)
            {
                userGroup = configuration.AddSectionGroup(UserSettingsGroupName);
            }

            ClientSettingsSection clientSettings = userGroup.Get(SettingsSection) as ClientSettingsSection;

            if (clientSettings == null)
            {
                clientSettings = new ClientSettingsSection();
                clientSettings.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
                clientSettings.SectionInformation.RequirePermission = false;
                userGroup.Add(SettingsSection, clientSettings);
            }

            _clientSettings = clientSettings;
            return true;
        }