From 3cbd5af9a3b8a06920ea09c7b4d572674e9c67c3 Mon Sep 17 00:00:00 2001 From: ChsBuffer <33744752+chsbuffer@users.noreply.github.com> Date: Sat, 27 Mar 2021 17:40:18 +0800 Subject: [PATCH] Extract TagItem class, Update Nullable --- Netch/Controllers/MainController.cs | 2 +- Netch/Forms/LogForm.cs | 14 +- Netch/Forms/MainForm.cs | 20 ++- Netch/Forms/Mode/Process.cs | 5 +- Netch/Forms/Mode/Process.resx | 120 ++++++++++++++++++ Netch/Forms/Mode/Route.cs | 33 +---- Netch/Forms/SettingForm.cs | 23 ++-- Netch/Models/GitHubRelease/SuffixVersion.cs | 7 +- Netch/Models/GitHubRelease/VersionComparer.cs | 11 +- Netch/Models/GitHubRelease/VersionUtil.cs | 2 +- Netch/Models/TagItem.cs | 19 +++ Netch/Utils/AdapterUtils.cs | 4 +- Netch/Utils/ServerHelper.cs | 2 +- Netch/Utils/ShareLink.cs | 2 +- Netch/Utils/Utils.cs | 8 +- Netch/Utils/WebUtil.cs | 20 +-- Netch/Utils/i18N.cs | 2 +- 17 files changed, 214 insertions(+), 80 deletions(-) create mode 100644 Netch/Forms/Mode/Process.resx create mode 100644 Netch/Models/TagItem.cs diff --git a/Netch/Controllers/MainController.cs b/Netch/Controllers/MainController.cs index ea618040..ec9f90f8 100644 --- a/Netch/Controllers/MainController.cs +++ b/Netch/Controllers/MainController.cs @@ -190,7 +190,7 @@ namespace Netch.Controllers string fileName; try { - fileName = p.MainModule!.FileName; + fileName = p.MainModule?.FileName ?? throw new Exception(); // TODO what's this exception? } catch (Exception e) { diff --git a/Netch/Forms/LogForm.cs b/Netch/Forms/LogForm.cs index 8afb72d5..38329d74 100644 --- a/Netch/Forms/LogForm.cs +++ b/Netch/Forms/LogForm.cs @@ -16,13 +16,13 @@ namespace Netch.Forms _parent = parent; } - protected override void OnLoad(EventArgs e) + protected override void OnLoad(EventArgs? e) { base.OnLoad(e); Parent_Move(null!, null!); } - private void Parent_Move(object sender, EventArgs e) + private void Parent_Move(object? sender, EventArgs? e) { var cl = Location; var fl = _parent.Location; @@ -32,7 +32,7 @@ namespace Netch.Forms Location = cl; } - private void Parent_Activated(object sender, EventArgs e) + private void Parent_Activated(object? sender, EventArgs? e) { SetWindowPos(Handle, HWND.HWND_TOPMOST, @@ -51,7 +51,7 @@ namespace Netch.Forms SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_SHOWWINDOW); } - private void richTextBox1_TextChanged(object sender, System.EventArgs e) + private void richTextBox1_TextChanged(object? sender, EventArgs? e) { if (!checkBox1.Checked) return; @@ -60,19 +60,19 @@ namespace Netch.Forms richTextBox1.ScrollToCaret(); } - private void Notifycation_Load(object sender, EventArgs e) + private void Notifycation_Load(object? sender, EventArgs? e) { _parent.LocationChanged += Parent_Move; _parent.SizeChanged += Parent_Move; _parent.Activated += Parent_Activated; } - protected override void OnClosing(CancelEventArgs e) + protected override void OnClosing(CancelEventArgs? e) { _parent.Activated -= Parent_Activated; _parent.LocationChanged -= Parent_Move; _parent.SizeChanged -= Parent_Move; - base.OnClosing(e); + base.OnClosing(e!); } } } \ No newline at end of file diff --git a/Netch/Forms/MainForm.cs b/Netch/Forms/MainForm.cs index 4af55046..63e7ef01 100644 --- a/Netch/Forms/MainForm.cs +++ b/Netch/Forms/MainForm.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.IO; using System.Linq; @@ -234,8 +235,12 @@ namespace Netch.Forms } } - private void AddServerToolStripMenuItem_Click(object sender, EventArgs e) + private void AddServerToolStripMenuItem_Click([NotNull] object? sender, EventArgs? e) { + if (sender == null) + throw new ArgumentNullException(nameof(sender)); + + // TODO get Util from Tag var s = ((ToolStripMenuItem) sender).Text; var start = s.IndexOf("[", StringComparison.Ordinal) + 1; @@ -321,12 +326,12 @@ namespace Netch.Forms { Task.Run(() => { - void OnNewVersionNotFound(object o, EventArgs args) + void OnNewVersionNotFound(object? o, EventArgs? args) { NotifyTip(i18N.Translate("Already latest version")); } - void OnNewVersionFoundFailed(object o, EventArgs args) + void OnNewVersionFoundFailed(object? o, EventArgs? args) { NotifyTip(i18N.Translate("New version found failed"), info: false); } @@ -661,7 +666,7 @@ namespace Netch.Forms ServerHelper.DelayTestHelper.TestDelayFinished += OnTestDelayFinished; _ = Task.Run(ServerHelper.DelayTestHelper.TestAllDelay); - void OnTestDelayFinished(object o1, EventArgs e1) + void OnTestDelayFinished(object? o1, EventArgs? e1) { Refresh(); @@ -900,8 +905,11 @@ namespace Netch.Forms return profile; } - private async void ProfileButton_Click(object sender, EventArgs e) + private async void ProfileButton_Click([NotNull] object? sender, EventArgs? e) { + if (sender == null) + throw new ArgumentNullException(nameof(sender)); + var profileButton = (Button) sender; var profile = (Profile?) profileButton.Tag; var index = ProfileTable.Controls.IndexOf(profileButton); @@ -1317,7 +1325,7 @@ namespace Netch.Forms UpdateChecker.NewVersionFound -= OnUpdateCheckerOnNewVersionFound; } - void OnUpdateCheckerOnNewVersionFound(object o, EventArgs eventArgs) + void OnUpdateCheckerOnNewVersionFound(object? o, EventArgs? eventArgs) { NotifyTip($"{i18N.Translate(@"New version available", ": ")}{UpdateChecker.LatestVersionNumber}"); NewVersionLabel.Text = i18N.Translate("New version available"); diff --git a/Netch/Forms/Mode/Process.cs b/Netch/Forms/Mode/Process.cs index c22d4fea..832718ed 100644 --- a/Netch/Forms/Mode/Process.cs +++ b/Netch/Forms/Mode/Process.cs @@ -149,7 +149,7 @@ namespace Netch.Forms.Mode Close(); } - private void RemarkTextBox_TextChanged(object sender, EventArgs e) + private void RemarkTextBox_TextChanged(object? sender, EventArgs? e) { BeginInvoke(new Action(() => { @@ -195,7 +195,8 @@ namespace Netch.Forms.Mode foreach (string dir in Directory.GetDirectories(directory)) ScanDirectory(dir, list, maxCount); - list.AddRange(Directory.GetFiles(directory).Select(Path.GetFileName).Where(s => s.EndsWith(".exe")).Select(s => s.ToRegexString())); + list.AddRange( + Directory.GetFiles(directory).Select(s => Path.GetFileName(s)).Where(s => s.EndsWith(".exe")).Select(s => s.ToRegexString())); if (maxCount != 0 && list.Count > maxCount) throw new Exception("The number of results is greater than maxCount"); diff --git a/Netch/Forms/Mode/Process.resx b/Netch/Forms/Mode/Process.resx new file mode 100644 index 00000000..1af7de15 --- /dev/null +++ b/Netch/Forms/Mode/Process.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Netch/Forms/Mode/Route.cs b/Netch/Forms/Mode/Route.cs index b99195cc..7a6dd087 100644 --- a/Netch/Forms/Mode/Route.cs +++ b/Netch/Forms/Mode/Route.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Windows.Forms; +using Netch.Models; using Netch.Properties; using Netch.Utils; @@ -8,26 +9,7 @@ namespace Netch.Forms.Mode { public partial class Route : Form { - class Item - { - private string _text; - - public Item(int value, string text) - { - _text = text; - Value = value; - } - - public string Text - { - get => i18N.Translate(_text); - set => _text = value; - } - - public int Value { get; set; } - } - - private readonly Item[] _items = {new(1, "Proxy Rule IPs"), new(2, "Bypass Rule IPs")}; + private readonly TagItem[] _items = {new(1, "Proxy Rule IPs"), new(2, "Bypass Rule IPs")}; private readonly Models.Mode? _mode; @@ -41,8 +23,8 @@ namespace Netch.Forms.Mode InitializeComponent(); Icon = Resources.icon; comboBox1.DataSource = _items; - comboBox1.ValueMember = "Value"; - comboBox1.DisplayMember = "Text"; + comboBox1.ValueMember = nameof(TagItem.Value); + comboBox1.DisplayMember = nameof(TagItem.Text); } private void Route_Load(object sender, EventArgs e) @@ -110,12 +92,9 @@ namespace Netch.Forms.Mode Close(); } - private void RemarkTextBox_TextChanged(object sender, EventArgs e) + private void RemarkTextBox_TextChanged(object? sender, EventArgs? e) { - BeginInvoke(new Action(() => - { - FilenameTextBox.Text = ModeEditorUtils.GetCustomModeRelativePath(RemarkTextBox.Text); - })); + BeginInvoke(new Action(() => { FilenameTextBox.Text = ModeEditorUtils.GetCustomModeRelativePath(RemarkTextBox.Text); })); } } } \ No newline at end of file diff --git a/Netch/Forms/SettingForm.cs b/Netch/Forms/SettingForm.cs index 93d85868..12502953 100644 --- a/Netch/Forms/SettingForm.cs +++ b/Netch/Forms/SettingForm.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; using System.Windows.Forms; +using Netch.Models; using Netch.Properties; using Netch.Utils; @@ -99,10 +100,7 @@ namespace Netch.Forms BindTextBox(AclAddrTextBox, s => true, s => Global.Settings.ACL = s, Global.Settings.ACL); - BindListComboBox(LanguageComboBox, - o => Global.Settings.Language = o.ToString(), - i18N.GetTranslateList().Cast().ToArray(), - Global.Settings.Language); + BindListComboBox(LanguageComboBox, o => Global.Settings.Language = o.ToString(), i18N.GetTranslateList(), Global.Settings.Language); #endregion @@ -128,7 +126,7 @@ namespace Netch.Forms BindListComboBox(ProcessProxyProtocolComboBox, s => Global.Settings.ProcessProxyProtocol = (PortType) Enum.Parse(typeof(PortType), s.ToString(), false), - Enum.GetNames(typeof(PortType)).Cast().ToArray(), + Enum.GetNames(typeof(PortType)), Global.Settings.ProcessProxyProtocol.ToString()); #endregion @@ -324,14 +322,19 @@ namespace Netch.Forms _saveActions.Add(control, c => save.Invoke(((RadioButton) c).Checked)); } - private void BindListComboBox(ComboBox control, Action save, object[] values, object value, string propertyName = "SelectedItem") + private void BindListComboBox(ComboBox comboBox, Action save, IEnumerable values, T value) where T : notnull { - if (control.DropDownStyle != ComboBoxStyle.DropDownList) + if (comboBox.DropDownStyle != ComboBoxStyle.DropDownList) throw new ArgumentOutOfRangeException(); - control.Items.AddRange(values); - _saveActions.Add(control, c => save.Invoke(((ComboBox) c).SelectedItem)); - Load += (_, _) => { control.SelectedItem = value; }; + var tagItems = values.Select(o => new TagItem(o, o.ToString()!)).ToArray(); + comboBox.Items.AddRange(tagItems.Cast().ToArray()); + + comboBox.ValueMember = nameof(TagItem.Value); + comboBox.DisplayMember = nameof(TagItem.Text); + + _saveActions.Add(comboBox, c => save.Invoke(((TagItem) ((ComboBox) c).SelectedItem).Value)); + Load += (_, _) => { comboBox.SelectedItem = tagItems.SingleOrDefault(t => t.Value.Equals(value)); }; } private void BindComboBox(ComboBox control, Func check, Action save, string value, object[]? values = null) diff --git a/Netch/Models/GitHubRelease/SuffixVersion.cs b/Netch/Models/GitHubRelease/SuffixVersion.cs index 58c58cef..92164863 100644 --- a/Netch/Models/GitHubRelease/SuffixVersion.cs +++ b/Netch/Models/GitHubRelease/SuffixVersion.cs @@ -16,8 +16,11 @@ namespace Netch.Models.GitHubRelease Suffix = suffix; } - public static SuffixVersion Parse(string input) + public static SuffixVersion Parse(string? input) { + if (input == null) + throw new ArgumentNullException(nameof(input)); + var split = input.Split('-'); var dotNetVersion = Version.Parse(split[0]); var preRelease = split.ElementAtOrDefault(1) ?? string.Empty; @@ -39,7 +42,7 @@ namespace Netch.Models.GitHubRelease } } - public int CompareTo(object obj) + public int CompareTo(object? obj) { if (obj is not SuffixVersion version) throw new ArgumentOutOfRangeException(); diff --git a/Netch/Models/GitHubRelease/VersionComparer.cs b/Netch/Models/GitHubRelease/VersionComparer.cs index 368ad20c..2cd67630 100644 --- a/Netch/Models/GitHubRelease/VersionComparer.cs +++ b/Netch/Models/GitHubRelease/VersionComparer.cs @@ -1,11 +1,18 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; namespace Netch.Models.GitHubRelease { public class VersionComparer : IComparer { - public int Compare(object x, object y) + public int Compare(object? x, object? y) { + if (x == null) + throw new ArgumentNullException(nameof(x)); + + if (y == null) + throw new ArgumentNullException(nameof(y)); + return VersionUtil.CompareVersion(x.ToString(), y.ToString()); } } diff --git a/Netch/Models/GitHubRelease/VersionUtil.cs b/Netch/Models/GitHubRelease/VersionUtil.cs index 3d5ba3dc..39eb2f46 100644 --- a/Netch/Models/GitHubRelease/VersionUtil.cs +++ b/Netch/Models/GitHubRelease/VersionUtil.cs @@ -23,7 +23,7 @@ namespace Netch.Models.GitHubRelease /// =0:versions are equal /// >0:version1 is greater /// <0:version2 is greater - public static int CompareVersion(string v1, string v2) + public static int CompareVersion(string? v1, string? v2) { var version1 = SuffixVersion.Parse(v1); var version2 = SuffixVersion.Parse(v2); diff --git a/Netch/Models/TagItem.cs b/Netch/Models/TagItem.cs new file mode 100644 index 00000000..96afbcbe --- /dev/null +++ b/Netch/Models/TagItem.cs @@ -0,0 +1,19 @@ +using Netch.Utils; + +namespace Netch.Models +{ + internal class TagItem + { + private readonly string _text; + + public TagItem(T value, string text) + { + _text = text; + Value = value; + } + + public string Text => i18N.Translate(_text); + + public T Value { get; } + } +} \ No newline at end of file diff --git a/Netch/Utils/AdapterUtils.cs b/Netch/Utils/AdapterUtils.cs index cb1b5df4..82758103 100644 --- a/Netch/Utils/AdapterUtils.cs +++ b/Netch/Utils/AdapterUtils.cs @@ -17,9 +17,7 @@ namespace Netch.Utils /// 适配器名称 public static string GetName(string componentId) { - var registry = Registry.LocalMachine.OpenSubKey($"{NETWORK_KEY}\\{componentId}\\Connection"); - - return registry.GetValue("Name", "").ToString(); + return Registry.LocalMachine.OpenSubKey($"{NETWORK_KEY}\\{componentId}\\Connection")?.GetValue("Name")?.ToString() ?? ""; } public static string? GetAdapterId(params string[] componentIds) diff --git a/Netch/Utils/ServerHelper.cs b/Netch/Utils/ServerHelper.cs index eef6b921..948bccde 100644 --- a/Netch/Utils/ServerHelper.cs +++ b/Netch/Utils/ServerHelper.cs @@ -17,7 +17,7 @@ namespace Netch.Utils .GetExportedTypes() .Where(type => type.GetInterfaces().Contains(typeof(IServerUtil))); - ServerUtils = serversUtilsTypes.Select(t => (IServerUtil) Activator.CreateInstance(t)).OrderBy(util => util.Priority); + ServerUtils = serversUtilsTypes.Select(t => (IServerUtil) Activator.CreateInstance(t)!).OrderBy(util => util.Priority); } public static Type GetTypeByTypeName(string typeName) diff --git a/Netch/Utils/ShareLink.cs b/Netch/Utils/ShareLink.cs index 6caf8eb4..50baca07 100644 --- a/Netch/Utils/ShareLink.cs +++ b/Netch/Utils/ShareLink.cs @@ -32,7 +32,7 @@ namespace Netch.Utils try { - list.AddRange(JsonSerializer.Deserialize>(text) + list.AddRange(JsonSerializer.Deserialize>(text)! .Select(server => new Shadowsocks { Hostname = server.server, diff --git a/Netch/Utils/Utils.cs b/Netch/Utils/Utils.cs index 0194b641..f6da6a86 100644 --- a/Netch/Utils/Utils.cs +++ b/Netch/Utils/Utils.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.IO; using System.Linq; @@ -116,7 +117,10 @@ namespace Netch.Utils public static string GetFileVersion(string file) { - return File.Exists(file) ? FileVersionInfo.GetVersionInfo(file).FileVersion : string.Empty; + if (File.Exists(file)) + return FileVersionInfo.GetVersionInfo(file).FileVersion ?? ""; + + return ""; } public static void DrawCenterComboBox(object sender, DrawItemEventArgs e) @@ -223,7 +227,7 @@ namespace Netch.Utils } } - public static async Task ProcessRunHiddenAsync(string fileName, string? arguments = null, bool print = true) + public static async Task ProcessRunHiddenAsync(string fileName, string arguments = "", bool print = true) { var p = new Process { diff --git a/Netch/Utils/WebUtil.cs b/Netch/Utils/WebUtil.cs index 5757d74b..acb400d5 100644 --- a/Netch/Utils/WebUtil.cs +++ b/Netch/Utils/WebUtil.cs @@ -1,6 +1,5 @@ using System.IO; using System.Net; -using System.Net.Sockets; using System.Text; using System.Threading.Tasks; @@ -30,13 +29,6 @@ namespace Netch.Utils return req; } - public static IPEndPoint BestLocalEndPoint(IPEndPoint remoteIPEndPoint) - { - var testSocket = new Socket(remoteIPEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); - testSocket.Connect(remoteIPEndPoint); - return (IPEndPoint) testSocket.LocalEndPoint; - } - /// /// 异步下载 /// @@ -44,9 +36,9 @@ namespace Netch.Utils /// public static async Task DownloadBytesAsync(HttpWebRequest req) { - using var webResponse = (HttpWebResponse) await req.GetResponseAsync(); - using var memoryStream = new MemoryStream(); - using var input = webResponse.GetResponseStream(); + using var webResponse = req.GetResponseAsync(); + await using var memoryStream = new MemoryStream(); + await using var input = webResponse.Result.GetResponseStream(); await input.CopyToAsync(memoryStream); return memoryStream.ToArray(); @@ -77,7 +69,7 @@ namespace Netch.Utils public static async Task DownloadStringAsync(HttpWebRequest req, string encoding = "UTF-8") { using var webResponse = await req.GetResponseAsync(); - using var responseStream = webResponse.GetResponseStream(); + await using var responseStream = webResponse.GetResponseStream(); using var streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding)); return await streamReader.ReadToEndAsync(); @@ -92,8 +84,8 @@ namespace Netch.Utils public static async Task DownloadFileAsync(HttpWebRequest req, string fileFullPath) { using var webResponse = (HttpWebResponse) await req.GetResponseAsync(); - using var input = webResponse.GetResponseStream(); - using var fileStream = File.OpenWrite(fileFullPath); + await using var input = webResponse.GetResponseStream(); + await using var fileStream = File.OpenWrite(fileFullPath); await input.CopyToAsync(fileStream); fileStream.Flush(); diff --git a/Netch/Utils/i18N.cs b/Netch/Utils/i18N.cs index 9062e088..0248a6c8 100644 --- a/Netch/Utils/i18N.cs +++ b/Netch/Utils/i18N.cs @@ -88,7 +88,7 @@ namespace Netch.Utils var a = new StringBuilder(); foreach (var t in text) if (t is string) - a.Append(Data.Contains(t) ? Data[t].ToString() : t); + a.Append(Data[t]?.ToString() ?? t); else a.Append(t);