diff --git a/Network Monitor.Tests/UserConfigImportTests.cs b/Network Monitor.Tests/UserConfigImportTests.cs deleted file mode 100644 index fecce04..0000000 --- a/Network Monitor.Tests/UserConfigImportTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Xml.Linq; - -namespace Network_Monitor.Tests; - -public sealed class UserConfigImportTests : IDisposable -{ - private readonly string _root = Path.Combine(Path.GetTempPath(), "NetworkMonitorTests", Guid.NewGuid().ToString("N")); - - public void Dispose() - { - if (Directory.Exists(_root)) - Directory.Delete(_root, recursive: true); - } - - private string CurrentCopyPath => Path.Combine(_root, "Network.Monitor_(1).exe_Url_new", "4.1.0.0", "user.config"); - - private string WriteConfig(string copyFolder, string version, DateTime writtenUtc, bool declared = true, bool withPlacement = true, string size = "96") - { - var path = Path.Combine(_root, copyFolder, version, "user.config"); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - - var declaration = declared - ? """ - - -
- - - """ - : ""; - var placement = withPlacement - ? """44""" - : ""; - - File.WriteAllText(path, $""" - - - {declaration} - - - False - {size} - {placement} - - - - """); - File.SetLastWriteTimeUtc(path, writtenUtc); - return path; - } - - private static string ReadSetting(string path, string name) => - XDocument.Load(path).Descendants("setting").FirstOrDefault(x => (string)x.Attribute("name") == name)?.Element("value")?.Value; - - [Fact] - public void ImportIfNewCopy_CopiesTheMostRecentlySavedSettings() - { - WriteConfig("Network.Monitor.exe_Url_old", "4.0.0.0", new DateTime(2026, 1, 1), size: "150"); - var newest = WriteConfig("Network_Monitor.exe_Url_msi", "4.0.0.0", new DateTime(2026, 9, 1), size: "200"); - - var imported = UserConfigImport.ImportIfNewCopy(CurrentCopyPath, includePlacement: true); - - Assert.Equal(newest, imported); - Assert.Equal("200", ReadSetting(CurrentCopyPath, "Size")); - } - - [Fact] - public void ImportIfNewCopy_WhenThisCopyHasSavedBefore_LeavesItToUpgrade() - { - WriteConfig("Network.Monitor_(1).exe_Url_new", "4.0.0.0", new DateTime(2026, 1, 1), size: "150"); - WriteConfig("Network_Monitor.exe_Url_msi", "4.0.0.0", new DateTime(2026, 9, 1), size: "200"); - - var imported = UserConfigImport.ImportIfNewCopy(CurrentCopyPath, includePlacement: true); - - Assert.Null(imported); - Assert.False(File.Exists(CurrentCopyPath)); - } - - [Fact] - public void ImportIfNewCopy_SkipsFilesThatCantBeRead() - { - var readable = WriteConfig("Network.Monitor.exe_Url_old", "4.0.0.0", new DateTime(2026, 1, 1), size: "150"); - var truncated = Path.Combine(_root, "Network_Monitor.exe_Url_msi", "4.0.0.0", "user.config"); - Directory.CreateDirectory(Path.GetDirectoryName(truncated)); - File.WriteAllText(truncated, " - /// Brings in another copy's settings if this copy has none, upgrades settings from an older version, and repairs a settings file that can't be read. + /// Upgrades settings from an older version, and repairs a settings file that can't be read. /// /// False when the app restarted itself to load repaired settings, so this process should exit. public static bool Prepare(string[] args) { - var userConfigPath = TryGetUserConfigPath(); - try { - if (userConfigPath != null) - TryImport(userConfigPath); - if (Settings.Default.MustUpgrade) { Settings.Default.Upgrade(); @@ -36,7 +31,7 @@ public static bool Prepare(string[] args) return true; } - catch (ConfigurationErrorsException ex) when (!args.Contains(RepairedArgument) && TryDeleteUnreadable(ex, userConfigPath)) + catch (ConfigurationErrorsException ex) when (!args.Contains(RepairedArgument) && TryDeleteUnreadable(ex)) { // The settings already failed to load in this process and can't be loaded again, so start over in a fresh one. SingleInstance.Release(); @@ -46,49 +41,16 @@ public static bool Prepare(string[] args) } /// - /// Returns where this copy keeps its settings for the current version, or null if the existing file can't even be opened, which deals with. - /// - private static string TryGetUserConfigPath() - { - try - { - return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath; - } - catch (ConfigurationErrorsException) - { - return null; - } - } - - private static void TryImport(string userConfigPath) - { - try - { - UserConfigImport.ImportIfNewCopy(userConfigPath, includePlacement: !IsAnotherCopyRunning()); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Xml.XmlException) - { - // Starting from defaults is better than not starting. - } - } - - /// - /// Deletes the settings file that failed to load, as long as it belongs to this copy (the current file or the older one reads). + /// Deletes the settings file that failed to load, which is this copy's current one or the older one reads. /// A file cut short by a power loss would otherwise stop the app from starting every time, and reinstalling doesn't remove it. /// - private static bool TryDeleteUnreadable(ConfigurationErrorsException exception, string userConfigPath) + private static bool TryDeleteUnreadable(ConfigurationErrorsException exception) { var failedFile = (exception.InnerException as ConfigurationErrorsException)?.Filename ?? exception.Filename; if (string.IsNullOrEmpty(failedFile) || !string.Equals(Path.GetFileName(failedFile), "user.config", StringComparison.OrdinalIgnoreCase)) return false; - // When the current file can't be opened its path isn't known up front, but the failing file names it. - var copyFolder = Path.GetDirectoryName(Path.GetDirectoryName(userConfigPath ?? failedFile)); - - if (!IsInFolder(failedFile, copyFolder)) - return false; - try { File.Delete(failedFile); @@ -99,40 +61,4 @@ private static bool TryDeleteUnreadable(ConfigurationErrorsException exception, return false; } } - - /// - /// Returns whether is inside . - /// - public static bool IsInFolder(string path, string folder) => - Path.GetFullPath(path).StartsWith(Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); - - /// - /// Returns whether another copy of Network Monitor is running, at any path. - /// - private static bool IsAnotherCopyRunning() - { - var currentId = Process.GetCurrentProcess().Id; - - foreach (var process in Process.GetProcesses()) - { - try - { - // Downloads can be renamed (like "Network.Monitor (1)"), so look at what the exe says it is rather than its name. - if (process.Id != currentId && - process.ProcessName.IndexOf("Network", StringComparison.OrdinalIgnoreCase) >= 0 && - process.MainModule?.FileVersionInfo.ProductName == "Network Monitor") - return true; - } - catch - { - // Processes we can't inspect, like elevated ones, aren't ours. - } - finally - { - process.Dispose(); - } - } - - return false; - } } diff --git a/Network Monitor/UserConfigImport.cs b/Network Monitor/UserConfigImport.cs deleted file mode 100644 index 9302b1c..0000000 --- a/Network Monitor/UserConfigImport.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Xml.Linq; - -namespace Network_Monitor; - -/// -/// Brings in another copy's settings the first time a copy of the app runs. -/// Windows keeps settings per exe path, so a portable download saved under a new name or in a new folder, or switching between the installer and the portable exe, would otherwise start from scratch. -/// -public static class UserConfigImport -{ - private const string FileName = "user.config"; - private const string SectionName = "Network_Monitor.Properties.Settings"; - - /// - /// Copies the most recently saved settings of another copy into when this copy has never saved settings in any version. - /// The other copies' files are only read. - /// - /// Where this copy keeps its settings for the current version. - /// Whether to bring the window position along; leaving it out keeps a new copy from opening exactly on top of one that's still running. - /// The file that was imported, or null if nothing was. - public static string ImportIfNewCopy(string userConfigPath, bool includePlacement) - { - var versionFolder = Path.GetDirectoryName(userConfigPath); - var copyFolder = Path.GetDirectoryName(versionFolder); - var settingsRoot = Path.GetDirectoryName(copyFolder); - - // A settings file for any version means this copy has run before, and in-place updates keep going through Upgrade(). - if (Directory.Exists(copyFolder) && Directory.EnumerateFiles(copyFolder, FileName, SearchOption.AllDirectories).Any()) - return null; - - var source = FindNewestReadable(settingsRoot, copyFolder); - - if (source is null) - return null; - - var document = XDocument.Load(source); - EnsureSectionDeclared(document); - - if (!includePlacement) - GetSettings(document).Where(x => (string)x.Attribute("name") == "Placement").Remove(); - - // Written next to the destination and then moved into place, so a crash halfway through can't leave a half-written settings file. - Directory.CreateDirectory(versionFolder); - var tempPath = userConfigPath + ".import"; - document.Save(tempPath); - File.Move(tempPath, userConfigPath); - - return source; - } - - /// - /// Returns the most recently written settings file under that can be read, skipping anything in . - /// - public static string FindNewestReadable(string settingsRoot, string excludedFolder) - { - if (!Directory.Exists(settingsRoot)) - return null; - - var excludedPrefix = excludedFolder.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; - - return new DirectoryInfo(settingsRoot) - .EnumerateFiles(FileName, SearchOption.AllDirectories) - .Where(x => !x.FullName.StartsWith(excludedPrefix, StringComparison.OrdinalIgnoreCase)) - .Where(x => x.Length > 0 && IsReadable(x.FullName)) - .OrderByDescending(x => x.LastWriteTimeUtc) - .FirstOrDefault()?.FullName; - } - - private static bool IsReadable(string path) - { - try - { - return GetSettings(XDocument.Load(path)).Any(); - } - catch - { - // A file cut short by a power loss isn't worth bringing along. - return false; - } - } - - private static IEnumerable GetSettings(XDocument document) => - document.Root?.Element("userSettings")?.Element(SectionName)?.Elements("setting") ?? Enumerable.Empty(); - - /// - /// Adds the declaration of the settings section if the file doesn't have one. - /// Files written by a build that came with its .exe.config, such as a debug build, leave it out, and the published exe can't load them without it. - /// - private static void EnsureSectionDeclared(XDocument document) - { - var configSections = document.Root.Element("configSections"); - - if (configSections is null) - { - configSections = new XElement("configSections"); - document.Root.AddFirst(configSections); - } - - var group = configSections.Elements("sectionGroup").FirstOrDefault(x => (string)x.Attribute("name") == "userSettings"); - - if (group is null) - { - group = new XElement("sectionGroup", - new XAttribute("name", "userSettings"), - new XAttribute("type", "System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); - configSections.Add(group); - } - - if (group.Elements("section").Any(x => (string)x.Attribute("name") == SectionName)) - return; - - group.Add(new XElement("section", - new XAttribute("name", SectionName), - new XAttribute("type", "System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"), - new XAttribute("allowExeDefinition", "MachineToLocalUser"), - new XAttribute("requirePermission", "false"))); - } -}