diff --git a/PortProxyGUI/About.Designer.cs b/PortProxyGUI/About.Designer.cs index 6454db6..7970ee2 100644 --- a/PortProxyGUI/About.Designer.cs +++ b/PortProxyGUI/About.Designer.cs @@ -1,85 +1,84 @@ -namespace PortProxyGUI +namespace PortProxyGUI; + +partial class About { - partial class About + /// <summary> + /// Required designer variable. + /// </summary> + private System.ComponentModel.IContainer components = null; + + /// <summary> + /// Clean up any resources being used. + /// </summary> + /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> + protected override void Dispose(bool disposing) { - /// <summary> - /// Required designer variable. - /// </summary> - private System.ComponentModel.IContainer components = null; - - /// <summary> - /// Clean up any resources being used. - /// </summary> - /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> - protected override void Dispose(bool disposing) + if (disposing && (components != null)) { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); + components.Dispose(); } - - #region Windows Form Designer generated code - - /// <summary> - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// </summary> - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(About)); - this.linkLabel1 = new System.Windows.Forms.LinkLabel(); - this.label1 = new System.Windows.Forms.Label(); - this.label_version = new System.Windows.Forms.Label(); - this.label_Star = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // linkLabel1 - // - resources.ApplyResources(this.linkLabel1, "linkLabel1"); - this.linkLabel1.Name = "linkLabel1"; - this.linkLabel1.TabStop = true; - this.linkLabel1.Click += new System.EventHandler(this.linkLabel1_Click); - // - // label1 - // - resources.ApplyResources(this.label1, "label1"); - this.label1.Name = "label1"; - // - // label_version - // - resources.ApplyResources(this.label_version, "label_version"); - this.label_version.Name = "label_version"; - // - // label_Star - // - resources.ApplyResources(this.label_Star, "label_Star"); - this.label_Star.Name = "label_Star"; - // - // About - // - resources.ApplyResources(this, "$this"); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Controls.Add(this.label_Star); - this.Controls.Add(this.label_version); - this.Controls.Add(this.label1); - this.Controls.Add(this.linkLabel1); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "About"; - this.TopMost = true; - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.About_FormClosing); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.LinkLabel linkLabel1; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label label_version; - private System.Windows.Forms.Label label_Star; + base.Dispose(disposing); } + + #region Windows Form Designer generated code + + /// <summary> + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// </summary> + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(About)); + this.linkLabel1 = new System.Windows.Forms.LinkLabel(); + this.label1 = new System.Windows.Forms.Label(); + this.label_version = new System.Windows.Forms.Label(); + this.label_Star = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // linkLabel1 + // + resources.ApplyResources(this.linkLabel1, "linkLabel1"); + this.linkLabel1.Name = "linkLabel1"; + this.linkLabel1.TabStop = true; + this.linkLabel1.Click += new System.EventHandler(this.linkLabel1_Click); + // + // label1 + // + resources.ApplyResources(this.label1, "label1"); + this.label1.Name = "label1"; + // + // label_version + // + resources.ApplyResources(this.label_version, "label_version"); + this.label_version.Name = "label_version"; + // + // label_Star + // + resources.ApplyResources(this.label_Star, "label_Star"); + this.label_Star.Name = "label_Star"; + // + // About + // + resources.ApplyResources(this, "$this"); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.label_Star); + this.Controls.Add(this.label_version); + this.Controls.Add(this.label1); + this.Controls.Add(this.linkLabel1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "About"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.About_FormClosing); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.LinkLabel linkLabel1; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label_version; + private System.Windows.Forms.Label label_Star; } \ No newline at end of file diff --git a/PortProxyGUI/About.cs b/PortProxyGUI/About.cs index 77a0f35..670e988 100644 --- a/PortProxyGUI/About.cs +++ b/PortProxyGUI/About.cs @@ -2,31 +2,30 @@ using System.Diagnostics; using System.Windows.Forms; -namespace PortProxyGUI +namespace PortProxyGUI; + +public partial class About : Form { - public partial class About : Form + public readonly PortProxyGUI PortProxyGUI; + + public About(PortProxyGUI portProxyGUI) { - public readonly PortProxyGUI PortProxyGUI; + PortProxyGUI = portProxyGUI; - public About(PortProxyGUI portProxyGUI) + InitializeComponent(); + label_version.Text = label_version.Text + " v" + Application.ProductVersion; + } + + private void linkLabel1_Click(object sender, EventArgs e) + { + if (sender is LinkLabel _sender) { - PortProxyGUI = portProxyGUI; - - InitializeComponent(); - label_version.Text = label_version.Text + " v" + Application.ProductVersion; - } - - private void linkLabel1_Click(object sender, EventArgs e) - { - if (sender is LinkLabel _sender) - { - Process.Start("explorer", _sender.Text); - } - } - - private void About_FormClosing(object sender, FormClosingEventArgs e) - { - PortProxyGUI.AboutForm = null; + Process.Start("explorer", _sender.Text); } } + + private void About_FormClosing(object sender, FormClosingEventArgs e) + { + PortProxyGUI.AboutForm = null; + } } diff --git a/PortProxyGUI/Data/AppConfig.cs b/PortProxyGUI/Data/AppConfig.cs index 7beae1b..a2c31f7 100644 --- a/PortProxyGUI/Data/AppConfig.cs +++ b/PortProxyGUI/Data/AppConfig.cs @@ -3,51 +3,50 @@ using System.Drawing; using System.Linq; using System.Text.RegularExpressions; -namespace PortProxyGUI.Data +namespace PortProxyGUI.Data; + +public class AppConfig { - public class AppConfig + public Size MainWindowSize = new(720, 500); + public int[] PortProxyColumnWidths = [24, 64, 140, 100, 140, 100, 100]; + + private readonly Regex _intArrayRegex = new(@"^\[\s*(\d+)(?:\s*,\s*(\d+))*\s*\]$"); + + public AppConfig() { } + public AppConfig(Config[] rows) { - public Size MainWindowSize = new(720, 500); - public int[] PortProxyColumnWidths = new int[] { 24, 64, 140, 100, 140, 100, 100 }; - - private readonly Regex _intArrayRegex = new(@"^\[\s*(\d+)(?:\s*,\s*(\d+))*\s*\]$"); - - public AppConfig() { } - public AppConfig(Config[] rows) { + var item = rows.Where(x => x.Item == "MainWindow"); + if (int.TryParse(item.FirstOrDefault(x => x.Key == "Width")?.Value, out var width) + && int.TryParse(item.FirstOrDefault(x => x.Key == "Height")?.Value, out var height)) { - var item = rows.Where(x => x.Item == "MainWindow"); - if (int.TryParse(item.FirstOrDefault(x => x.Key == "Width")?.Value, out var width) - && int.TryParse(item.FirstOrDefault(x => x.Key == "Height")?.Value, out var height)) - { - MainWindowSize = new Size(width, height); - } - else MainWindowSize = new Size(720, 500); - } - - { - var item = rows.Where(x => x.Item == "PortProxy"); - var s_ColumnWidths = item.FirstOrDefault(x => x.Key == "ColumnWidths").Value; - var match = _intArrayRegex.Match(s_ColumnWidths); - - if (match.Success) - { - PortProxyColumnWidths = match.Groups - .OfType<Group>().Skip(1) - .SelectMany(x => x.Captures.OfType<Capture>()) - .Select(x => int.Parse(x.Value)) - .ToArray(); - } - else - { -#if NETCOREAPP3_0_OR_GREATER - PortProxyColumnWidths = Array.Empty<int>(); -#else - PortProxyColumnWidths = new int[0]; -#endif - } + MainWindowSize = new Size(width, height); } + else MainWindowSize = new Size(720, 500); } + { + var item = rows.Where(x => x.Item == "PortProxy"); + var s_ColumnWidths = item.FirstOrDefault(x => x.Key == "ColumnWidths").Value; + var match = _intArrayRegex.Match(s_ColumnWidths); + + if (match.Success) + { + PortProxyColumnWidths = match.Groups + .OfType<Group>().Skip(1) + .SelectMany(x => x.Captures.OfType<Capture>()) + .Select(x => int.Parse(x.Value)) + .ToArray(); + } + else + { +#if NETCOREAPP3_0_OR_GREATER + PortProxyColumnWidths = Array.Empty<int>(); +#else + PortProxyColumnWidths = []; +#endif + } + } } + } diff --git a/PortProxyGUI/Data/ApplicationDbScope.cs b/PortProxyGUI/Data/ApplicationDbScope.cs index 782abeb..67a834b 100644 --- a/PortProxyGUI/Data/ApplicationDbScope.cs +++ b/PortProxyGUI/Data/ApplicationDbScope.cs @@ -5,109 +5,108 @@ using System.Collections.Generic; using System.IO; using System.Linq; -namespace PortProxyGUI.Data +namespace PortProxyGUI.Data; + +public class ApplicationDbScope : SqliteScope<ApplicationDbScope> { - public class ApplicationDbScope : SqliteScope<ApplicationDbScope> + public static readonly string AppDbDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "PortProxyGUI"); + public static readonly string AppDbFile = Path.Combine(AppDbDirectory, "config.db"); + + public static ApplicationDbScope FromFile(string file) { - public static readonly string AppDbDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "PortProxyGUI"); - public static readonly string AppDbFile = Path.Combine(AppDbDirectory, "config.db"); + var dir = Path.GetDirectoryName(file); - public static ApplicationDbScope FromFile(string file) + if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); + if (!File.Exists(file)) { - var dir = Path.GetDirectoryName(file); - - if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); - if (!File.Exists(file)) - { #if NETCOREAPP3_0_OR_GREATER #else - System.Data.SQLite.SQLiteConnection.CreateFile(file); + System.Data.SQLite.SQLiteConnection.CreateFile(file); #endif - } - - var scope = new ApplicationDbScope($"Data Source=\"{file}\""); - scope.Migrate(); - return scope; - } - - public ApplicationDbScope(string connectionString) : base(connectionString) - { - } - - public override void Initialize() - { - } - - public void Migrate() => new MigrationUtil(this).MigrateToLast(); - - public Migration GetLastMigration() - { - return SqlQuery<Migration>($"SELECT * FROM __history ORDER BY MigrationId DESC LIMIT 1;").First(); - } - - public IEnumerable<Rule> Rules => SqlQuery<Rule>($"SELECT * FROM Rules;"); - - public Rule GetRule(string type, string listenOn, int listenPort) - { - return SqlQuery<Rule>($"SELECT * FROM Rules WHERE Type={type} AND ListenOn={listenOn} AND ListenPort={listenPort} LIMIT 1;").FirstOrDefault(); - } - - public void Add<T>(T obj) where T : class - { - var newid = Guid.NewGuid().ToString(); - if (obj is Rule rule) - { - Sql($"INSERT INTO Rules (Id, Type, ListenOn, ListenPort, ConnectTo, ConnectPort, Comment, `Group`) VALUES ({newid}, {rule.Type}, {rule.ListenOn}, {rule.ListenPort}, {rule.ConnectTo}, {rule.ConnectPort}, {rule.Comment ?? ""}, {rule.Group ?? ""});"); - rule.Id = newid; - } - else throw new NotSupportedException($"Adding {obj.GetType().FullName} is not supported."); - } - public void AddRange<T>(IEnumerable<T> objs) where T : class - { - foreach (var obj in objs) Add(obj); - } - - public void Update<T>(T obj) where T : class - { - if (obj is Rule rule) - { - Sql($"UPDATE Rules SET Type={rule.Type}, ListenOn={rule.ListenOn}, ListenPort={rule.ListenPort}, ConnectTo={rule.ConnectTo}, ConnectPort={rule.ConnectPort} WHERE Id={rule.Id};"); - } - else throw new NotSupportedException($"Updating {obj.GetType().FullName} is not supported."); - } - public void UpdateRange<T>(IEnumerable<T> objs) where T : class - { - foreach (var obj in objs) Update(obj); - } - - public void Remove<T>(T obj) where T : class - { - if (obj is Rule rule) - { - Sql($"DELETE FROM Rules WHERE Id={rule.Id};"); - } - else throw new NotSupportedException($"Removing {obj.GetType().FullName} is not supported."); - } - public void RemoveRange<T>(IEnumerable<T> objs) where T : class - { - foreach (var obj in objs) Remove(obj); - } - - public AppConfig GetAppConfig() - { - var configRows = SqlQuery<Config>($"SELECT * FROM Configs;"); - var appConfig = new AppConfig(configRows); - return appConfig; - } - - public void SaveAppConfig(AppConfig appConfig) - { - Sql($"UPDATE Configs SET Value = {appConfig.MainWindowSize.Width} WHERE Item = 'MainWindow' AND `Key` = 'Width';"); - Sql($"UPDATE Configs SET Value = {appConfig.MainWindowSize.Height} WHERE Item = 'MainWindow' AND `Key` = 'Height';"); - - var s_portProxyColumnWidths = $"[{appConfig.PortProxyColumnWidths.Select(x => x.ToString()).Join(", ")}]"; - Sql($"UPDATE Configs SET Value = {s_portProxyColumnWidths} WHERE Item = 'PortProxy' AND `Key` = 'ColumnWidths';"); } + var scope = new ApplicationDbScope($"Data Source=\"{file}\""); + scope.Migrate(); + return scope; } + + public ApplicationDbScope(string connectionString) : base(connectionString) + { + } + + public override void Initialize() + { + } + + public void Migrate() => new MigrationUtil(this).MigrateToLast(); + + public Migration GetLastMigration() + { + return SqlQuery<Migration>($"SELECT * FROM __history ORDER BY MigrationId DESC LIMIT 1;").First(); + } + + public IEnumerable<Rule> Rules => SqlQuery<Rule>($"SELECT * FROM Rules;"); + + public Rule GetRule(string type, string listenOn, int listenPort) + { + return SqlQuery<Rule>($"SELECT * FROM Rules WHERE Type={type} AND ListenOn={listenOn} AND ListenPort={listenPort} LIMIT 1;").FirstOrDefault(); + } + + public void Add<T>(T obj) where T : class + { + var newid = Guid.NewGuid().ToString(); + if (obj is Rule rule) + { + Sql($"INSERT INTO Rules (Id, Type, ListenOn, ListenPort, ConnectTo, ConnectPort, Comment, `Group`) VALUES ({newid}, {rule.Type}, {rule.ListenOn}, {rule.ListenPort}, {rule.ConnectTo}, {rule.ConnectPort}, {rule.Comment ?? ""}, {rule.Group ?? ""});"); + rule.Id = newid; + } + else throw new NotSupportedException($"Adding {obj.GetType().FullName} is not supported."); + } + public void AddRange<T>(IEnumerable<T> objs) where T : class + { + foreach (var obj in objs) Add(obj); + } + + public void Update<T>(T obj) where T : class + { + if (obj is Rule rule) + { + Sql($"UPDATE Rules SET Type={rule.Type}, ListenOn={rule.ListenOn}, ListenPort={rule.ListenPort}, ConnectTo={rule.ConnectTo}, ConnectPort={rule.ConnectPort} WHERE Id={rule.Id};"); + } + else throw new NotSupportedException($"Updating {obj.GetType().FullName} is not supported."); + } + public void UpdateRange<T>(IEnumerable<T> objs) where T : class + { + foreach (var obj in objs) Update(obj); + } + + public void Remove<T>(T obj) where T : class + { + if (obj is Rule rule) + { + Sql($"DELETE FROM Rules WHERE Id={rule.Id};"); + } + else throw new NotSupportedException($"Removing {obj.GetType().FullName} is not supported."); + } + public void RemoveRange<T>(IEnumerable<T> objs) where T : class + { + foreach (var obj in objs) Remove(obj); + } + + public AppConfig GetAppConfig() + { + var configRows = SqlQuery<Config>($"SELECT * FROM Configs;"); + var appConfig = new AppConfig(configRows); + return appConfig; + } + + public void SaveAppConfig(AppConfig appConfig) + { + Sql($"UPDATE Configs SET Value = {appConfig.MainWindowSize.Width} WHERE Item = 'MainWindow' AND `Key` = 'Width';"); + Sql($"UPDATE Configs SET Value = {appConfig.MainWindowSize.Height} WHERE Item = 'MainWindow' AND `Key` = 'Height';"); + + var s_portProxyColumnWidths = $"[{appConfig.PortProxyColumnWidths.Select(x => x.ToString()).Join(", ")}]"; + Sql($"UPDATE Configs SET Value = {s_portProxyColumnWidths} WHERE Item = 'PortProxy' AND `Key` = 'ColumnWidths';"); + } + } diff --git a/PortProxyGUI/Data/Config.cs b/PortProxyGUI/Data/Config.cs index c8bb6d8..6bc5400 100644 --- a/PortProxyGUI/Data/Config.cs +++ b/PortProxyGUI/Data/Config.cs @@ -1,9 +1,8 @@ -namespace PortProxyGUI.Data +namespace PortProxyGUI.Data; + +public class Config { - public class Config - { - public string Item { get; set; } - public string Key { get; set; } - public string Value { get; set; } - } + public string Item { get; set; } + public string Key { get; set; } + public string Value { get; set; } } diff --git a/PortProxyGUI/Data/Migration.cs b/PortProxyGUI/Data/Migration.cs index 7c48285..3a8c9ce 100644 --- a/PortProxyGUI/Data/Migration.cs +++ b/PortProxyGUI/Data/Migration.cs @@ -1,8 +1,7 @@ -namespace PortProxyGUI.Data +namespace PortProxyGUI.Data; + +public class Migration { - public class Migration - { - public string MigrationId { get; set; } - public string ProductVersion { get; set; } - } + public string MigrationId { get; set; } + public string ProductVersion { get; set; } } diff --git a/PortProxyGUI/Data/MigrationKey.cs b/PortProxyGUI/Data/MigrationKey.cs index fc217ef..86f469f 100644 --- a/PortProxyGUI/Data/MigrationKey.cs +++ b/PortProxyGUI/Data/MigrationKey.cs @@ -1,8 +1,7 @@ -namespace PortProxyGUI.Data +namespace PortProxyGUI.Data; + +public struct MigrationKey { - public struct MigrationKey - { - public string MigrationId { get; set; } - public string ProductVersion { get; set; } - } + public string MigrationId { get; set; } + public string ProductVersion { get; set; } } diff --git a/PortProxyGUI/Data/MigrationUtil.cs b/PortProxyGUI/Data/MigrationUtil.cs index 3dec1e0..26505cd 100644 --- a/PortProxyGUI/Data/MigrationUtil.cs +++ b/PortProxyGUI/Data/MigrationUtil.cs @@ -5,71 +5,71 @@ using System.Linq; using System.Reflection; using System.Windows.Forms; -namespace PortProxyGUI.Data +namespace PortProxyGUI.Data; + +public class MigrationUtil { - public class MigrationUtil + public ApplicationDbScope DbScope { get; private set; } + + public MigrationUtil(ApplicationDbScope context) { - public ApplicationDbScope DbScope { get; private set; } + DbScope = context; + EnsureHistoryTable(); + EnsureUpdateVersion(); + } - public MigrationUtil(ApplicationDbScope context) + public void EnsureHistoryTable() + { + if (!DbScope.SqlQuery($"SELECT * FROM sqlite_master WHERE type = 'table' AND name = '__history';").Any()) { - DbScope = context; - EnsureHistoryTable(); - EnsureUpdateVersion(); + DbScope.UnsafeSql(@"CREATE TABLE __history ( MigrationId text PRIMARY KEY, ProductVersion text);"); + DbScope.UnsafeSql($"INSERT INTO __history (MigrationId, ProductVersion) VALUES ('000000000000', '0.0');"); } + } - public void EnsureHistoryTable() + public void EnsureUpdateVersion() + { + var migration = DbScope.GetLastMigration(); + var assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version; + + if (new Version(migration.ProductVersion) > assemblyVersion) { - if (!DbScope.SqlQuery($"SELECT * FROM sqlite_master WHERE type = 'table' AND name = '__history';").Any()) - { - DbScope.UnsafeSql(@"CREATE TABLE __history ( MigrationId text PRIMARY KEY, ProductVersion text);"); - DbScope.UnsafeSql($"INSERT INTO __history (MigrationId, ProductVersion) VALUES ('000000000000', '0.0');"); - } - } - - public void EnsureUpdateVersion() - { - var migration = DbScope.GetLastMigration(); - var assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version; - - if (new Version(migration.ProductVersion) > assemblyVersion) - { - if (MessageBox.Show(@"The current software version cannot use the configuration. + if (MessageBox.Show(@"The current software version cannot use the configuration. You need to use a newer version of PortProxyGUI. Would you like to download it now?", "Upgrade", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) - { - Process.Start("explorer.exe", "https://github.com/zmjack/PortProxyGUI/releases"); - } - - Environment.Exit(0); - } - } - - public void MigrateToLast() - { - var migration = DbScope.GetLastMigration(); - var migrationId = migration.MigrationId; - var pendingMigrations = migrationId != "000000000000" - ? History.SkipWhile(pair => pair.Key.MigrationId != migrationId).Skip(1) - : History; - - foreach (var pendingMigration in pendingMigrations) { - foreach (var sql in pendingMigration.Value) - { - DbScope.UnsafeSql(sql); - } - DbScope.Sql($"INSERT INTO __history (MigrationId, ProductVersion) VALUES ({pendingMigration.Key.MigrationId}, {pendingMigration.Key.ProductVersion});"); + Process.Start("explorer.exe", "https://github.com/zmjack/PortProxyGUI/releases"); } - } - public Dictionary<MigrationKey, string[]> History = new Dictionary<MigrationKey, string[]> + Environment.Exit(0); + } + } + + public void MigrateToLast() + { + var migration = DbScope.GetLastMigration(); + var migrationId = migration.MigrationId; + var pendingMigrations = migrationId != "000000000000" + ? History.SkipWhile(pair => pair.Key.MigrationId != migrationId).Skip(1) + : History; + + foreach (var pendingMigration in pendingMigrations) { - [new MigrationKey { MigrationId = "202103021542", ProductVersion = "1.1.0" }] = new[] + foreach (var sql in pendingMigration.Value) { - @"CREATE TABLE rules + DbScope.UnsafeSql(sql); + } + DbScope.Sql($"INSERT INTO __history (MigrationId, ProductVersion) VALUES ({pendingMigration.Key.MigrationId}, {pendingMigration.Key.ProductVersion});"); + } + } + + public Dictionary<MigrationKey, string[]> History = new Dictionary<MigrationKey, string[]> + { + [new MigrationKey { MigrationId = "202103021542", ProductVersion = "1.1.0" }] = + [ + @"CREATE TABLE rules ( Id text PRIMARY KEY, Type text, @@ -78,21 +78,21 @@ Would you like to download it now?", "Upgrade", MessageBoxButtons.YesNo, Message ConnectTo text, ConnectPort integer );", - "CREATE UNIQUE INDEX IX_Rules_Type_ListenOn_ListenPort ON Rules(Type, ListenOn, ListenPort);", - }, + "CREATE UNIQUE INDEX IX_Rules_Type_ListenOn_ListenPort ON Rules(Type, ListenOn, ListenPort);", + ], - [new MigrationKey { MigrationId = "202201172103", ProductVersion = "1.2.0" }] = new[] - { - "ALTER TABLE rules ADD Note text;", - "ALTER TABLE rules ADD `Group` text;", - }, + [new MigrationKey { MigrationId = "202201172103", ProductVersion = "1.2.0" }] = + [ + "ALTER TABLE rules ADD Note text;", + "ALTER TABLE rules ADD `Group` text;", + ], - [new MigrationKey { MigrationId = "202202221635", ProductVersion = "1.3.0" }] = new[] - { - "ALTER TABLE rules RENAME TO rulesOld;", - "DROP INDEX IX_Rules_Type_ListenOn_ListenPort;", + [new MigrationKey { MigrationId = "202202221635", ProductVersion = "1.3.0" }] = + [ + "ALTER TABLE rules RENAME TO rulesOld;", + "DROP INDEX IX_Rules_Type_ListenOn_ListenPort;", - @"CREATE TABLE rules ( + @"CREATE TABLE rules ( Id text PRIMARY KEY, Type text, ListenOn text, @@ -102,15 +102,15 @@ Would you like to download it now?", "Upgrade", MessageBoxButtons.YesNo, Message Comment text, `Group` text );", - "CREATE UNIQUE INDEX IX_Rules_Type_ListenOn_ListenPort ON Rules ( Type, ListenOn, ListenPort );", + "CREATE UNIQUE INDEX IX_Rules_Type_ListenOn_ListenPort ON Rules ( Type, ListenOn, ListenPort );", - "INSERT INTO rules SELECT Id, Type, ListenOn, ListenPort, ConnectTo, ConnectPort, Note, `Group` FROM rulesOld;", - "DROP TABLE rulesOld;", - }, + "INSERT INTO rules SELECT Id, Type, ListenOn, ListenPort, ConnectTo, ConnectPort, Note, `Group` FROM rulesOld;", + "DROP TABLE rulesOld;", + ], - [new MigrationKey { MigrationId = "202303092024", ProductVersion = "1.4.0" }] = new[] - { - @"CREATE TABLE configs ( + [new MigrationKey { MigrationId = "202303092024", ProductVersion = "1.4.0" }] = + [ + @"CREATE TABLE configs ( Item text, `Key` text, Value text @@ -121,7 +121,6 @@ Would you like to download it now?", "Upgrade", MessageBoxButtons.YesNo, Message "INSERT INTO configs ( Item, `Key`, Value ) VALUES ( 'MainWindow', 'Width', '720' );", "INSERT INTO configs ( Item, `Key`, Value ) VALUES ( 'MainWindow', 'Height', '500' );", "INSERT INTO configs ( Item, `Key`, Value ) VALUES ( 'PortProxy', 'ColumnWidths', '[24, 64, 140, 100, 140, 100, 100]' );", - }, - }; - } + ], + }; } diff --git a/PortProxyGUI/Data/Rule.cs b/PortProxyGUI/Data/Rule.cs index 55a62d1..31e166e 100644 --- a/PortProxyGUI/Data/Rule.cs +++ b/PortProxyGUI/Data/Rule.cs @@ -1,74 +1,73 @@ using System; -namespace PortProxyGUI.Data +namespace PortProxyGUI.Data; + +public class Rule : IEquatable<Rule> { - public class Rule : IEquatable<Rule> + public string Id { get; set; } + + public string Type { get; set; } + public string ListenOn { get; set; } + public int ListenPort { get; set; } + public string ConnectTo { get; set; } + public int ConnectPort { get; set; } + public string Comment { get; set; } + public string Group { get; set; } + + public bool Valid => ListenPort > 0 && ConnectPort > 0; + + private string _realListenPort; + /// <summary> + /// Not mapped + /// </summary> + public string RealListenPort { - public string Id { get; set; } + get => ListenPort > 0 ? ListenPort.ToString() : _realListenPort; + set => _realListenPort = value; + } - public string Type { get; set; } - public string ListenOn { get; set; } - public int ListenPort { get; set; } - public string ConnectTo { get; set; } - public int ConnectPort { get; set; } - public string Comment { get; set; } - public string Group { get; set; } + private string _realConnectPort; + /// <summary> + /// Not mapped + /// </summary> + public string RealConnectPort + { + get => ConnectPort > 0 ? ConnectPort.ToString() : _realConnectPort; + set => _realConnectPort = value; + } - public bool Valid => ListenPort > 0 && ConnectPort > 0; + public override int GetHashCode() + { + return base.GetHashCode(); + } - private string _realListenPort; - /// <summary> - /// Not mapped - /// </summary> - public string RealListenPort - { - get => ListenPort > 0 ? ListenPort.ToString() : _realListenPort; - set => _realListenPort = value; - } + public bool Equals(Rule other) + { + return Id == other.Id + && Type == other.Type + && ListenOn == other.ListenOn + && ListenPort == other.ListenPort + && ConnectTo == other.ConnectTo + && ConnectPort == other.ConnectPort + && Comment == other.Comment + && Group == other.Group; + } - private string _realConnectPort; - /// <summary> - /// Not mapped - /// </summary> - public string RealConnectPort - { - get => ConnectPort > 0 ? ConnectPort.ToString() : _realConnectPort; - set => _realConnectPort = value; - } + public bool EqualsWithKeys(Rule other) + { + return Type == other.Type + && ListenOn == other.ListenOn + && ListenPort == other.ListenPort; + } - public override int GetHashCode() - { - return base.GetHashCode(); - } + public static int ParsePort(string portString) + { + if (int.TryParse(portString, out var port) && 0 < port && port < 65536) return port; + else throw new NotSupportedException($"Invalid port string. ({portString})"); + } - public bool Equals(Rule other) - { - return Id == other.Id - && Type == other.Type - && ListenOn == other.ListenOn - && ListenPort == other.ListenPort - && ConnectTo == other.ConnectTo - && ConnectPort == other.ConnectPort - && Comment == other.Comment - && Group == other.Group; - } - - public bool EqualsWithKeys(Rule other) - { - return Type == other.Type - && ListenOn == other.ListenOn - && ListenPort == other.ListenPort; - } - - public static int ParsePort(string portString) - { - if (int.TryParse(portString, out var port) && 0 < port && port < 65536) return port; - else throw new NotSupportedException($"Invalid port string. ({portString})"); - } - - public override bool Equals(object obj) - { - return Equals(obj as Rule); - } + public override bool Equals(object obj) + { + return Equals(obj as Rule); } } diff --git a/PortProxyGUI/Native/GenericRights.cs b/PortProxyGUI/Native/GenericRights.cs index 233acf6..1697aef 100644 --- a/PortProxyGUI/Native/GenericRights.cs +++ b/PortProxyGUI/Native/GenericRights.cs @@ -1,13 +1,12 @@ using System; -namespace PortProxyGUI.Native +namespace PortProxyGUI.Native; + +[Flags] +internal enum GenericRights : uint { - [Flags] - internal enum GenericRights : uint - { - GENERIC_READ = 0x80000000, - GENERIC_WRITE = 0x40000000, - GENERIC_EXECUTE = 0x20000000, - GENERIC_ALL = 0x10000000, - } + GENERIC_READ = 0x80000000, + GENERIC_WRITE = 0x40000000, + GENERIC_EXECUTE = 0x20000000, + GENERIC_ALL = 0x10000000, } diff --git a/PortProxyGUI/Native/NativeMethods.cs b/PortProxyGUI/Native/NativeMethods.cs index bd1d6fd..c6a0cf1 100644 --- a/PortProxyGUI/Native/NativeMethods.cs +++ b/PortProxyGUI/Native/NativeMethods.cs @@ -1,33 +1,32 @@ using System; using System.Runtime.InteropServices; -namespace PortProxyGUI.Native +namespace PortProxyGUI.Native; + +internal class NativeMethods { - internal class NativeMethods - { - [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern IntPtr OpenSCManager(string machineName, string databaseName, uint dwAccess); + [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern IntPtr OpenSCManager(string machineName, string databaseName, uint dwAccess); - [DllImport("advapi32.dll", EntryPoint = "OpenServiceW", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess); + [DllImport("advapi32.dll", EntryPoint = "OpenServiceW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess); - [DllImport("advapi32.dll", EntryPoint = "QueryServiceStatus", CharSet = CharSet.Auto)] - internal static extern bool QueryServiceStatus(IntPtr hService, ref ServiceStatus dwServiceStatus); + [DllImport("advapi32.dll", EntryPoint = "QueryServiceStatus", CharSet = CharSet.Auto)] + internal static extern bool QueryServiceStatus(IntPtr hService, ref ServiceStatus dwServiceStatus); - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool ControlService(IntPtr hService, ServiceControls dwControl, ref ServiceStatus lpServiceStatus); + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ControlService(IntPtr hService, ServiceControls dwControl, ref ServiceStatus lpServiceStatus); - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CloseServiceHandle(IntPtr hSCObject); + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CloseServiceHandle(IntPtr hSCObject); - [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache")] - internal static extern uint DnsFlushResolverCache(); + [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCache")] + internal static extern uint DnsFlushResolverCache(); - [DllImport("advapi32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool StartService(IntPtr hService, int dwNumServiceArgs, string[] lpServiceArgVectors); + [DllImport("advapi32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool StartService(IntPtr hService, int dwNumServiceArgs, string[] lpServiceArgVectors); - } } diff --git a/PortProxyGUI/Native/ScmRights.cs b/PortProxyGUI/Native/ScmRights.cs index 6a21bc6..77520a7 100644 --- a/PortProxyGUI/Native/ScmRights.cs +++ b/PortProxyGUI/Native/ScmRights.cs @@ -1,21 +1,20 @@ -namespace PortProxyGUI.Native -{ - internal enum ScmRights : uint - { - SC_MANAGER_CONNECT = 0x0001, - SC_MANAGER_CREATE_SERVICE = 0x0002, - SC_MANAGER_ENUMERATE_SERVICE = 0x0004, - SC_MANAGER_LOCK = 0x0008, - SC_MANAGER_QUERY_LOCK_STATUS = 0x0010, - SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020, +namespace PortProxyGUI.Native; - SC_MANAGER_ALL_ACCESS = - StandardRights.STANDARD_RIGHTS_REQUIRED - | SC_MANAGER_CONNECT - | SC_MANAGER_CREATE_SERVICE - | SC_MANAGER_ENUMERATE_SERVICE - | SC_MANAGER_LOCK - | SC_MANAGER_QUERY_LOCK_STATUS - | SC_MANAGER_MODIFY_BOOT_CONFIG - } +internal enum ScmRights : uint +{ + SC_MANAGER_CONNECT = 0x0001, + SC_MANAGER_CREATE_SERVICE = 0x0002, + SC_MANAGER_ENUMERATE_SERVICE = 0x0004, + SC_MANAGER_LOCK = 0x0008, + SC_MANAGER_QUERY_LOCK_STATUS = 0x0010, + SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020, + + SC_MANAGER_ALL_ACCESS = + StandardRights.STANDARD_RIGHTS_REQUIRED + | SC_MANAGER_CONNECT + | SC_MANAGER_CREATE_SERVICE + | SC_MANAGER_ENUMERATE_SERVICE + | SC_MANAGER_LOCK + | SC_MANAGER_QUERY_LOCK_STATUS + | SC_MANAGER_MODIFY_BOOT_CONFIG } diff --git a/PortProxyGUI/Native/ServiceControls.cs b/PortProxyGUI/Native/ServiceControls.cs index 05c050d..6fc83a5 100644 --- a/PortProxyGUI/Native/ServiceControls.cs +++ b/PortProxyGUI/Native/ServiceControls.cs @@ -1,10 +1,9 @@ using System; -namespace PortProxyGUI.Native +namespace PortProxyGUI.Native; + +[Flags] +internal enum ServiceControls : uint { - [Flags] - internal enum ServiceControls : uint - { - SERVICE_CONTROL_PARAMCHANGE = 0x00000006, - } + SERVICE_CONTROL_PARAMCHANGE = 0x00000006, } diff --git a/PortProxyGUI/Native/ServiceRights.cs b/PortProxyGUI/Native/ServiceRights.cs index df0b56c..794a7ba 100644 --- a/PortProxyGUI/Native/ServiceRights.cs +++ b/PortProxyGUI/Native/ServiceRights.cs @@ -1,29 +1,28 @@ using System; -namespace PortProxyGUI.Native -{ - [Flags] - internal enum ServiceRights : uint - { - SERVICE_QUERY_CONFIG = 0x0001, - SERVICE_CHANGE_CONFIG = 0x0002, - SERVICE_QUERY_STATUS = 0x0004, - SERVICE_ENUMERATE_DEPENDENTS = 0x0008, - SERVICE_START = 0x0010, - SERVICE_STOP = 0x0020, - SERVICE_PAUSE_CONTINUE = 0x0040, - SERVICE_INTERROGATE = 0x0080, - SERVICE_USER_DEFINED_CONTROL = 0x0100, +namespace PortProxyGUI.Native; - SERVICE_ALL_ACCESS = - SERVICE_QUERY_CONFIG - | SERVICE_CHANGE_CONFIG - | SERVICE_QUERY_STATUS - | SERVICE_ENUMERATE_DEPENDENTS - | SERVICE_START - | SERVICE_STOP - | SERVICE_PAUSE_CONTINUE - | SERVICE_INTERROGATE - | SERVICE_USER_DEFINED_CONTROL - } +[Flags] +internal enum ServiceRights : uint +{ + SERVICE_QUERY_CONFIG = 0x0001, + SERVICE_CHANGE_CONFIG = 0x0002, + SERVICE_QUERY_STATUS = 0x0004, + SERVICE_ENUMERATE_DEPENDENTS = 0x0008, + SERVICE_START = 0x0010, + SERVICE_STOP = 0x0020, + SERVICE_PAUSE_CONTINUE = 0x0040, + SERVICE_INTERROGATE = 0x0080, + SERVICE_USER_DEFINED_CONTROL = 0x0100, + + SERVICE_ALL_ACCESS = + SERVICE_QUERY_CONFIG + | SERVICE_CHANGE_CONFIG + | SERVICE_QUERY_STATUS + | SERVICE_ENUMERATE_DEPENDENTS + | SERVICE_START + | SERVICE_STOP + | SERVICE_PAUSE_CONTINUE + | SERVICE_INTERROGATE + | SERVICE_USER_DEFINED_CONTROL } diff --git a/PortProxyGUI/Native/ServiceState.cs b/PortProxyGUI/Native/ServiceState.cs index a7b0596..a9c4df2 100644 --- a/PortProxyGUI/Native/ServiceState.cs +++ b/PortProxyGUI/Native/ServiceState.cs @@ -1,13 +1,12 @@ -namespace PortProxyGUI.Native +namespace PortProxyGUI.Native; + +internal enum ServiceState : int { - internal enum ServiceState : int - { - SERVICE_STOPPED = 0x00000001, - SERVICE_START_PENDING = 0x00000002, - SERVICE_STOP_PENDING = 0x00000003, - SERVICE_RUNNING = 0x00000004, - SERVICE_CONTINUE_PENDING = 0x00000005, - SERVICE_PAUSE_PENDING = 0x00000006, - SERVICE_PAUSED = 0x00000007, - } + SERVICE_STOPPED = 0x00000001, + SERVICE_START_PENDING = 0x00000002, + SERVICE_STOP_PENDING = 0x00000003, + SERVICE_RUNNING = 0x00000004, + SERVICE_CONTINUE_PENDING = 0x00000005, + SERVICE_PAUSE_PENDING = 0x00000006, + SERVICE_PAUSED = 0x00000007, } diff --git a/PortProxyGUI/Native/ServiceStatus.cs b/PortProxyGUI/Native/ServiceStatus.cs index f4803c1..bb3240d 100644 --- a/PortProxyGUI/Native/ServiceStatus.cs +++ b/PortProxyGUI/Native/ServiceStatus.cs @@ -1,16 +1,15 @@ using System.Runtime.InteropServices; -namespace PortProxyGUI.Native +namespace PortProxyGUI.Native; + +[StructLayout(LayoutKind.Sequential)] +internal struct ServiceStatus { - [StructLayout(LayoutKind.Sequential)] - internal struct ServiceStatus - { - public uint dwServiceType; - public ServiceState dwCurrentState; - public uint dwControlsAccepted; - public uint dwWin32ExitCode; - public uint dwServiceSpecificExitCode; - public uint dwCheckPoint; - public uint dwWaitHint; - } + public uint dwServiceType; + public ServiceState dwCurrentState; + public uint dwControlsAccepted; + public uint dwWin32ExitCode; + public uint dwServiceSpecificExitCode; + public uint dwCheckPoint; + public uint dwWaitHint; } diff --git a/PortProxyGUI/Native/StandardRights.cs b/PortProxyGUI/Native/StandardRights.cs index 9d17948..9803bc7 100644 --- a/PortProxyGUI/Native/StandardRights.cs +++ b/PortProxyGUI/Native/StandardRights.cs @@ -1,7 +1,6 @@ -namespace PortProxyGUI.Native +namespace PortProxyGUI.Native; + +internal enum StandardRights : uint { - internal enum StandardRights : uint - { - STANDARD_RIGHTS_REQUIRED = 0x000F0000, - } + STANDARD_RIGHTS_REQUIRED = 0x000F0000, } diff --git a/PortProxyGUI/PortProxyGUI.Designer.cs b/PortProxyGUI/PortProxyGUI.Designer.cs index b1c18ad..8fef746 100644 --- a/PortProxyGUI/PortProxyGUI.Designer.cs +++ b/PortProxyGUI/PortProxyGUI.Designer.cs @@ -1,301 +1,300 @@ -namespace PortProxyGUI +namespace PortProxyGUI; + +partial class PortProxyGUI { - partial class PortProxyGUI + /// <summary> + /// Required designer variable. + /// </summary> + private System.ComponentModel.IContainer components = null; + + /// <summary> + /// Clean up any resources being used. + /// </summary> + /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> + protected override void Dispose(bool disposing) { - /// <summary> - /// Required designer variable. - /// </summary> - private System.ComponentModel.IContainer components = null; - - /// <summary> - /// Clean up any resources being used. - /// </summary> - /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> - protected override void Dispose(bool disposing) + if (disposing && (components != null)) { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); + components.Dispose(); } - - #region Windows Form Designer generated code - - /// <summary> - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// </summary> - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PortProxyGUI)); - listViewProxies = new System.Windows.Forms.ListView(); - columnHeader1 = new System.Windows.Forms.ColumnHeader(); - columnHeader2 = new System.Windows.Forms.ColumnHeader(); - columnHeader3 = new System.Windows.Forms.ColumnHeader(); - columnHeader4 = new System.Windows.Forms.ColumnHeader(); - columnHeader5 = new System.Windows.Forms.ColumnHeader(); - columnHeader6 = new System.Windows.Forms.ColumnHeader(); - columnHeader7 = new System.Windows.Forms.ColumnHeader(); - contextMenuStrip_RightClick = new System.Windows.Forms.ContextMenuStrip(components); - toolStripMenuItem_Enable = new System.Windows.Forms.ToolStripMenuItem(); - toolStripMenuItem_Disable = new System.Windows.Forms.ToolStripMenuItem(); - toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); - toolStripMenuItem_Refresh = new System.Windows.Forms.ToolStripMenuItem(); - toolStripMenuItem_FlushDnsCache = new System.Windows.Forms.ToolStripMenuItem(); - toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); - toolStripMenuItem_New = new System.Windows.Forms.ToolStripMenuItem(); - toolStripMenuItem_Modify = new System.Windows.Forms.ToolStripMenuItem(); - toolStripMenuItem_Delete = new System.Windows.Forms.ToolStripMenuItem(); - toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); - toolStripMenuItem_More = new System.Windows.Forms.ToolStripMenuItem(); - toolStripMenuItem_Import = new System.Windows.Forms.ToolStripMenuItem(); - toolStripMenuItem_Export = new System.Windows.Forms.ToolStripMenuItem(); - toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); - toolStripMenuItem_ResetWindowSize = new System.Windows.Forms.ToolStripMenuItem(); - toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); - toolStripMenuItem_About = new System.Windows.Forms.ToolStripMenuItem(); - imageListProxies = new System.Windows.Forms.ImageList(components); - saveFileDialog_Export = new System.Windows.Forms.SaveFileDialog(); - openFileDialog_Import = new System.Windows.Forms.OpenFileDialog(); - statusStrip_Footer = new System.Windows.Forms.StatusStrip(); - toolStripStatusLabel_Status = new System.Windows.Forms.ToolStripStatusLabel(); - toolStripStatusLabel_ServiceNotRunning = new System.Windows.Forms.ToolStripStatusLabel(); - contextMenuStrip_RightClick.SuspendLayout(); - statusStrip_Footer.SuspendLayout(); - SuspendLayout(); - // - // listViewProxies - // - listViewProxies.BorderStyle = System.Windows.Forms.BorderStyle.None; - listViewProxies.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnHeader1, columnHeader2, columnHeader3, columnHeader4, columnHeader5, columnHeader6, columnHeader7 }); - listViewProxies.ContextMenuStrip = contextMenuStrip_RightClick; - resources.ApplyResources(listViewProxies, "listViewProxies"); - listViewProxies.FullRowSelect = true; - listViewProxies.Name = "listViewProxies"; - listViewProxies.SmallImageList = imageListProxies; - listViewProxies.UseCompatibleStateImageBehavior = false; - listViewProxies.View = System.Windows.Forms.View.Details; - listViewProxies.ColumnClick += listView1_ColumnClick; - listViewProxies.ColumnWidthChanged += listViewProxies_ColumnWidthChanged; - listViewProxies.DoubleClick += listView1_DoubleClick; - listViewProxies.KeyUp += listViewProxies_KeyUp; - listViewProxies.MouseUp += listView1_MouseUp; - // - // columnHeader1 - // - resources.ApplyResources(columnHeader1, "columnHeader1"); - // - // columnHeader2 - // - resources.ApplyResources(columnHeader2, "columnHeader2"); - // - // columnHeader3 - // - resources.ApplyResources(columnHeader3, "columnHeader3"); - // - // columnHeader4 - // - columnHeader4.Tag = ""; - resources.ApplyResources(columnHeader4, "columnHeader4"); - // - // columnHeader5 - // - resources.ApplyResources(columnHeader5, "columnHeader5"); - // - // columnHeader6 - // - columnHeader6.Tag = ""; - resources.ApplyResources(columnHeader6, "columnHeader6"); - // - // columnHeader7 - // - resources.ApplyResources(columnHeader7, "columnHeader7"); - // - // contextMenuStrip_RightClick - // - contextMenuStrip_RightClick.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripMenuItem_Enable, toolStripMenuItem_Disable, toolStripSeparator3, toolStripMenuItem_Refresh, toolStripMenuItem_FlushDnsCache, toolStripSeparator2, toolStripMenuItem_New, toolStripMenuItem_Modify, toolStripMenuItem_Delete, toolStripSeparator1, toolStripMenuItem_More, toolStripSeparator4, toolStripMenuItem_About }); - contextMenuStrip_RightClick.Name = "contextMenuStrip1"; - resources.ApplyResources(contextMenuStrip_RightClick, "contextMenuStrip_RightClick"); - contextMenuStrip_RightClick.MouseClick += contextMenuStrip_RightClick_MouseClick; - // - // toolStripMenuItem_Enable - // - toolStripMenuItem_Enable.Name = "toolStripMenuItem_Enable"; - resources.ApplyResources(toolStripMenuItem_Enable, "toolStripMenuItem_Enable"); - // - // toolStripMenuItem_Disable - // - toolStripMenuItem_Disable.Name = "toolStripMenuItem_Disable"; - resources.ApplyResources(toolStripMenuItem_Disable, "toolStripMenuItem_Disable"); - // - // toolStripSeparator3 - // - toolStripSeparator3.Name = "toolStripSeparator3"; - resources.ApplyResources(toolStripSeparator3, "toolStripSeparator3"); - // - // toolStripMenuItem_Refresh - // - toolStripMenuItem_Refresh.Name = "toolStripMenuItem_Refresh"; - resources.ApplyResources(toolStripMenuItem_Refresh, "toolStripMenuItem_Refresh"); - // - // toolStripMenuItem_FlushDnsCache - // - toolStripMenuItem_FlushDnsCache.Name = "toolStripMenuItem_FlushDnsCache"; - resources.ApplyResources(toolStripMenuItem_FlushDnsCache, "toolStripMenuItem_FlushDnsCache"); - // - // toolStripSeparator2 - // - toolStripSeparator2.Name = "toolStripSeparator2"; - resources.ApplyResources(toolStripSeparator2, "toolStripSeparator2"); - // - // toolStripMenuItem_New - // - toolStripMenuItem_New.Name = "toolStripMenuItem_New"; - resources.ApplyResources(toolStripMenuItem_New, "toolStripMenuItem_New"); - // - // toolStripMenuItem_Modify - // - toolStripMenuItem_Modify.Name = "toolStripMenuItem_Modify"; - resources.ApplyResources(toolStripMenuItem_Modify, "toolStripMenuItem_Modify"); - // - // toolStripMenuItem_Delete - // - toolStripMenuItem_Delete.Name = "toolStripMenuItem_Delete"; - resources.ApplyResources(toolStripMenuItem_Delete, "toolStripMenuItem_Delete"); - // - // toolStripSeparator1 - // - toolStripSeparator1.Name = "toolStripSeparator1"; - resources.ApplyResources(toolStripSeparator1, "toolStripSeparator1"); - // - // toolStripMenuItem_More - // - toolStripMenuItem_More.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripMenuItem_Import, toolStripMenuItem_Export, toolStripSeparator5, toolStripMenuItem_ResetWindowSize }); - toolStripMenuItem_More.Name = "toolStripMenuItem_More"; - resources.ApplyResources(toolStripMenuItem_More, "toolStripMenuItem_More"); - // - // toolStripMenuItem_Import - // - toolStripMenuItem_Import.Name = "toolStripMenuItem_Import"; - resources.ApplyResources(toolStripMenuItem_Import, "toolStripMenuItem_Import"); - toolStripMenuItem_Import.Click += toolStripMenuItem_Import_Click; - // - // toolStripMenuItem_Export - // - toolStripMenuItem_Export.Name = "toolStripMenuItem_Export"; - resources.ApplyResources(toolStripMenuItem_Export, "toolStripMenuItem_Export"); - toolStripMenuItem_Export.Click += toolStripMenuItem_Export_Click; - // - // toolStripSeparator5 - // - toolStripSeparator5.Name = "toolStripSeparator5"; - resources.ApplyResources(toolStripSeparator5, "toolStripSeparator5"); - // - // toolStripMenuItem_ResetWindowSize - // - toolStripMenuItem_ResetWindowSize.Name = "toolStripMenuItem_ResetWindowSize"; - resources.ApplyResources(toolStripMenuItem_ResetWindowSize, "toolStripMenuItem_ResetWindowSize"); - toolStripMenuItem_ResetWindowSize.Click += toolStripMenuItem_ResetWindowSize_Click; - // - // toolStripSeparator4 - // - toolStripSeparator4.Name = "toolStripSeparator4"; - resources.ApplyResources(toolStripSeparator4, "toolStripSeparator4"); - // - // toolStripMenuItem_About - // - toolStripMenuItem_About.Name = "toolStripMenuItem_About"; - resources.ApplyResources(toolStripMenuItem_About, "toolStripMenuItem_About"); - // - // imageListProxies - // - imageListProxies.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; - imageListProxies.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("imageListProxies.ImageStream"); - imageListProxies.TransparentColor = System.Drawing.Color.Transparent; - imageListProxies.Images.SetKeyName(0, "disable.png"); - imageListProxies.Images.SetKeyName(1, "enable.png"); - // - // saveFileDialog_Export - // - resources.ApplyResources(saveFileDialog_Export, "saveFileDialog_Export"); - // - // openFileDialog_Import - // - openFileDialog_Import.FileName = "openFileDialog1"; - resources.ApplyResources(openFileDialog_Import, "openFileDialog_Import"); - // - // statusStrip_Footer - // - statusStrip_Footer.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripStatusLabel_Status, toolStripStatusLabel_ServiceNotRunning }); - resources.ApplyResources(statusStrip_Footer, "statusStrip_Footer"); - statusStrip_Footer.Name = "statusStrip_Footer"; - // - // toolStripStatusLabel_Status - // - toolStripStatusLabel_Status.Name = "toolStripStatusLabel_Status"; - resources.ApplyResources(toolStripStatusLabel_Status, "toolStripStatusLabel_Status"); - // - // toolStripStatusLabel_ServiceNotRunning - // - toolStripStatusLabel_ServiceNotRunning.IsLink = true; - toolStripStatusLabel_ServiceNotRunning.LinkColor = System.Drawing.Color.Red; - toolStripStatusLabel_ServiceNotRunning.Name = "toolStripStatusLabel_ServiceNotRunning"; - resources.ApplyResources(toolStripStatusLabel_ServiceNotRunning, "toolStripStatusLabel_ServiceNotRunning"); - toolStripStatusLabel_ServiceNotRunning.Click += toolStripStatusLabel_ServiceNotRunning_Click; - // - // PortProxyGUI - // - resources.ApplyResources(this, "$this"); - AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - Controls.Add(statusStrip_Footer); - Controls.Add(listViewProxies); - Name = "PortProxyGUI"; - FormClosing += PortProxyGUI_FormClosing; - Load += PortProxyGUI_Load; - Shown += PortProxyGUI_Shown; - Resize += PortProxyGUI_Resize; - contextMenuStrip_RightClick.ResumeLayout(false); - statusStrip_Footer.ResumeLayout(false); - statusStrip_Footer.PerformLayout(); - ResumeLayout(false); - PerformLayout(); - } - - #endregion - private System.Windows.Forms.ColumnHeader columnHeader2; - private System.Windows.Forms.ColumnHeader columnHeader3; - private System.Windows.Forms.ContextMenuStrip contextMenuStrip_RightClick; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_New; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Delete; - private System.Windows.Forms.ColumnHeader columnHeader4; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Refresh; - private System.Windows.Forms.ColumnHeader columnHeader5; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_About; - private System.Windows.Forms.ColumnHeader columnHeader6; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Modify; - private System.Windows.Forms.ColumnHeader columnHeader1; - private System.Windows.Forms.ImageList imageListProxies; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Enable; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Disable; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; - private System.Windows.Forms.ColumnHeader columnHeader7; - internal System.Windows.Forms.ListView listViewProxies; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_FlushDnsCache; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_More; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Export; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Import; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; - private System.Windows.Forms.SaveFileDialog saveFileDialog_Export; - private System.Windows.Forms.OpenFileDialog openFileDialog_Import; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_ResetWindowSize; - private System.Windows.Forms.StatusStrip statusStrip_Footer; - private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_Status; - private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_ServiceNotRunning; + base.Dispose(disposing); } + + #region Windows Form Designer generated code + + /// <summary> + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// </summary> + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PortProxyGUI)); + listViewProxies = new System.Windows.Forms.ListView(); + columnHeader1 = new System.Windows.Forms.ColumnHeader(); + columnHeader2 = new System.Windows.Forms.ColumnHeader(); + columnHeader3 = new System.Windows.Forms.ColumnHeader(); + columnHeader4 = new System.Windows.Forms.ColumnHeader(); + columnHeader5 = new System.Windows.Forms.ColumnHeader(); + columnHeader6 = new System.Windows.Forms.ColumnHeader(); + columnHeader7 = new System.Windows.Forms.ColumnHeader(); + contextMenuStrip_RightClick = new System.Windows.Forms.ContextMenuStrip(components); + toolStripMenuItem_Enable = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem_Disable = new System.Windows.Forms.ToolStripMenuItem(); + toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); + toolStripMenuItem_Refresh = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem_FlushDnsCache = new System.Windows.Forms.ToolStripMenuItem(); + toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); + toolStripMenuItem_New = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem_Modify = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem_Delete = new System.Windows.Forms.ToolStripMenuItem(); + toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); + toolStripMenuItem_More = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem_Import = new System.Windows.Forms.ToolStripMenuItem(); + toolStripMenuItem_Export = new System.Windows.Forms.ToolStripMenuItem(); + toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); + toolStripMenuItem_ResetWindowSize = new System.Windows.Forms.ToolStripMenuItem(); + toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); + toolStripMenuItem_About = new System.Windows.Forms.ToolStripMenuItem(); + imageListProxies = new System.Windows.Forms.ImageList(components); + saveFileDialog_Export = new System.Windows.Forms.SaveFileDialog(); + openFileDialog_Import = new System.Windows.Forms.OpenFileDialog(); + statusStrip_Footer = new System.Windows.Forms.StatusStrip(); + toolStripStatusLabel_Status = new System.Windows.Forms.ToolStripStatusLabel(); + toolStripStatusLabel_ServiceNotRunning = new System.Windows.Forms.ToolStripStatusLabel(); + contextMenuStrip_RightClick.SuspendLayout(); + statusStrip_Footer.SuspendLayout(); + SuspendLayout(); + // + // listViewProxies + // + listViewProxies.BorderStyle = System.Windows.Forms.BorderStyle.None; + listViewProxies.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { columnHeader1, columnHeader2, columnHeader3, columnHeader4, columnHeader5, columnHeader6, columnHeader7 }); + listViewProxies.ContextMenuStrip = contextMenuStrip_RightClick; + resources.ApplyResources(listViewProxies, "listViewProxies"); + listViewProxies.FullRowSelect = true; + listViewProxies.Name = "listViewProxies"; + listViewProxies.SmallImageList = imageListProxies; + listViewProxies.UseCompatibleStateImageBehavior = false; + listViewProxies.View = System.Windows.Forms.View.Details; + listViewProxies.ColumnClick += listView1_ColumnClick; + listViewProxies.ColumnWidthChanged += listViewProxies_ColumnWidthChanged; + listViewProxies.DoubleClick += listView1_DoubleClick; + listViewProxies.KeyUp += listViewProxies_KeyUp; + listViewProxies.MouseUp += listView1_MouseUp; + // + // columnHeader1 + // + resources.ApplyResources(columnHeader1, "columnHeader1"); + // + // columnHeader2 + // + resources.ApplyResources(columnHeader2, "columnHeader2"); + // + // columnHeader3 + // + resources.ApplyResources(columnHeader3, "columnHeader3"); + // + // columnHeader4 + // + columnHeader4.Tag = ""; + resources.ApplyResources(columnHeader4, "columnHeader4"); + // + // columnHeader5 + // + resources.ApplyResources(columnHeader5, "columnHeader5"); + // + // columnHeader6 + // + columnHeader6.Tag = ""; + resources.ApplyResources(columnHeader6, "columnHeader6"); + // + // columnHeader7 + // + resources.ApplyResources(columnHeader7, "columnHeader7"); + // + // contextMenuStrip_RightClick + // + contextMenuStrip_RightClick.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripMenuItem_Enable, toolStripMenuItem_Disable, toolStripSeparator3, toolStripMenuItem_Refresh, toolStripMenuItem_FlushDnsCache, toolStripSeparator2, toolStripMenuItem_New, toolStripMenuItem_Modify, toolStripMenuItem_Delete, toolStripSeparator1, toolStripMenuItem_More, toolStripSeparator4, toolStripMenuItem_About }); + contextMenuStrip_RightClick.Name = "contextMenuStrip1"; + resources.ApplyResources(contextMenuStrip_RightClick, "contextMenuStrip_RightClick"); + contextMenuStrip_RightClick.MouseClick += contextMenuStrip_RightClick_MouseClick; + // + // toolStripMenuItem_Enable + // + toolStripMenuItem_Enable.Name = "toolStripMenuItem_Enable"; + resources.ApplyResources(toolStripMenuItem_Enable, "toolStripMenuItem_Enable"); + // + // toolStripMenuItem_Disable + // + toolStripMenuItem_Disable.Name = "toolStripMenuItem_Disable"; + resources.ApplyResources(toolStripMenuItem_Disable, "toolStripMenuItem_Disable"); + // + // toolStripSeparator3 + // + toolStripSeparator3.Name = "toolStripSeparator3"; + resources.ApplyResources(toolStripSeparator3, "toolStripSeparator3"); + // + // toolStripMenuItem_Refresh + // + toolStripMenuItem_Refresh.Name = "toolStripMenuItem_Refresh"; + resources.ApplyResources(toolStripMenuItem_Refresh, "toolStripMenuItem_Refresh"); + // + // toolStripMenuItem_FlushDnsCache + // + toolStripMenuItem_FlushDnsCache.Name = "toolStripMenuItem_FlushDnsCache"; + resources.ApplyResources(toolStripMenuItem_FlushDnsCache, "toolStripMenuItem_FlushDnsCache"); + // + // toolStripSeparator2 + // + toolStripSeparator2.Name = "toolStripSeparator2"; + resources.ApplyResources(toolStripSeparator2, "toolStripSeparator2"); + // + // toolStripMenuItem_New + // + toolStripMenuItem_New.Name = "toolStripMenuItem_New"; + resources.ApplyResources(toolStripMenuItem_New, "toolStripMenuItem_New"); + // + // toolStripMenuItem_Modify + // + toolStripMenuItem_Modify.Name = "toolStripMenuItem_Modify"; + resources.ApplyResources(toolStripMenuItem_Modify, "toolStripMenuItem_Modify"); + // + // toolStripMenuItem_Delete + // + toolStripMenuItem_Delete.Name = "toolStripMenuItem_Delete"; + resources.ApplyResources(toolStripMenuItem_Delete, "toolStripMenuItem_Delete"); + // + // toolStripSeparator1 + // + toolStripSeparator1.Name = "toolStripSeparator1"; + resources.ApplyResources(toolStripSeparator1, "toolStripSeparator1"); + // + // toolStripMenuItem_More + // + toolStripMenuItem_More.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripMenuItem_Import, toolStripMenuItem_Export, toolStripSeparator5, toolStripMenuItem_ResetWindowSize }); + toolStripMenuItem_More.Name = "toolStripMenuItem_More"; + resources.ApplyResources(toolStripMenuItem_More, "toolStripMenuItem_More"); + // + // toolStripMenuItem_Import + // + toolStripMenuItem_Import.Name = "toolStripMenuItem_Import"; + resources.ApplyResources(toolStripMenuItem_Import, "toolStripMenuItem_Import"); + toolStripMenuItem_Import.Click += toolStripMenuItem_Import_Click; + // + // toolStripMenuItem_Export + // + toolStripMenuItem_Export.Name = "toolStripMenuItem_Export"; + resources.ApplyResources(toolStripMenuItem_Export, "toolStripMenuItem_Export"); + toolStripMenuItem_Export.Click += toolStripMenuItem_Export_Click; + // + // toolStripSeparator5 + // + toolStripSeparator5.Name = "toolStripSeparator5"; + resources.ApplyResources(toolStripSeparator5, "toolStripSeparator5"); + // + // toolStripMenuItem_ResetWindowSize + // + toolStripMenuItem_ResetWindowSize.Name = "toolStripMenuItem_ResetWindowSize"; + resources.ApplyResources(toolStripMenuItem_ResetWindowSize, "toolStripMenuItem_ResetWindowSize"); + toolStripMenuItem_ResetWindowSize.Click += toolStripMenuItem_ResetWindowSize_Click; + // + // toolStripSeparator4 + // + toolStripSeparator4.Name = "toolStripSeparator4"; + resources.ApplyResources(toolStripSeparator4, "toolStripSeparator4"); + // + // toolStripMenuItem_About + // + toolStripMenuItem_About.Name = "toolStripMenuItem_About"; + resources.ApplyResources(toolStripMenuItem_About, "toolStripMenuItem_About"); + // + // imageListProxies + // + imageListProxies.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; + imageListProxies.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("imageListProxies.ImageStream"); + imageListProxies.TransparentColor = System.Drawing.Color.Transparent; + imageListProxies.Images.SetKeyName(0, "disable.png"); + imageListProxies.Images.SetKeyName(1, "enable.png"); + // + // saveFileDialog_Export + // + resources.ApplyResources(saveFileDialog_Export, "saveFileDialog_Export"); + // + // openFileDialog_Import + // + openFileDialog_Import.FileName = "openFileDialog1"; + resources.ApplyResources(openFileDialog_Import, "openFileDialog_Import"); + // + // statusStrip_Footer + // + statusStrip_Footer.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripStatusLabel_Status, toolStripStatusLabel_ServiceNotRunning }); + resources.ApplyResources(statusStrip_Footer, "statusStrip_Footer"); + statusStrip_Footer.Name = "statusStrip_Footer"; + // + // toolStripStatusLabel_Status + // + toolStripStatusLabel_Status.Name = "toolStripStatusLabel_Status"; + resources.ApplyResources(toolStripStatusLabel_Status, "toolStripStatusLabel_Status"); + // + // toolStripStatusLabel_ServiceNotRunning + // + toolStripStatusLabel_ServiceNotRunning.IsLink = true; + toolStripStatusLabel_ServiceNotRunning.LinkColor = System.Drawing.Color.Red; + toolStripStatusLabel_ServiceNotRunning.Name = "toolStripStatusLabel_ServiceNotRunning"; + resources.ApplyResources(toolStripStatusLabel_ServiceNotRunning, "toolStripStatusLabel_ServiceNotRunning"); + toolStripStatusLabel_ServiceNotRunning.Click += toolStripStatusLabel_ServiceNotRunning_Click; + // + // PortProxyGUI + // + resources.ApplyResources(this, "$this"); + AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + Controls.Add(statusStrip_Footer); + Controls.Add(listViewProxies); + Name = "PortProxyGUI"; + FormClosing += PortProxyGUI_FormClosing; + Load += PortProxyGUI_Load; + Shown += PortProxyGUI_Shown; + Resize += PortProxyGUI_Resize; + contextMenuStrip_RightClick.ResumeLayout(false); + statusStrip_Footer.ResumeLayout(false); + statusStrip_Footer.PerformLayout(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ColumnHeader columnHeader3; + private System.Windows.Forms.ContextMenuStrip contextMenuStrip_RightClick; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_New; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Delete; + private System.Windows.Forms.ColumnHeader columnHeader4; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Refresh; + private System.Windows.Forms.ColumnHeader columnHeader5; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_About; + private System.Windows.Forms.ColumnHeader columnHeader6; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Modify; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ImageList imageListProxies; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Enable; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Disable; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; + private System.Windows.Forms.ColumnHeader columnHeader7; + internal System.Windows.Forms.ListView listViewProxies; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_FlushDnsCache; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_More; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Export; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_Import; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; + private System.Windows.Forms.SaveFileDialog saveFileDialog_Export; + private System.Windows.Forms.OpenFileDialog openFileDialog_Import; + private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; + private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem_ResetWindowSize; + private System.Windows.Forms.StatusStrip statusStrip_Footer; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_Status; + private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel_ServiceNotRunning; } diff --git a/PortProxyGUI/PortProxyGUI.cs b/PortProxyGUI/PortProxyGUI.cs index 485eda2..daa6f02 100644 --- a/PortProxyGUI/PortProxyGUI.cs +++ b/PortProxyGUI/PortProxyGUI.cs @@ -9,131 +9,85 @@ using System.Linq; using System.Windows.Forms; using static System.Windows.Forms.ListViewItem; -namespace PortProxyGUI +namespace PortProxyGUI; + +public partial class PortProxyGUI : Form { - public partial class PortProxyGUI : Form + private readonly ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter(); + + public SetProxy SetProxyForm; + public About AboutForm; + private AppConfig AppConfig; + + public PortProxyGUI() { - private readonly ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter(); + InitializeComponent(); + listViewProxies.ListViewItemSorter = lvwColumnSorter; + } - public SetProxy SetProxyForm; - public About AboutForm; - private AppConfig AppConfig; + private void PortProxyGUI_Load(object sender, EventArgs e) + { + AppConfig = Program.Database.GetAppConfig(); - public PortProxyGUI() + var size = AppConfig.MainWindowSize; + Left -= (size.Width - Width) / 2; + Top -= (size.Height - Height) / 2; + + ResetWindowSize(); + } + + private void PortProxyGUI_Shown(object sender, EventArgs e) + { + RefreshProxyList(); + } + + private void ResetWindowSize() + { + Size = AppConfig.MainWindowSize; + + if (AppConfig.PortProxyColumnWidths.Length != listViewProxies.Columns.Count) { - InitializeComponent(); - listViewProxies.ListViewItemSorter = lvwColumnSorter; + Any.ReDim(ref AppConfig.PortProxyColumnWidths, listViewProxies.Columns.Count); } - private void PortProxyGUI_Load(object sender, EventArgs e) + foreach (var (column, configWidth) in Any.Zip(listViewProxies.Columns.OfType<ColumnHeader>(), AppConfig.PortProxyColumnWidths)) { - AppConfig = Program.Database.GetAppConfig(); - - var size = AppConfig.MainWindowSize; - Left -= (size.Width - Width) / 2; - Top -= (size.Height - Height) / 2; - - ResetWindowSize(); + column.Width = configWidth; } + } - private void PortProxyGUI_Shown(object sender, EventArgs e) + private Data.Rule ParseRule(ListViewItem item) + { + var subItems = item.SubItems.OfType<ListViewSubItem>().ToArray(); + int listenPort, connectPort; + + listenPort = Data.Rule.ParsePort(subItems[3].Text); + connectPort = Data.Rule.ParsePort(subItems[5].Text); + + var rule = new Data.Rule { - RefreshProxyList(); - } + Type = subItems[1].Text.Trim(), + ListenOn = subItems[2].Text.Trim(), + ListenPort = listenPort, + ConnectTo = subItems[4].Text.Trim(), + ConnectPort = connectPort, + Comment = subItems[6].Text.Trim(), + Group = item.Group?.Header.Trim(), + }; + return rule; + } - private void ResetWindowSize() + private void EnableSelectedProxies() + { + var items = listViewProxies.SelectedItems.OfType<ListViewItem>(); + foreach (var item in items) { - Size = AppConfig.MainWindowSize; + item.ImageIndex = 1; - if (AppConfig.PortProxyColumnWidths.Length != listViewProxies.Columns.Count) - { - Any.ReDim(ref AppConfig.PortProxyColumnWidths, listViewProxies.Columns.Count); - } - - foreach (var (column, configWidth) in Any.Zip(listViewProxies.Columns.OfType<ColumnHeader>(), AppConfig.PortProxyColumnWidths)) - { - column.Width = configWidth; - } - } - - private Data.Rule ParseRule(ListViewItem item) - { - var subItems = item.SubItems.OfType<ListViewSubItem>().ToArray(); - int listenPort, connectPort; - - listenPort = Data.Rule.ParsePort(subItems[3].Text); - connectPort = Data.Rule.ParsePort(subItems[5].Text); - - var rule = new Data.Rule - { - Type = subItems[1].Text.Trim(), - ListenOn = subItems[2].Text.Trim(), - ListenPort = listenPort, - ConnectTo = subItems[4].Text.Trim(), - ConnectPort = connectPort, - Comment = subItems[6].Text.Trim(), - Group = item.Group?.Header.Trim(), - }; - return rule; - } - - private void EnableSelectedProxies() - { - var items = listViewProxies.SelectedItems.OfType<ListViewItem>(); - foreach (var item in items) - { - item.ImageIndex = 1; - - try - { - var rule = ParseRule(item); - PortPorxyUtil.AddOrUpdateProxy(rule); - } - catch (NotSupportedException ex) - { - MessageBox.Show(ex.Message, "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - return; - } - } - PortPorxyUtil.ParamChange(); - } - - private void DisableSelectedProxies() - { - var items = listViewProxies.SelectedItems.OfType<ListViewItem>(); - foreach (var item in items) - { - item.ImageIndex = 0; - - try - { - var rule = ParseRule(item); - PortPorxyUtil.DeleteProxy(rule); - } - catch (NotSupportedException ex) - { - MessageBox.Show(ex.Message, "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - return; - } - } - PortPorxyUtil.ParamChange(); - } - - private void DeleteSelectedProxies() - { - var items = listViewProxies.SelectedItems.OfType<ListViewItem>(); - DisableSelectedProxies(); - Program.Database.RemoveRange(items.Select(x => new Data.Rule { Id = x.Tag.ToString() })); - foreach (var item in items) listViewProxies.Items.Remove(item); - } - - private void SetProxyForUpdate(SetProxy form) - { - var item = listViewProxies.SelectedItems.OfType<ListViewItem>().FirstOrDefault(); try { var rule = ParseRule(item); - form.UseUpdateMode(item, rule); + Util.AddOrUpdateProxy(rule); } catch (NotSupportedException ex) { @@ -141,269 +95,314 @@ namespace PortProxyGUI return; } } + Util.ParamChange(); + } - private void InitProxyGroups(Data.Rule[] rules) + private void DisableSelectedProxies() + { + var items = listViewProxies.SelectedItems.OfType<ListViewItem>(); + foreach (var item in items) { - listViewProxies.Groups.Clear(); - var groups = ( - from g in rules.GroupBy(x => x.Group) - let name = g.Key - where !name.IsNullOrWhiteSpace() - orderby name - select new ListViewGroup(name) - ).ToArray(); - listViewProxies.Groups.AddRange(groups); - } + item.ImageIndex = 0; - private void InitProxyItems(Data.Rule[] rules, Data.Rule[] proxies) - { - listViewProxies.Items.Clear(); - foreach (var rule in rules) + try { - var imageIndex = proxies.Any(p => p.EqualsWithKeys(rule)) ? 1 : 0; - var group = listViewProxies.Groups.OfType<ListViewGroup>().FirstOrDefault(x => x.Header == rule.Group); - - var item = new ListViewItem(); - UpdateListViewItem(item, rule, imageIndex); - listViewProxies.Items.Add(item); + var rule = ParseRule(item); + Util.DeleteProxy(rule); + } + catch (NotSupportedException ex) + { + MessageBox.Show(ex.Message, "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + return; } } + Util.ParamChange(); + } - public void UpdateListViewItem(ListViewItem item, Data.Rule rule, int imageIndex) + private void DeleteSelectedProxies() + { + var items = listViewProxies.SelectedItems.OfType<ListViewItem>(); + DisableSelectedProxies(); + Program.Database.RemoveRange(items.Select(x => new Data.Rule { Id = x.Tag.ToString() })); + foreach (var item in items) listViewProxies.Items.Remove(item); + } + + private void SetProxyForUpdate(SetProxy form) + { + var item = listViewProxies.SelectedItems.OfType<ListViewItem>().FirstOrDefault(); + try { - item.ImageIndex = imageIndex; - item.Tag = rule.Id; - item.SubItems.Clear(); - item.SubItems.AddRange(new[] - { - new ListViewSubItem(item, rule.Type), - new ListViewSubItem(item, rule.ListenOn), - new ListViewSubItem(item, rule.ListenPort.ToString()) { Tag = "Number" }, - new ListViewSubItem(item, rule.ConnectTo), - new ListViewSubItem(item, rule.ConnectPort.ToString ()) { Tag = "Number" }, - new ListViewSubItem(item, rule.Comment ?? ""), - }); + var rule = ParseRule(item); + form.UseUpdateMode(item, rule); + } + catch (NotSupportedException ex) + { + MessageBox.Show(ex.Message, "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + return; + } + } - if (rule.Group.IsNullOrWhiteSpace()) item.Group = null; - else + private void InitProxyGroups(Data.Rule[] rules) + { + listViewProxies.Groups.Clear(); + var groups = ( + from g in rules.GroupBy(x => x.Group) + let name = g.Key + where !name.IsNullOrWhiteSpace() + orderby name + select new ListViewGroup(name) + ).ToArray(); + listViewProxies.Groups.AddRange(groups); + } + + private void InitProxyItems(Data.Rule[] rules, Data.Rule[] proxies) + { + listViewProxies.Items.Clear(); + foreach (var rule in rules) + { + var imageIndex = proxies.Any(p => p.EqualsWithKeys(rule)) ? 1 : 0; + var group = listViewProxies.Groups.OfType<ListViewGroup>().FirstOrDefault(x => x.Header == rule.Group); + + var item = new ListViewItem(); + UpdateListViewItem(item, rule, imageIndex); + listViewProxies.Items.Add(item); + } + } + + public void UpdateListViewItem(ListViewItem item, Data.Rule rule, int imageIndex) + { + item.ImageIndex = imageIndex; + item.Tag = rule.Id; + item.SubItems.Clear(); + item.SubItems.AddRange(new[] + { + new ListViewSubItem(item, rule.Type), + new ListViewSubItem(item, rule.ListenOn), + new ListViewSubItem(item, rule.ListenPort.ToString()) { Tag = "Number" }, + new ListViewSubItem(item, rule.ConnectTo), + new ListViewSubItem(item, rule.ConnectPort.ToString ()) { Tag = "Number" }, + new ListViewSubItem(item, rule.Comment ?? ""), + }); + + if (rule.Group.IsNullOrWhiteSpace()) item.Group = null; + else + { + var group = listViewProxies.Groups.OfType<ListViewGroup>().FirstOrDefault(x => x.Header == rule.Group); + if (group == null) { - var group = listViewProxies.Groups.OfType<ListViewGroup>().FirstOrDefault(x => x.Header == rule.Group); - if (group == null) - { - group = new ListViewGroup(rule.Group); - listViewProxies.Groups.Add(group); - } - item.Group = group; + group = new ListViewGroup(rule.Group); + listViewProxies.Groups.Add(group); } + item.Group = group; + } + } + + public void RefreshProxyList() + { + var proxies = Util.GetProxies(); + var rules = Program.Database.Rules.ToArray(); + foreach (var proxy in proxies) + { + var matchedRule = rules.FirstOrDefault(r => r.EqualsWithKeys(proxy)); + proxy.Id = matchedRule?.Id; } - public void RefreshProxyList() + var pendingAdds = proxies.Where(x => x.Valid && x.Id == null); + var pendingUpdates = + from proxy in proxies + let exsist = rules.FirstOrDefault(r => r.Id == proxy.Id) + where exsist is not null + where proxy.Valid && proxy.Id is not null + select proxy; + + Program.Database.AddRange(pendingAdds); + Program.Database.UpdateRange(pendingUpdates); + + rules = Program.Database.Rules.ToArray(); + InitProxyGroups(rules); + InitProxyItems(rules, proxies); + + // CheckServiceStatus + toolStripStatusLabel_ServiceNotRunning.Visible = !Util.IsServiceRunning(); + } + + private void contextMenuStrip_RightClick_MouseClick(object sender, MouseEventArgs e) + { + if (sender is ContextMenuStrip strip) { - var proxies = PortPorxyUtil.GetProxies(); - var rules = Program.Database.Rules.ToArray(); - foreach (var proxy in proxies) + var selected = strip.Items.OfType<ToolStripMenuItem>().Where(x => x.Selected).FirstOrDefault(); + if (selected is null || !selected.Enabled) return; + + switch (selected) { - var matchedRule = rules.FirstOrDefault(r => r.EqualsWithKeys(proxy)); - proxy.Id = matchedRule?.Id; - } + case ToolStripMenuItem item when item == toolStripMenuItem_Enable: EnableSelectedProxies(); break; + case ToolStripMenuItem item when item == toolStripMenuItem_Disable: DisableSelectedProxies(); break; - var pendingAdds = proxies.Where(x => x.Valid && x.Id == null); - var pendingUpdates = - from proxy in proxies - let exsist = rules.FirstOrDefault(r => r.Id == proxy.Id) - where exsist is not null - where proxy.Valid && proxy.Id is not null - select proxy; + case ToolStripMenuItem item when item == toolStripMenuItem_New: + SetProxyForm ??= new SetProxy(this); + SetProxyForm.UseNormalMode(); + SetProxyForm.ShowDialog(); + break; - Program.Database.AddRange(pendingAdds); - Program.Database.UpdateRange(pendingUpdates); - - rules = Program.Database.Rules.ToArray(); - InitProxyGroups(rules); - InitProxyItems(rules, proxies); - - // CheckServiceStatus - toolStripStatusLabel_ServiceNotRunning.Visible = !PortPorxyUtil.IsServiceRunning(); - } - - private void contextMenuStrip_RightClick_MouseClick(object sender, MouseEventArgs e) - { - if (sender is ContextMenuStrip strip) - { - var selected = strip.Items.OfType<ToolStripMenuItem>().Where(x => x.Selected).FirstOrDefault(); - if (selected is null || !selected.Enabled) return; - - switch (selected) - { - case ToolStripMenuItem item when item == toolStripMenuItem_Enable: EnableSelectedProxies(); break; - case ToolStripMenuItem item when item == toolStripMenuItem_Disable: DisableSelectedProxies(); break; - - case ToolStripMenuItem item when item == toolStripMenuItem_New: - SetProxyForm ??= new SetProxy(this); - SetProxyForm.UseNormalMode(); - SetProxyForm.ShowDialog(); - break; - - case ToolStripMenuItem item when item == toolStripMenuItem_Modify: - SetProxyForm ??= new SetProxy(this); - SetProxyForUpdate(SetProxyForm); - SetProxyForm.ShowDialog(); - break; - - case ToolStripMenuItem item when item == toolStripMenuItem_Refresh: - RefreshProxyList(); - toolStripStatusLabel_Status.Text = $"{DateTime.Now} : Refreshed."; - break; - - case ToolStripMenuItem item when item == toolStripMenuItem_FlushDnsCache: - DnsUtil.FlushCache(); - toolStripStatusLabel_Status.Text = $"{DateTime.Now} : DNS cache cleared."; - break; - - case ToolStripMenuItem item when item == toolStripMenuItem_Delete: - DeleteSelectedProxies(); - break; - - case ToolStripMenuItem item when item == toolStripMenuItem_About: - if (AboutForm == null) - { - AboutForm = new About(this); - AboutForm.Show(); - } - else AboutForm.Show(); - break; - } - } - } - - private void listView1_MouseUp(object sender, MouseEventArgs e) - { - if (sender is ListView listView) - { - toolStripMenuItem_Enable.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Any(x => x.ImageIndex == 0); - toolStripMenuItem_Disable.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Any(x => x.ImageIndex == 1); - - toolStripMenuItem_Delete.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Any(); - toolStripMenuItem_Modify.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Count() == 1; - } - } - - private void listView1_DoubleClick(object sender, EventArgs e) - { - if (sender is ListView listView) - { - var selectAny = listView.SelectedItems.OfType<ListViewItem>().Any(); - if (selectAny) - { + case ToolStripMenuItem item when item == toolStripMenuItem_Modify: SetProxyForm ??= new SetProxy(this); SetProxyForUpdate(SetProxyForm); SetProxyForm.ShowDialog(); - } + break; + + case ToolStripMenuItem item when item == toolStripMenuItem_Refresh: + RefreshProxyList(); + toolStripStatusLabel_Status.Text = $"{DateTime.Now} : Refreshed."; + break; + + case ToolStripMenuItem item when item == toolStripMenuItem_FlushDnsCache: + DnsUtil.FlushCache(); + toolStripStatusLabel_Status.Text = $"{DateTime.Now} : DNS cache cleared."; + break; + + case ToolStripMenuItem item when item == toolStripMenuItem_Delete: + DeleteSelectedProxies(); + break; + + case ToolStripMenuItem item when item == toolStripMenuItem_About: + if (AboutForm == null) + { + AboutForm = new About(this); + AboutForm.Show(); + } + else AboutForm.Show(); + break; } } + } - private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) + private void listView1_MouseUp(object sender, MouseEventArgs e) + { + if (sender is ListView listView) { - // Determine if clicked column is already the column that is being sorted. - if (e.Column == lvwColumnSorter.SortColumn) + toolStripMenuItem_Enable.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Any(x => x.ImageIndex == 0); + toolStripMenuItem_Disable.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Any(x => x.ImageIndex == 1); + + toolStripMenuItem_Delete.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Any(); + toolStripMenuItem_Modify.Enabled = e.Button == MouseButtons.Right && listView.SelectedItems.OfType<ListViewItem>().Count() == 1; + } + } + + private void listView1_DoubleClick(object sender, EventArgs e) + { + if (sender is ListView listView) + { + var selectAny = listView.SelectedItems.OfType<ListViewItem>().Any(); + if (selectAny) { - // Reverse the current sort direction for this column. - if (lvwColumnSorter.Order == SortOrder.Ascending) - { - lvwColumnSorter.Order = SortOrder.Descending; - } - else - { - lvwColumnSorter.Order = SortOrder.Ascending; - } + SetProxyForm ??= new SetProxy(this); + SetProxyForUpdate(SetProxyForm); + SetProxyForm.ShowDialog(); + } + } + } + + private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) + { + // Determine if clicked column is already the column that is being sorted. + if (e.Column == lvwColumnSorter.SortColumn) + { + // Reverse the current sort direction for this column. + if (lvwColumnSorter.Order == SortOrder.Ascending) + { + lvwColumnSorter.Order = SortOrder.Descending; } else { - // Set the column number that is to be sorted; default to ascending. - lvwColumnSorter.SortColumn = e.Column; lvwColumnSorter.Order = SortOrder.Ascending; } - - // Perform the sort with these new sort options. - listViewProxies.Sort(); + } + else + { + // Set the column number that is to be sorted; default to ascending. + lvwColumnSorter.SortColumn = e.Column; + lvwColumnSorter.Order = SortOrder.Ascending; } - private void listViewProxies_KeyUp(object sender, KeyEventArgs e) + // Perform the sort with these new sort options. + listViewProxies.Sort(); + } + + private void listViewProxies_KeyUp(object sender, KeyEventArgs e) + { + if (sender is ListView) { - if (sender is ListView) - { - if (e.KeyCode == Keys.Delete) DeleteSelectedProxies(); - } - } - - private void listViewProxies_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) - { - if (AppConfig is not null && sender is ListView listView) - { - AppConfig.PortProxyColumnWidths[e.ColumnIndex] = listView.Columns[e.ColumnIndex].Width; - } - } - - private void PortProxyGUI_FormClosing(object sender, FormClosingEventArgs e) - { - Program.Database.SaveAppConfig(AppConfig); - } - - private void PortProxyGUI_Resize(object sender, EventArgs e) - { - if (AppConfig is not null && sender is Form form) - { - AppConfig.MainWindowSize = form.Size; - } - } - - private void toolStripMenuItem_Export_Click(object sender, EventArgs e) - { - using var dialog = saveFileDialog_Export; - - var result = dialog.ShowDialog(); - if (result == DialogResult.OK) - { - var fileName = dialog.FileName; - File.Copy(ApplicationDbScope.AppDbFile, fileName, true); - } - } - - private void toolStripMenuItem_Import_Click(object sender, EventArgs e) - { - using var dialog = openFileDialog_Import; - - var result = dialog.ShowDialog(); - if (result == DialogResult.OK) - { - var fileName = dialog.FileName; - using (var scope = ApplicationDbScope.FromFile(fileName)) - { - foreach (var rule in scope.Rules) - { - var exsist = Program.Database.GetRule(rule.Type, rule.ListenOn, rule.ListenPort); - if (exsist is null) - { - rule.Id = Guid.NewGuid().ToString(); - Program.Database.Add(rule); - } - } - } - - RefreshProxyList(); - } - } - - private void toolStripMenuItem_ResetWindowSize_Click(object sender, EventArgs e) - { - AppConfig = new AppConfig(); - ResetWindowSize(); - } - - private void toolStripStatusLabel_ServiceNotRunning_Click(object sender, EventArgs e) - { - PortPorxyUtil.StartService(); - toolStripStatusLabel_ServiceNotRunning.Visible = false; + if (e.KeyCode == Keys.Delete) DeleteSelectedProxies(); } } + + private void listViewProxies_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) + { + if (AppConfig is not null && sender is ListView listView) + { + AppConfig.PortProxyColumnWidths[e.ColumnIndex] = listView.Columns[e.ColumnIndex].Width; + } + } + + private void PortProxyGUI_FormClosing(object sender, FormClosingEventArgs e) + { + Program.Database.SaveAppConfig(AppConfig); + } + + private void PortProxyGUI_Resize(object sender, EventArgs e) + { + if (AppConfig is not null && sender is Form form) + { + AppConfig.MainWindowSize = form.Size; + } + } + + private void toolStripMenuItem_Export_Click(object sender, EventArgs e) + { + using var dialog = saveFileDialog_Export; + + var result = dialog.ShowDialog(); + if (result == DialogResult.OK) + { + var fileName = dialog.FileName; + File.Copy(ApplicationDbScope.AppDbFile, fileName, true); + } + } + + private void toolStripMenuItem_Import_Click(object sender, EventArgs e) + { + using var dialog = openFileDialog_Import; + + var result = dialog.ShowDialog(); + if (result == DialogResult.OK) + { + var fileName = dialog.FileName; + using (var scope = ApplicationDbScope.FromFile(fileName)) + { + foreach (var rule in scope.Rules) + { + var exsist = Program.Database.GetRule(rule.Type, rule.ListenOn, rule.ListenPort); + if (exsist is null) + { + rule.Id = Guid.NewGuid().ToString(); + Program.Database.Add(rule); + } + } + } + + RefreshProxyList(); + } + } + + private void toolStripMenuItem_ResetWindowSize_Click(object sender, EventArgs e) + { + AppConfig = new AppConfig(); + ResetWindowSize(); + } + + private void toolStripStatusLabel_ServiceNotRunning_Click(object sender, EventArgs e) + { + Util.StartService(); + toolStripStatusLabel_ServiceNotRunning.Visible = false; + } } diff --git a/PortProxyGUI/Program.cs b/PortProxyGUI/Program.cs index 1c8304e..d0c3fdf 100644 --- a/PortProxyGUI/Program.cs +++ b/PortProxyGUI/Program.cs @@ -1,41 +1,50 @@ using PortProxyGUI.Data; using System; using System.IO; +using System.Linq; using System.Windows.Forms; -namespace PortProxyGUI -{ - static class Program - { - public static readonly ApplicationDbScope Database = ApplicationDbScope.FromFile( - Path.Combine( - Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), - "PortProxyGUI" - ), "config.db" - )); +namespace PortProxyGUI; - /// <summary> - /// The main entry point for the application. - /// </summary> - [STAThread] - static void Main() - { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. +static class Program +{ + private static string GetPath(params string[] pathes) + { + if (!pathes.Any()) return string.Empty; + +#if NET6_0_OR_GREATER || NET451_OR_GREATER + return Path.Combine(pathes); +#else + return pathes.Aggregate(Path.Combine); +#endif + } + + public static ApplicationDbScope Database { get; } = ApplicationDbScope.FromFile(GetPath( + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), + "PortProxyGUI", + "config.db" + )); + + /// <summary> + /// The main entry point for the application. + /// </summary> + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. #if NET6_0_OR_GREATER - ApplicationConfiguration.Initialize(); + ApplicationConfiguration.Initialize(); #elif NETCOREAPP3_1_OR_GREATER - Application.SetHighDpiMode(HighDpiMode.SystemAware); - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); #else - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); #endif - Application.Run(new PortProxyGUI()); - } + Application.Run(new PortProxyGUI()); } } diff --git a/PortProxyGUI/SetProxy.Designer.cs b/PortProxyGUI/SetProxy.Designer.cs index 6176392..d5dedd2 100644 --- a/PortProxyGUI/SetProxy.Designer.cs +++ b/PortProxyGUI/SetProxy.Designer.cs @@ -1,184 +1,183 @@ -namespace PortProxyGUI +namespace PortProxyGUI; + +partial class SetProxy { - partial class SetProxy + /// <summary> + /// Required designer variable. + /// </summary> + private System.ComponentModel.IContainer components = null; + + /// <summary> + /// Clean up any resources being used. + /// </summary> + /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> + protected override void Dispose(bool disposing) { - /// <summary> - /// Required designer variable. - /// </summary> - private System.ComponentModel.IContainer components = null; - - /// <summary> - /// Clean up any resources being used. - /// </summary> - /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> - protected override void Dispose(bool disposing) + if (disposing && (components != null)) { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); + components.Dispose(); } - - #region Windows Form Designer generated code - - /// <summary> - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// </summary> - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetProxy)); - this.label_ListenOn = new System.Windows.Forms.Label(); - this.textBox_ListenOn = new System.Windows.Forms.TextBox(); - this.label_ConnectTo = new System.Windows.Forms.Label(); - this.textBox_ConnectTo = new System.Windows.Forms.TextBox(); - this.textBox_ConnectPort = new System.Windows.Forms.TextBox(); - this.label_ConnectPort = new System.Windows.Forms.Label(); - this.button_Set = new System.Windows.Forms.Button(); - this.label_Type = new System.Windows.Forms.Label(); - this.label_ListenPort = new System.Windows.Forms.Label(); - this.textBox_ListenPort = new System.Windows.Forms.TextBox(); - this.comboBox_Type = new System.Windows.Forms.ComboBox(); - this.label_Comment = new System.Windows.Forms.Label(); - this.textBox_Comment = new System.Windows.Forms.TextBox(); - this.label_Group = new System.Windows.Forms.Label(); - this.comboBox_Group = new System.Windows.Forms.ComboBox(); - this.SuspendLayout(); - // - // label_ListenOn - // - resources.ApplyResources(this.label_ListenOn, "label_ListenOn"); - this.label_ListenOn.Name = "label_ListenOn"; - // - // textBox_ListenOn - // - resources.ApplyResources(this.textBox_ListenOn, "textBox_ListenOn"); - this.textBox_ListenOn.Name = "textBox_ListenOn"; - // - // label_ConnectTo - // - resources.ApplyResources(this.label_ConnectTo, "label_ConnectTo"); - this.label_ConnectTo.Name = "label_ConnectTo"; - // - // textBox_ConnectTo - // - resources.ApplyResources(this.textBox_ConnectTo, "textBox_ConnectTo"); - this.textBox_ConnectTo.Name = "textBox_ConnectTo"; - // - // textBox_ConnectPort - // - resources.ApplyResources(this.textBox_ConnectPort, "textBox_ConnectPort"); - this.textBox_ConnectPort.Name = "textBox_ConnectPort"; - // - // label_ConnectPort - // - resources.ApplyResources(this.label_ConnectPort, "label_ConnectPort"); - this.label_ConnectPort.Name = "label_ConnectPort"; - // - // button_Set - // - resources.ApplyResources(this.button_Set, "button_Set"); - this.button_Set.Name = "button_Set"; - this.button_Set.UseVisualStyleBackColor = true; - this.button_Set.Click += new System.EventHandler(this.button_Set_Click); - // - // label_Type - // - resources.ApplyResources(this.label_Type, "label_Type"); - this.label_Type.Name = "label_Type"; - // - // label_ListenPort - // - resources.ApplyResources(this.label_ListenPort, "label_ListenPort"); - this.label_ListenPort.Name = "label_ListenPort"; - // - // textBox_ListenPort - // - resources.ApplyResources(this.textBox_ListenPort, "textBox_ListenPort"); - this.textBox_ListenPort.Name = "textBox_ListenPort"; - // - // comboBox_Type - // - resources.ApplyResources(this.comboBox_Type, "comboBox_Type"); - this.comboBox_Type.FormattingEnabled = true; - this.comboBox_Type.Items.AddRange(new object[] { - resources.GetString("comboBox_Type.Items"), - resources.GetString("comboBox_Type.Items1"), - resources.GetString("comboBox_Type.Items2"), - resources.GetString("comboBox_Type.Items3"), - resources.GetString("comboBox_Type.Items4")}); - this.comboBox_Type.Name = "comboBox_Type"; - // - // label_Comment - // - resources.ApplyResources(this.label_Comment, "label_Comment"); - this.label_Comment.Name = "label_Comment"; - // - // textBox_Comment - // - resources.ApplyResources(this.textBox_Comment, "textBox_Comment"); - this.textBox_Comment.Name = "textBox_Comment"; - // - // label_Group - // - resources.ApplyResources(this.label_Group, "label_Group"); - this.label_Group.Name = "label_Group"; - // - // comboBox_Group - // - resources.ApplyResources(this.comboBox_Group, "comboBox_Group"); - this.comboBox_Group.FormattingEnabled = true; - this.comboBox_Group.Name = "comboBox_Group"; - // - // SetProxy - // - this.AcceptButton = this.button_Set; - resources.ApplyResources(this, "$this"); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.Controls.Add(this.comboBox_Group); - this.Controls.Add(this.label_Group); - this.Controls.Add(this.textBox_Comment); - this.Controls.Add(this.label_Comment); - this.Controls.Add(this.comboBox_Type); - this.Controls.Add(this.textBox_ListenPort); - this.Controls.Add(this.label_ListenPort); - this.Controls.Add(this.label_Type); - this.Controls.Add(this.button_Set); - this.Controls.Add(this.label_ConnectPort); - this.Controls.Add(this.textBox_ConnectPort); - this.Controls.Add(this.textBox_ConnectTo); - this.Controls.Add(this.label_ConnectTo); - this.Controls.Add(this.textBox_ListenOn); - this.Controls.Add(this.label_ListenOn); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "SetProxy"; - this.TopMost = true; - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SetProxyForm_FormClosing); - this.Load += new System.EventHandler(this.SetProxyForm_Load); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Label label_ListenOn; - private System.Windows.Forms.TextBox textBox_ListenOn; - private System.Windows.Forms.Label label_ConnectTo; - private System.Windows.Forms.TextBox textBox_ConnectTo; - private System.Windows.Forms.TextBox textBox_ConnectPort; - private System.Windows.Forms.Label label_ConnectPort; - private System.Windows.Forms.Button button_Set; - private System.Windows.Forms.Label label_Type; - private System.Windows.Forms.Label label_ListenPort; - private System.Windows.Forms.TextBox textBox_ListenPort; - private System.Windows.Forms.ComboBox comboBox_Type; - private System.Windows.Forms.Label label_Comment; - private System.Windows.Forms.TextBox textBox_Comment; - private System.Windows.Forms.Label label_Group; - private System.Windows.Forms.ComboBox comboBox_Group; + base.Dispose(disposing); } + + #region Windows Form Designer generated code + + /// <summary> + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// </summary> + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetProxy)); + this.label_ListenOn = new System.Windows.Forms.Label(); + this.textBox_ListenOn = new System.Windows.Forms.TextBox(); + this.label_ConnectTo = new System.Windows.Forms.Label(); + this.textBox_ConnectTo = new System.Windows.Forms.TextBox(); + this.textBox_ConnectPort = new System.Windows.Forms.TextBox(); + this.label_ConnectPort = new System.Windows.Forms.Label(); + this.button_Set = new System.Windows.Forms.Button(); + this.label_Type = new System.Windows.Forms.Label(); + this.label_ListenPort = new System.Windows.Forms.Label(); + this.textBox_ListenPort = new System.Windows.Forms.TextBox(); + this.comboBox_Type = new System.Windows.Forms.ComboBox(); + this.label_Comment = new System.Windows.Forms.Label(); + this.textBox_Comment = new System.Windows.Forms.TextBox(); + this.label_Group = new System.Windows.Forms.Label(); + this.comboBox_Group = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // label_ListenOn + // + resources.ApplyResources(this.label_ListenOn, "label_ListenOn"); + this.label_ListenOn.Name = "label_ListenOn"; + // + // textBox_ListenOn + // + resources.ApplyResources(this.textBox_ListenOn, "textBox_ListenOn"); + this.textBox_ListenOn.Name = "textBox_ListenOn"; + // + // label_ConnectTo + // + resources.ApplyResources(this.label_ConnectTo, "label_ConnectTo"); + this.label_ConnectTo.Name = "label_ConnectTo"; + // + // textBox_ConnectTo + // + resources.ApplyResources(this.textBox_ConnectTo, "textBox_ConnectTo"); + this.textBox_ConnectTo.Name = "textBox_ConnectTo"; + // + // textBox_ConnectPort + // + resources.ApplyResources(this.textBox_ConnectPort, "textBox_ConnectPort"); + this.textBox_ConnectPort.Name = "textBox_ConnectPort"; + // + // label_ConnectPort + // + resources.ApplyResources(this.label_ConnectPort, "label_ConnectPort"); + this.label_ConnectPort.Name = "label_ConnectPort"; + // + // button_Set + // + resources.ApplyResources(this.button_Set, "button_Set"); + this.button_Set.Name = "button_Set"; + this.button_Set.UseVisualStyleBackColor = true; + this.button_Set.Click += new System.EventHandler(this.button_Set_Click); + // + // label_Type + // + resources.ApplyResources(this.label_Type, "label_Type"); + this.label_Type.Name = "label_Type"; + // + // label_ListenPort + // + resources.ApplyResources(this.label_ListenPort, "label_ListenPort"); + this.label_ListenPort.Name = "label_ListenPort"; + // + // textBox_ListenPort + // + resources.ApplyResources(this.textBox_ListenPort, "textBox_ListenPort"); + this.textBox_ListenPort.Name = "textBox_ListenPort"; + // + // comboBox_Type + // + resources.ApplyResources(this.comboBox_Type, "comboBox_Type"); + this.comboBox_Type.FormattingEnabled = true; + this.comboBox_Type.Items.AddRange(new object[] { + resources.GetString("comboBox_Type.Items"), + resources.GetString("comboBox_Type.Items1"), + resources.GetString("comboBox_Type.Items2"), + resources.GetString("comboBox_Type.Items3"), + resources.GetString("comboBox_Type.Items4")}); + this.comboBox_Type.Name = "comboBox_Type"; + // + // label_Comment + // + resources.ApplyResources(this.label_Comment, "label_Comment"); + this.label_Comment.Name = "label_Comment"; + // + // textBox_Comment + // + resources.ApplyResources(this.textBox_Comment, "textBox_Comment"); + this.textBox_Comment.Name = "textBox_Comment"; + // + // label_Group + // + resources.ApplyResources(this.label_Group, "label_Group"); + this.label_Group.Name = "label_Group"; + // + // comboBox_Group + // + resources.ApplyResources(this.comboBox_Group, "comboBox_Group"); + this.comboBox_Group.FormattingEnabled = true; + this.comboBox_Group.Name = "comboBox_Group"; + // + // SetProxy + // + this.AcceptButton = this.button_Set; + resources.ApplyResources(this, "$this"); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.comboBox_Group); + this.Controls.Add(this.label_Group); + this.Controls.Add(this.textBox_Comment); + this.Controls.Add(this.label_Comment); + this.Controls.Add(this.comboBox_Type); + this.Controls.Add(this.textBox_ListenPort); + this.Controls.Add(this.label_ListenPort); + this.Controls.Add(this.label_Type); + this.Controls.Add(this.button_Set); + this.Controls.Add(this.label_ConnectPort); + this.Controls.Add(this.textBox_ConnectPort); + this.Controls.Add(this.textBox_ConnectTo); + this.Controls.Add(this.label_ConnectTo); + this.Controls.Add(this.textBox_ListenOn); + this.Controls.Add(this.label_ListenOn); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "SetProxy"; + this.TopMost = true; + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SetProxyForm_FormClosing); + this.Load += new System.EventHandler(this.SetProxyForm_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label_ListenOn; + private System.Windows.Forms.TextBox textBox_ListenOn; + private System.Windows.Forms.Label label_ConnectTo; + private System.Windows.Forms.TextBox textBox_ConnectTo; + private System.Windows.Forms.TextBox textBox_ConnectPort; + private System.Windows.Forms.Label label_ConnectPort; + private System.Windows.Forms.Button button_Set; + private System.Windows.Forms.Label label_Type; + private System.Windows.Forms.Label label_ListenPort; + private System.Windows.Forms.TextBox textBox_ListenPort; + private System.Windows.Forms.ComboBox comboBox_Type; + private System.Windows.Forms.Label label_Comment; + private System.Windows.Forms.TextBox textBox_Comment; + private System.Windows.Forms.Label label_Group; + private System.Windows.Forms.ComboBox comboBox_Group; } \ No newline at end of file diff --git a/PortProxyGUI/SetProxy.cs b/PortProxyGUI/SetProxy.cs index 4132d45..f31c4b5 100644 --- a/PortProxyGUI/SetProxy.cs +++ b/PortProxyGUI/SetProxy.cs @@ -6,145 +6,144 @@ using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; -namespace PortProxyGUI +namespace PortProxyGUI; + +public partial class SetProxy : Form { - public partial class SetProxy : Form + public readonly PortProxyGUI ParentWindow; + private string AutoTypeString { get; } + + private bool _updateMode; + private ListViewItem _listViewItem; + private Rule _itemRule; + + public SetProxy(PortProxyGUI parent) { - public readonly PortProxyGUI ParentWindow; - private string AutoTypeString { get; } + ParentWindow = parent; - private bool _updateMode; - private ListViewItem _listViewItem; - private Rule _itemRule; - - public SetProxy(PortProxyGUI parent) - { - ParentWindow = parent; - - InitializeComponent(); - - AutoTypeString = comboBox_Type.Text = comboBox_Type.Items.OfType<string>().First(); - var groupNames = ( - from g in parent.listViewProxies.Groups.OfType<ListViewGroup>() - let header = g.Header - where !header.IsNullOrWhiteSpace() - select header - ).ToArray(); - comboBox_Group.Items.AddRange(groupNames); - } - - public void UseNormalMode() - { - _updateMode = false; - _listViewItem = null; - _itemRule = null; - - comboBox_Type.Text = AutoTypeString; - comboBox_Group.Text = ""; - - textBox_ListenOn.Text = "*"; - textBox_ListenPort.Text = ""; - textBox_ConnectTo.Text = ""; - textBox_ConnectPort.Text = ""; - textBox_Comment.Text = ""; - } - - public void UseUpdateMode(ListViewItem item, Rule rule) - { - _updateMode = true; - _listViewItem = item; - - _itemRule = rule; - - comboBox_Type.Text = rule.Type; - comboBox_Group.Text = rule.Group; - - textBox_ListenOn.Text = rule.ListenOn; - textBox_ListenPort.Text = rule.ListenPort.ToString(); - textBox_ConnectTo.Text = rule.ConnectTo; - textBox_ConnectPort.Text = rule.ConnectPort.ToString(); - textBox_Comment.Text = rule.Comment; - } - - private bool IsIPv6(string ip) - { - return ip.IsMatch(new Regex(@"^[\dABCDEF]{2}(?::(?:[\dABCDEF]{2})){5}$")); - } - - private string GetPassType(string listenOn, string connectTo) - { - var from = IsIPv6(listenOn) ? "v6" : "v4"; - var to = IsIPv6(connectTo) ? "v6" : "v4"; - return $"{from}to{to}"; - } - - private void button_Set_Click(object sender, EventArgs e) - { - int listenPort, connectPort; - - try - { - listenPort = Rule.ParsePort(textBox_ListenPort.Text); - connectPort = Rule.ParsePort(textBox_ConnectPort.Text); - } - catch (NotSupportedException ex) - { - MessageBox.Show(ex.Message, "Invalid port", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - return; - } - - var rule = new Rule - { - Type = comboBox_Type.Text.Trim(), - ListenOn = textBox_ListenOn.Text.Trim(), - ListenPort = listenPort, - ConnectTo = textBox_ConnectTo.Text.Trim(), - ConnectPort = connectPort, - Comment = textBox_Comment.Text.Trim(), - Group = comboBox_Group.Text.Trim(), - }; - - if (rule.Type == AutoTypeString) rule.Type = GetPassType(rule.ListenOn, rule.ConnectTo); - - if (!new[] { "v4tov4", "v4tov6", "v6tov4", "v6tov6" }.Contains(rule.Type)) - { - MessageBox.Show($"Unknow type for ({rule.ListenOn} -> {rule.ConnectTo}).", "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - return; - } - - if (_updateMode) - { - var oldRule = Program.Database.GetRule(_itemRule.Type, _itemRule.ListenOn, _itemRule.ListenPort); - PortPorxyUtil.DeleteProxy(oldRule); - Program.Database.Remove(oldRule); - - PortPorxyUtil.AddOrUpdateProxy(rule); - Program.Database.Add(rule); - - ParentWindow.UpdateListViewItem(_listViewItem, rule, 1); - } - else - { - PortPorxyUtil.AddOrUpdateProxy(rule); - Program.Database.Add(rule); - - ParentWindow.RefreshProxyList(); - } - PortPorxyUtil.ParamChange(); - - Close(); - } - - private void SetProxyForm_Load(object sender, EventArgs e) - { - Top = ParentWindow.Top + (ParentWindow.Height - Height) / 2; - Left = ParentWindow.Left + (ParentWindow.Width - Width) / 2; - } - - private void SetProxyForm_FormClosing(object sender, FormClosingEventArgs e) - { - ParentWindow.SetProxyForm = null; - } + InitializeComponent(); + AutoTypeString = comboBox_Type.Text = comboBox_Type.Items.OfType<string>().First(); + var groupNames = ( + from g in parent.listViewProxies.Groups.OfType<ListViewGroup>() + let header = g.Header + where !header.IsNullOrWhiteSpace() + select header + ).ToArray(); + comboBox_Group.Items.AddRange(groupNames); } + + public void UseNormalMode() + { + _updateMode = false; + _listViewItem = null; + _itemRule = null; + + comboBox_Type.Text = AutoTypeString; + comboBox_Group.Text = ""; + + textBox_ListenOn.Text = "*"; + textBox_ListenPort.Text = ""; + textBox_ConnectTo.Text = ""; + textBox_ConnectPort.Text = ""; + textBox_Comment.Text = ""; + } + + public void UseUpdateMode(ListViewItem item, Rule rule) + { + _updateMode = true; + _listViewItem = item; + + _itemRule = rule; + + comboBox_Type.Text = rule.Type; + comboBox_Group.Text = rule.Group; + + textBox_ListenOn.Text = rule.ListenOn; + textBox_ListenPort.Text = rule.ListenPort.ToString(); + textBox_ConnectTo.Text = rule.ConnectTo; + textBox_ConnectPort.Text = rule.ConnectPort.ToString(); + textBox_Comment.Text = rule.Comment; + } + + private bool IsIPv6(string ip) + { + return ip.IsMatch(new Regex(@"^[\dABCDEF]{2}(?::(?:[\dABCDEF]{2})){5}$")); + } + + private string GetPassType(string listenOn, string connectTo) + { + var from = IsIPv6(listenOn) ? "v6" : "v4"; + var to = IsIPv6(connectTo) ? "v6" : "v4"; + return $"{from}to{to}"; + } + + private void button_Set_Click(object sender, EventArgs e) + { + int listenPort, connectPort; + + try + { + listenPort = Rule.ParsePort(textBox_ListenPort.Text); + connectPort = Rule.ParsePort(textBox_ConnectPort.Text); + } + catch (NotSupportedException ex) + { + MessageBox.Show(ex.Message, "Invalid port", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + return; + } + + var rule = new Rule + { + Type = comboBox_Type.Text.Trim(), + ListenOn = textBox_ListenOn.Text.Trim(), + ListenPort = listenPort, + ConnectTo = textBox_ConnectTo.Text.Trim(), + ConnectPort = connectPort, + Comment = textBox_Comment.Text.Trim(), + Group = comboBox_Group.Text.Trim(), + }; + + if (rule.Type == AutoTypeString) rule.Type = GetPassType(rule.ListenOn, rule.ConnectTo); + + if (!new[] { "v4tov4", "v4tov6", "v6tov4", "v6tov6" }.Contains(rule.Type)) + { + MessageBox.Show($"Unknow type for ({rule.ListenOn} -> {rule.ConnectTo}).", "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); + return; + } + + if (_updateMode) + { + var oldRule = Program.Database.GetRule(_itemRule.Type, _itemRule.ListenOn, _itemRule.ListenPort); + Util.DeleteProxy(oldRule); + Program.Database.Remove(oldRule); + + Util.AddOrUpdateProxy(rule); + Program.Database.Add(rule); + + ParentWindow.UpdateListViewItem(_listViewItem, rule, 1); + } + else + { + Util.AddOrUpdateProxy(rule); + Program.Database.Add(rule); + + ParentWindow.RefreshProxyList(); + } + Util.ParamChange(); + + Close(); + } + + private void SetProxyForm_Load(object sender, EventArgs e) + { + Top = ParentWindow.Top + (ParentWindow.Height - Height) / 2; + Left = ParentWindow.Left + (ParentWindow.Width - Width) / 2; + } + + private void SetProxyForm_FormClosing(object sender, FormClosingEventArgs e) + { + ParentWindow.SetProxyForm = null; + } + } diff --git a/PortProxyGUI/UI/ListViewColumnSorter.cs b/PortProxyGUI/UI/ListViewColumnSorter.cs index 2167af1..85b6561 100644 --- a/PortProxyGUI/UI/ListViewColumnSorter.cs +++ b/PortProxyGUI/UI/ListViewColumnSorter.cs @@ -1,111 +1,110 @@ using System.Collections; using System.Windows.Forms; -namespace PortProxyGUI.UI +namespace PortProxyGUI.UI; + +public class ListViewColumnSorter : IComparer { - public class ListViewColumnSorter : IComparer + /// <summary> + /// Specifies the column to be sorted + /// </summary> + private int ColumnToSort; + + /// <summary> + /// Specifies the order in which to sort (i.e. 'Ascending'). + /// </summary> + private SortOrder OrderOfSort; + + /// <summary> + /// Case insensitive comparer object + /// </summary> + private CaseInsensitiveComparer ObjectCompare; + + /// <summary> + /// Class constructor. Initializes various elements + /// </summary> + public ListViewColumnSorter() { - /// <summary> - /// Specifies the column to be sorted - /// </summary> - private int ColumnToSort; + // Initialize the column to '0' + ColumnToSort = 0; - /// <summary> - /// Specifies the order in which to sort (i.e. 'Ascending'). - /// </summary> - private SortOrder OrderOfSort; - - /// <summary> - /// Case insensitive comparer object - /// </summary> - private CaseInsensitiveComparer ObjectCompare; - - /// <summary> - /// Class constructor. Initializes various elements - /// </summary> - public ListViewColumnSorter() - { - // Initialize the column to '0' - ColumnToSort = 0; - - // Initialize the sort order to 'none' - OrderOfSort = SortOrder.None; - - // Initialize the CaseInsensitiveComparer object - ObjectCompare = new CaseInsensitiveComparer(); - } - - /// <summary> - /// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison. - /// </summary> - /// <param name="x">First object to be compared</param> - /// <param name="y">Second object to be compared</param> - /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns> - public int Compare(object x, object y) - { - int compareResult; - ListViewItem listviewX, listviewY; - - // Cast the objects to be compared to ListViewItem objects - listviewX = (ListViewItem)x; - listviewY = (ListViewItem)y; - - // Compare the two items - if (listviewX.SubItems[ColumnToSort].Tag?.ToString() == "Number" && listviewY.SubItems[ColumnToSort].Tag?.ToString() == "Number") - { - int.TryParse(listviewX.SubItems[ColumnToSort].Text, out var xint); - int.TryParse(listviewY.SubItems[ColumnToSort].Text, out var yint); - compareResult = ObjectCompare.Compare(xint, yint); - } - else compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text); - - // Calculate correct return value based on object comparison - if (OrderOfSort == SortOrder.Ascending) - { - // Ascending sort is selected, return normal result of compare operation - return compareResult; - } - else if (OrderOfSort == SortOrder.Descending) - { - // Descending sort is selected, return negative result of compare operation - return -compareResult; - } - else - { - // Return '0' to indicate they are equal - return 0; - } - } - - /// <summary> - /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0'). - /// </summary> - public int SortColumn - { - set - { - ColumnToSort = value; - } - get - { - return ColumnToSort; - } - } - - /// <summary> - /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending'). - /// </summary> - public SortOrder Order - { - set - { - OrderOfSort = value; - } - get - { - return OrderOfSort; - } - } + // Initialize the sort order to 'none' + OrderOfSort = SortOrder.None; + // Initialize the CaseInsensitiveComparer object + ObjectCompare = new CaseInsensitiveComparer(); } + + /// <summary> + /// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison. + /// </summary> + /// <param name="x">First object to be compared</param> + /// <param name="y">Second object to be compared</param> + /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns> + public int Compare(object x, object y) + { + int compareResult; + ListViewItem listviewX, listviewY; + + // Cast the objects to be compared to ListViewItem objects + listviewX = (ListViewItem)x; + listviewY = (ListViewItem)y; + + // Compare the two items + if (listviewX.SubItems[ColumnToSort].Tag?.ToString() == "Number" && listviewY.SubItems[ColumnToSort].Tag?.ToString() == "Number") + { + int.TryParse(listviewX.SubItems[ColumnToSort].Text, out var xint); + int.TryParse(listviewY.SubItems[ColumnToSort].Text, out var yint); + compareResult = ObjectCompare.Compare(xint, yint); + } + else compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text); + + // Calculate correct return value based on object comparison + if (OrderOfSort == SortOrder.Ascending) + { + // Ascending sort is selected, return normal result of compare operation + return compareResult; + } + else if (OrderOfSort == SortOrder.Descending) + { + // Descending sort is selected, return negative result of compare operation + return -compareResult; + } + else + { + // Return '0' to indicate they are equal + return 0; + } + } + + /// <summary> + /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0'). + /// </summary> + public int SortColumn + { + set + { + ColumnToSort = value; + } + get + { + return ColumnToSort; + } + } + + /// <summary> + /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending'). + /// </summary> + public SortOrder Order + { + set + { + OrderOfSort = value; + } + get + { + return OrderOfSort; + } + } + } diff --git a/PortProxyGUI/Utils/DnsUtil.cs b/PortProxyGUI/Utils/DnsUtil.cs index b6e3574..12501d1 100644 --- a/PortProxyGUI/Utils/DnsUtil.cs +++ b/PortProxyGUI/Utils/DnsUtil.cs @@ -1,15 +1,14 @@ using PortProxyGUI.Native; using System; -namespace PortProxyGUI.Utils -{ - internal class DnsUtil - { - public static void FlushCache() - { - var status = NativeMethods.DnsFlushResolverCache(); - if (status == 0) throw new InvalidOperationException("Flush DNS Cache failed."); - } +namespace PortProxyGUI.Utils; +internal class DnsUtil +{ + public static void FlushCache() + { + var status = NativeMethods.DnsFlushResolverCache(); + if (status == 0) throw new InvalidOperationException("Flush DNS Cache failed."); } + } diff --git a/PortProxyGUI/Utils/PortPorxyUtil.cs b/PortProxyGUI/Utils/PortPorxyUtil.cs deleted file mode 100644 index a956689..0000000 --- a/PortProxyGUI/Utils/PortPorxyUtil.cs +++ /dev/null @@ -1,149 +0,0 @@ -using Microsoft.Win32; -using PortProxyGUI.Data; -using PortProxyGUI.Native; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace PortProxyGUI.Utils -{ - public static class PortPorxyUtil - { - internal static readonly string ServiceName = "iphlpsvc"; - internal static readonly string ServiceFriendlyName = "IP Helper"; - - private static InvalidOperationException InvalidPortProxyType(string type) => new($"Invalid port proxy type ({type})."); - private static readonly string[] ProxyTypes = new[] { "v4tov4", "v4tov6", "v6tov4", "v6tov6" }; - - private static string GetKeyName(string type) - { - return $@"SYSTEM\CurrentControlSet\Services\PortProxy\{type}\tcp"; - } - - public static Rule[] GetProxies() - { - var ruleList = new List<Rule>(); - foreach (var type in ProxyTypes) - { - var keyName = GetKeyName(type); - var key = Registry.LocalMachine.OpenSubKey(keyName); - - if (key is not null) - { - foreach (var name in key.GetValueNames()) - { - var listenParts = name.Split('/'); - var listenOn = listenParts[0]; - if (!int.TryParse(listenParts[1], out var listenPort)) continue; - - var connectParts = key.GetValue(name).ToString().Split('/'); - var connectTo = connectParts[0]; - if (!int.TryParse(connectParts[1], out var connectPort)) continue; - - ruleList.Add(new Rule - { - Type = type, - ListenOn = listenOn, - ListenPort = listenPort, - ConnectTo = connectTo, - ConnectPort = connectPort, - }); - } - } - } - return ruleList.ToArray(); - } - - public static void AddOrUpdateProxy(Rule rule) - { - // $"netsh interface portproxy add {rule.Type} listenaddress={rule.ListenOn} listenport={rule.ListenPort} connectaddress={rule.ConnectTo} connectport={rule.ConnectPort}" - - if (!ProxyTypes.Contains(rule.Type)) throw InvalidPortProxyType(rule.Type); - - var keyName = GetKeyName(rule.Type); - var key = Registry.LocalMachine.OpenSubKey(keyName, true); - var name = $"{rule.ListenOn}/{rule.ListenPort}"; - var value = $"{rule.ConnectTo}/{rule.ConnectPort}"; - - if (key is null) Registry.LocalMachine.CreateSubKey(keyName); - key = Registry.LocalMachine.OpenSubKey(keyName, true); - key?.SetValue(name, value); - } - - public static void DeleteProxy(Rule rule) - { - // $"netsh interface portproxy delete {rule.Type} listenaddress={rule.ListenOn} listenport={rule.ListenPort}" - - if (!ProxyTypes.Contains(rule.Type)) throw InvalidPortProxyType(rule.Type); - - var keyName = GetKeyName(rule.Type); - var key = Registry.LocalMachine.OpenSubKey(keyName, true); - var name = $"{rule.ListenOn}/{rule.ListenPort}"; - - try - { - key?.DeleteValue(name); - } - catch { } - } - - public static bool IsServiceRunning() - { - var hManager = NativeMethods.OpenSCManager(null, null, (uint)GenericRights.GENERIC_READ); - if (hManager == IntPtr.Zero) throw new InvalidOperationException("Open SC Manager failed."); - - var hService = NativeMethods.OpenService(hManager, ServiceName, ServiceRights.SERVICE_QUERY_STATUS); - if (hService == IntPtr.Zero) - { - NativeMethods.CloseServiceHandle(hManager); - throw new InvalidOperationException($"Open Service ({ServiceName}) failed."); - } - - var status = new ServiceStatus(); - NativeMethods.QueryServiceStatus(hService, ref status); - - NativeMethods.CloseServiceHandle(hService); - NativeMethods.CloseServiceHandle(hManager); - - return status.dwCurrentState == ServiceState.SERVICE_RUNNING; - } - - public static void StartService() - { - var hManager = NativeMethods.OpenSCManager(null, null, (uint)GenericRights.GENERIC_READ | (uint)ScmRights.SC_MANAGER_CONNECT); - if (hManager == IntPtr.Zero) throw new InvalidOperationException("Open SC Manager failed."); - - var hService = NativeMethods.OpenService(hManager, ServiceName, ServiceRights.SERVICE_START); - if (hService == IntPtr.Zero) - { - NativeMethods.CloseServiceHandle(hManager); - throw new InvalidOperationException($"Open Service ({ServiceName}) failed."); - } - - NativeMethods.StartService(hService, 0, null); - - NativeMethods.CloseServiceHandle(hService); - NativeMethods.CloseServiceHandle(hManager); - } - - public static void ParamChange() - { - var hManager = NativeMethods.OpenSCManager(null, null, (uint)GenericRights.GENERIC_READ); - if (hManager == IntPtr.Zero) throw new InvalidOperationException("Open SC Manager failed."); - - var hService = NativeMethods.OpenService(hManager, ServiceName, ServiceRights.SERVICE_PAUSE_CONTINUE); - if (hService == IntPtr.Zero) - { - NativeMethods.CloseServiceHandle(hManager); - throw new InvalidOperationException($"Open Service ({ServiceName}) failed."); - } - - var status = new ServiceStatus(); - NativeMethods.ControlService(hService, ServiceControls.SERVICE_CONTROL_PARAMCHANGE, ref status); - - NativeMethods.CloseServiceHandle(hService); - NativeMethods.CloseServiceHandle(hManager); - } - - } -} diff --git a/PortProxyGUI/Utils/Util.cs b/PortProxyGUI/Utils/Util.cs new file mode 100644 index 0000000..07b5efa --- /dev/null +++ b/PortProxyGUI/Utils/Util.cs @@ -0,0 +1,148 @@ +using Microsoft.Win32; +using PortProxyGUI.Data; +using PortProxyGUI.Native; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace PortProxyGUI.Utils; + +public static class Util +{ + internal static readonly string ServiceName = "iphlpsvc"; + internal static readonly string ServiceFriendlyName = "IP Helper"; + + private static InvalidOperationException InvalidPortProxyType(string type) => new($"Invalid port proxy type ({type})."); + private static readonly string[] ProxyTypes = ["v4tov4", "v4tov6", "v6tov4", "v6tov6"]; + + private static string GetKeyName(string type) + { + return $@"SYSTEM\CurrentControlSet\Services\PortProxy\{type}\tcp"; + } + + public static Rule[] GetProxies() + { + var ruleList = new List<Rule>(); + foreach (var type in ProxyTypes) + { + var keyName = GetKeyName(type); + var key = Registry.LocalMachine.OpenSubKey(keyName); + + if (key is not null) + { + foreach (var name in key.GetValueNames()) + { + var listenParts = name.Split('/'); + var listenOn = listenParts[0]; + if (!int.TryParse(listenParts[1], out var listenPort)) continue; + + var connectParts = key.GetValue(name).ToString().Split('/'); + var connectTo = connectParts[0]; + if (!int.TryParse(connectParts[1], out var connectPort)) continue; + + ruleList.Add(new Rule + { + Type = type, + ListenOn = listenOn, + ListenPort = listenPort, + ConnectTo = connectTo, + ConnectPort = connectPort, + }); + } + } + } + return [.. ruleList]; + } + + public static void AddOrUpdateProxy(Rule rule) + { + // $"netsh interface portproxy add {rule.Type} listenaddress={rule.ListenOn} listenport={rule.ListenPort} connectaddress={rule.ConnectTo} connectport={rule.ConnectPort}" + + if (!ProxyTypes.Contains(rule.Type)) throw InvalidPortProxyType(rule.Type); + + var keyName = GetKeyName(rule.Type); + var key = Registry.LocalMachine.OpenSubKey(keyName, true); + var name = $"{rule.ListenOn}/{rule.ListenPort}"; + var value = $"{rule.ConnectTo}/{rule.ConnectPort}"; + + if (key is null) Registry.LocalMachine.CreateSubKey(keyName); + key = Registry.LocalMachine.OpenSubKey(keyName, true); + key?.SetValue(name, value); + } + + public static void DeleteProxy(Rule rule) + { + // $"netsh interface portproxy delete {rule.Type} listenaddress={rule.ListenOn} listenport={rule.ListenPort}" + + if (!ProxyTypes.Contains(rule.Type)) throw InvalidPortProxyType(rule.Type); + + var keyName = GetKeyName(rule.Type); + var key = Registry.LocalMachine.OpenSubKey(keyName, true); + var name = $"{rule.ListenOn}/{rule.ListenPort}"; + + try + { + key?.DeleteValue(name); + } + catch { } + } + + public static bool IsServiceRunning() + { + var hManager = NativeMethods.OpenSCManager(null, null, (uint)GenericRights.GENERIC_READ); + if (hManager == IntPtr.Zero) throw new InvalidOperationException("Open SC Manager failed."); + + var hService = NativeMethods.OpenService(hManager, ServiceName, ServiceRights.SERVICE_QUERY_STATUS); + if (hService == IntPtr.Zero) + { + NativeMethods.CloseServiceHandle(hManager); + throw new InvalidOperationException($"Open Service ({ServiceName}) failed."); + } + + var status = new ServiceStatus(); + NativeMethods.QueryServiceStatus(hService, ref status); + + NativeMethods.CloseServiceHandle(hService); + NativeMethods.CloseServiceHandle(hManager); + + return status.dwCurrentState == ServiceState.SERVICE_RUNNING; + } + + public static void StartService() + { + var hManager = NativeMethods.OpenSCManager(null, null, (uint)GenericRights.GENERIC_READ | (uint)ScmRights.SC_MANAGER_CONNECT); + if (hManager == IntPtr.Zero) throw new InvalidOperationException("Open SC Manager failed."); + + var hService = NativeMethods.OpenService(hManager, ServiceName, ServiceRights.SERVICE_START); + if (hService == IntPtr.Zero) + { + NativeMethods.CloseServiceHandle(hManager); + throw new InvalidOperationException($"Open Service ({ServiceName}) failed."); + } + + NativeMethods.StartService(hService, 0, null); + + NativeMethods.CloseServiceHandle(hService); + NativeMethods.CloseServiceHandle(hManager); + } + + public static void ParamChange() + { + var hManager = NativeMethods.OpenSCManager(null, null, (uint)GenericRights.GENERIC_READ); + if (hManager == IntPtr.Zero) throw new InvalidOperationException("Open SC Manager failed."); + + var hService = NativeMethods.OpenService(hManager, ServiceName, ServiceRights.SERVICE_PAUSE_CONTINUE); + if (hService == IntPtr.Zero) + { + NativeMethods.CloseServiceHandle(hManager); + throw new InvalidOperationException($"Open Service ({ServiceName}) failed."); + } + + var status = new ServiceStatus(); + NativeMethods.ControlService(hService, ServiceControls.SERVICE_CONTROL_PARAMCHANGE, ref status); + + NativeMethods.CloseServiceHandle(hService); + NativeMethods.CloseServiceHandle(hManager); + } + +}