/// <summary> /// Retrieves the current UserSettingsSection from the specified configuration, if none /// exists a new one is created. If a previous version of the userSettings exists they /// will be copied to the UserSettingsSection. /// </summary> public static UserSettingsSection UserSettingsFrom(Configuration config) { UserSettingsSection settings = null; try { settings = (UserSettingsSection)config.Sections[SECTION_NAME]; } catch(InvalidCastException) { config.Sections.Remove(SECTION_NAME); } if (settings == null) { settings = new UserSettingsSection(); settings.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser; settings.SectionInformation.RestartOnExternalChanges = false; settings.SectionInformation.Type = String.Format("{0}, {1}", typeof(UserSettingsSection).FullName, typeof(UserSettingsSection).Assembly.GetName().Name); UpgradeUserSettings(config, settings); config.Sections.Add(SECTION_NAME, settings); } else if (!config.HasFile) UpgradeUserSettings(config, settings); if (settings.IsModified()) { try { config.Save(); } catch (Exception e) { Trace.TraceError("{1}\r\n{0}", e, "Failed to save configuration."); } } return settings; }
/// <summary> /// Retrieves the current UserSettingsSection from the specified configuration, if none /// exists a new one is created. If a previous version of the userSettings exists they /// will be copied to the UserSettingsSection. /// </summary> public static UserSettingsSection UserSettingsFrom(Configuration config) { UserSettingsSection settings = null; try { settings = (UserSettingsSection)config.Sections[SECTION_NAME]; } catch (InvalidCastException) { config.Sections.Remove(SECTION_NAME); } if (settings == null) { settings = new UserSettingsSection(); settings.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser; settings.SectionInformation.RestartOnExternalChanges = false; settings.SectionInformation.Type = String.Format("{0}, {1}", typeof(UserSettingsSection).FullName, typeof(UserSettingsSection).Assembly.GetName().Name); UpgradeUserSettings(config, settings); config.Sections.Add(SECTION_NAME, settings); } else if (!config.HasFile) { UpgradeUserSettings(config, settings); } if (settings.IsModified()) { try { config.Save(); } catch (Exception e) { Trace.TraceError("{1}\r\n{0}", e, "Failed to save configuration."); } } return(settings); }
/// <summary> /// Searches for old user settings from previous versions and copies them into the /// configuration provided. /// </summary> /// <param name="config">The configuration to inspect for previous versions</param> /// <param name="settings">The destination UserSettingsSection object</param> public static void UpgradeUserSettings(Configuration config, UserSettingsSection settings) { if (String.IsNullOrEmpty(config.FilePath)) return; try { //pattern for version strings: "1.0.1000.325622", etc Regex match = RegexPatterns.FullVersion; List<String> folders = new List<string>(); string foundVersionFile = null; Version foundVersion = null; //breakdown the current configuration path to work from string newVersionFile = config.FilePath; string fileName = Path.GetFileName(newVersionFile); string versionDir = Path.GetDirectoryName(newVersionFile); string myVersion = Path.GetFileName(versionDir); string allVersions = Path.GetDirectoryName(versionDir); //The last directory in the path should be our current version, if not, get outta here if (false == match.IsMatch(myVersion)) return;//not versioned? //Get any directories that match a basic wildcard mask folders.AddRange(Directory.GetDirectories(allVersions, "*.*.*.*")); foreach (string folder in folders) { //directory must be a numeric version if (false == match.IsMatch(Path.GetFileName(folder))) continue; //user.config file must be located in directory if (!File.Exists(Path.Combine(folder, fileName))) continue;//no data //we are not looking for our own current configuration if (StringComparer.OrdinalIgnoreCase.Equals(myVersion, Path.GetFileName(folder))) continue; //try to parse the version and see if it's the newest, if so hang on to it. try { Version testVersion = new Version(Path.GetFileName(folder)); if (foundVersion == null || testVersion > foundVersion) { foundVersion = testVersion; foundVersionFile = Path.Combine(folder, fileName); } } catch { } } //Hopefully we now have a previous file and version, if not he'll just return. UpgradeSettingsFromFile(config, settings, foundVersion == null ? null : foundVersion.ToString(), myVersion, foundVersionFile); } catch (Exception e) { Trace.TraceError("{1}\r\n{0}", e, "Failed to upgrade user settings."); } }
/// <summary> /// Forces a read of the configuration file specified and copies the settings from /// the old file /// </summary> private static void UpgradeSettingsFromFile(Configuration config, UserSettingsSection settings, string oldVersionString, string newVersionString, string oldVersionConfig) { if (String.IsNullOrEmpty(oldVersionConfig) || !File.Exists(oldVersionConfig)) { return; } //Log.Info("Upgrading settings from version {0} to {1}", oldVersionString, newVersionString); //Copy the config file so that we can modify and read string tempexename = Path.GetTempFileName(); string tempconfig = tempexename + ".config"; try { //Make a copy and modify to ensure that we have a section declaration File.Copy(oldVersionConfig, tempconfig, true); ReplaceConfigDeclaration(tempconfig); //Read the new configuration Configuration upgradeFrom = ConfigurationManager.OpenExeConfiguration(tempexename); UserSettingsSection upgradeSettings = upgradeFrom.Sections[SECTION_NAME] as UserSettingsSection; if (upgradeSettings != null) { //copy the settings settings.CopyFrom(upgradeSettings); //update version upgrade information if (!String.IsNullOrEmpty(upgradeSettings.OriginalVersion)) { settings.OriginalVersion = upgradeSettings.OriginalVersion; } else { settings.OriginalVersion = oldVersionString; } settings.UpgradedVersion = oldVersionString; settings.UpgradedDate = XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind); //I guess it worked ;) Trace.WriteLine("Settings upgrade successful."); } } finally { //done with our temp files try { File.Delete(tempexename); File.Delete(tempconfig); } catch { } } }
/// <summary> /// Deep copy of all settings from one configuration to another. /// </summary> public void CopyFrom(UserSettingsSection otherSection) { foreach (KeyValueConfigurationElement from in otherSection.Settings) { KeyValueConfigurationElement to = this.Settings[from.Key]; if (to == null) { this.Settings.Add(from.Key, from.Value); } else { to.Value = from.Value; } } this.Sections.CopyFrom(otherSection.Sections); }
/// <summary> /// Forces a read of the configuration file specified and copies the settings from /// the old file /// </summary> private static void UpgradeSettingsFromFile(Configuration config, UserSettingsSection settings, string oldVersionString, string newVersionString, string oldVersionConfig) { if (String.IsNullOrEmpty(oldVersionConfig) || !File.Exists(oldVersionConfig)) return; //Log.Info("Upgrading settings from version {0} to {1}", oldVersionString, newVersionString); //Copy the config file so that we can modify and read string tempexename = Path.GetTempFileName(); string tempconfig = tempexename + ".config"; try { //Make a copy and modify to ensure that we have a section declaration File.Copy(oldVersionConfig, tempconfig, true); ReplaceConfigDeclaration(tempconfig); //Read the new configuration Configuration upgradeFrom = ConfigurationManager.OpenExeConfiguration(tempexename); UserSettingsSection upgradeSettings = upgradeFrom.Sections[SECTION_NAME] as UserSettingsSection; if (upgradeSettings != null) { //copy the settings settings.CopyFrom(upgradeSettings); //update version upgrade information if (!String.IsNullOrEmpty(upgradeSettings.OriginalVersion)) settings.OriginalVersion = upgradeSettings.OriginalVersion; else settings.OriginalVersion = oldVersionString; settings.UpgradedVersion = oldVersionString; settings.UpgradedDate = XmlConvert.ToString(DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind); //I guess it worked ;) Trace.WriteLine("Settings upgrade successful."); } } finally { //done with our temp files try { File.Delete(tempexename); File.Delete(tempconfig); } catch { } } }
/// <summary> /// Searches for old user settings from previous versions and copies them into the /// configuration provided. /// </summary> /// <param name="config">The configuration to inspect for previous versions</param> /// <param name="settings">The destination UserSettingsSection object</param> public static void UpgradeUserSettings(Configuration config, UserSettingsSection settings) { if (String.IsNullOrEmpty(config.FilePath)) { return; } try { //pattern for version strings: "1.0.1000.325622", etc Regex match = RegexPatterns.FullVersion; List <String> folders = new List <string>(); string foundVersionFile = null; Version foundVersion = null; //breakdown the current configuration path to work from string newVersionFile = config.FilePath; string fileName = Path.GetFileName(newVersionFile); string versionDir = Path.GetDirectoryName(newVersionFile); string myVersion = Path.GetFileName(versionDir); string allVersions = Path.GetDirectoryName(versionDir); //The last directory in the path should be our current version, if not, get outta here if (false == match.IsMatch(myVersion)) { return; //not versioned? } //Get any directories that match a basic wildcard mask folders.AddRange(Directory.GetDirectories(allVersions, "*.*.*.*")); foreach (string folder in folders) { //directory must be a numeric version if (false == match.IsMatch(Path.GetFileName(folder))) { continue; } //user.config file must be located in directory if (!File.Exists(Path.Combine(folder, fileName))) { continue; //no data } //we are not looking for our own current configuration if (StringComparer.OrdinalIgnoreCase.Equals(myVersion, Path.GetFileName(folder))) { continue; } //try to parse the version and see if it's the newest, if so hang on to it. try { Version testVersion = new Version(Path.GetFileName(folder)); if (foundVersion == null || testVersion > foundVersion) { foundVersion = testVersion; foundVersionFile = Path.Combine(folder, fileName); } } catch { } } //Hopefully we now have a previous file and version, if not he'll just return. UpgradeSettingsFromFile(config, settings, foundVersion == null ? null : foundVersion.ToString(), myVersion, foundVersionFile); } catch (Exception e) { Trace.TraceError("{1}\r\n{0}", e, "Failed to upgrade user settings."); } }
public void TestSettings() { UserSettingsSection settings = UserSettingsSection.DefaultSettings; Assert.IsNull(settings); Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); Assert.IsNull(cfg.GetSection("userSettings")); settings = UserSettingsSection.UserSettingsFrom(cfg); Assert.IsNotNull(settings); Assert.IsNotNull(settings.Settings); Assert.IsNotNull(settings.Sections); settings.Settings.Add("a", "b"); settings["1"] = "2"; Assert.AreEqual("2", settings["1"]); settings["1"] = "3"; Assert.AreEqual("3", settings["1"]); cfg.Save(); ConfigurationManager.RefreshSection("userSettings"); Assert.IsNotNull(UserSettingsSection.DefaultSettings); Assert.AreEqual("b", UserSettingsSection.DefaultSettings["a"]); Assert.IsNotNull(UserSettingsSection.UserSettings); Assert.AreEqual("b", UserSettingsSection.UserSettings["a"]); UserSettingsSection copy = new UserSettingsSection(); settings["a"] = "b"; settings["1"] = "2"; settings.Sections.Add("child.test").Settings.Add("AA", "BB"); copy.CopyFrom(settings); Assert.AreEqual("b", settings["a"]); Assert.AreEqual("2", settings["1"]); Assert.AreEqual("BB", settings.Sections["child.test"]["AA"]); }
/// <summary> /// Deep copy of all settings from one configuration to another. /// </summary> public void CopyFrom(UserSettingsSection otherSection) { foreach (KeyValueConfigurationElement from in otherSection.Settings) { KeyValueConfigurationElement to = this.Settings[from.Key]; if (to == null) this.Settings.Add(from.Key, from.Value); else to.Value = from.Value; } this.Sections.CopyFrom(otherSection.Sections); }