diff --git a/v2rayN/v2rayN/Base/HttpClientHelper.cs b/v2rayN/v2rayN/Base/HttpClientHelper.cs index a3bacb5d..06c67160 100644 --- a/v2rayN/v2rayN/Base/HttpClientHelper.cs +++ b/v2rayN/v2rayN/Base/HttpClientHelper.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; @@ -58,7 +57,7 @@ namespace v2rayN.Base HttpResponseMessage response = await client.GetAsync(url, token); if (!response.IsSuccessStatusCode) { - throw new Exception(string.Format("The request returned with HTTP status code {0}", response.StatusCode)); + throw new Exception($"The request returned with HTTP status code {response.StatusCode}"); } return await response.Content.ReadAsStringAsync(); } @@ -77,11 +76,11 @@ namespace v2rayN.Base { if (string.IsNullOrEmpty(url)) { - throw new ArgumentNullException("url"); + throw new ArgumentNullException(nameof(url)); } if (string.IsNullOrEmpty(fileName)) { - throw new ArgumentNullException("fileName"); + throw new ArgumentNullException(nameof(fileName)); } if (File.Exists(fileName)) { @@ -92,59 +91,55 @@ namespace v2rayN.Base if (!response.IsSuccessStatusCode) { - throw new Exception(string.Format("The request returned with HTTP status code {0}", response.StatusCode)); + throw new Exception($"The request returned with HTTP status code {response.StatusCode}"); } - var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; + var total = response.Content.Headers.ContentLength ?? -1L; var canReportProgress = total != -1 && progress != null; - using (var stream = await response.Content.ReadAsStreamAsync()) + using var stream = await response.Content.ReadAsStreamAsync(); + using var file = File.Create(fileName); + var totalRead = 0L; + var buffer = new byte[1024 * 1024]; + var isMoreToRead = true; + var progressPercentage = 0; + + do { - using (var file = File.Create(fileName)) + token.ThrowIfCancellationRequested(); + + var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); + + if (read == 0) { - var totalRead = 0L; - var buffer = new byte[1024 * 1024]; - var isMoreToRead = true; - var progressPercentage = 0; + isMoreToRead = false; + } + else + { + var data = new byte[read]; + buffer.ToList().CopyTo(0, data, 0, read); - do - { - token.ThrowIfCancellationRequested(); + // TODO: put here the code to write the file to disk + await file.WriteAsync(data, 0, read, token); - var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); + totalRead += read; - if (read == 0) - { - isMoreToRead = false; - } - else - { - var data = new byte[read]; - buffer.ToList().CopyTo(0, data, 0, read); - - // TODO: put here the code to write the file to disk - file.Write(data, 0, read); - - totalRead += read; - - if (canReportProgress) - { - var percent = Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100); - if (progressPercentage != percent && percent % 10 == 0) - { - progressPercentage = percent; - progress.Report(percent); - } - } - } - } while (isMoreToRead); - file.Close(); if (canReportProgress) { - progress.Report(101); - + var percent = Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100); + if (progressPercentage != percent && percent % 10 == 0) + { + progressPercentage = percent; + progress.Report(percent); + } } } + } while (isMoreToRead); + file.Close(); + if (canReportProgress) + { + progress.Report(101); + } } @@ -152,68 +147,66 @@ namespace v2rayN.Base { if (string.IsNullOrEmpty(url)) { - throw new ArgumentNullException("url"); + throw new ArgumentNullException(nameof(url)); } var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); if (!response.IsSuccessStatusCode) { - throw new Exception(string.Format("The request returned with HTTP status code {0}", response.StatusCode)); + throw new Exception($"The request returned with HTTP status code {response.StatusCode}"); } //var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L; //var canReportProgress = total != -1 && progress != null; - using (var stream = await response.Content.ReadAsStreamAsync()) + using var stream = await response.Content.ReadAsStreamAsync(); + var totalRead = 0L; + var buffer = new byte[1024 * 64]; + var isMoreToRead = true; + string progressSpeed = string.Empty; + DateTime totalDatetime = DateTime.Now; + + do { - var totalRead = 0L; - var buffer = new byte[1024 * 64]; - var isMoreToRead = true; - string progressSpeed = string.Empty; - DateTime totalDatetime = DateTime.Now; - - do + if (token.IsCancellationRequested) { - if (token.IsCancellationRequested) + if (totalRead > 0) { - if (totalRead > 0) - { - return; - } - else - { - token.ThrowIfCancellationRequested(); - } - } - - var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); - - if (read == 0) - { - isMoreToRead = false; + return; } else { - var data = new byte[read]; - buffer.ToList().CopyTo(0, data, 0, read); + token.ThrowIfCancellationRequested(); + } + } - // TODO: - totalRead += read; + var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); - TimeSpan ts = (DateTime.Now - totalDatetime); - var speed = (totalRead * 1d / ts.TotalMilliseconds / 1000).ToString("#0.0"); - if (progress != null) + if (read == 0) + { + isMoreToRead = false; + } + else + { + var data = new byte[read]; + buffer.ToList().CopyTo(0, data, 0, read); + + // TODO: + totalRead += read; + + TimeSpan ts = (DateTime.Now - totalDatetime); + var speed = (totalRead * 1d / ts.TotalMilliseconds / 1000).ToString("#0.0"); + if (progress != null) + { + if (progressSpeed != speed) { - if (progressSpeed != speed) - { - progressSpeed = speed; - progress.Report(speed); - } + progressSpeed = speed; + progress.Report(speed); } } - } while (isMoreToRead); - } + } + } while (isMoreToRead); } } diff --git a/v2rayN/v2rayN/Base/ListViewFlickerFree.cs b/v2rayN/v2rayN/Base/ListViewFlickerFree.cs index 94e803e9..9ac970cc 100644 --- a/v2rayN/v2rayN/Base/ListViewFlickerFree.cs +++ b/v2rayN/v2rayN/Base/ListViewFlickerFree.cs @@ -76,14 +76,7 @@ namespace v2rayN.Base Rectangle itemBounds = GetItemRect(targetIndex); EnsureVisible(targetIndex); - if (targetPoint.Y > itemBounds.Top + (itemBounds.Height / 2)) - { - InsertionMark.AppearsAfterItem = true; - } - else - { - InsertionMark.AppearsAfterItem = false; - } + InsertionMark.AppearsAfterItem = targetPoint.Y > itemBounds.Top + (itemBounds.Height / 2); } InsertionMark.Index = targetIndex; } diff --git a/v2rayN/v2rayN/Base/StringEx.cs b/v2rayN/v2rayN/Base/StringEx.cs index 40544106..d7f95650 100644 --- a/v2rayN/v2rayN/Base/StringEx.cs +++ b/v2rayN/v2rayN/Base/StringEx.cs @@ -36,8 +36,7 @@ namespace v2rayN.Base public static IEnumerable NonWhiteSpaceLines(this TextReader reader) { - string line; - while ((line = reader.ReadLine()) != null) + while (reader.ReadLine() is { } line) { if (line.IsWhiteSpace()) continue; yield return line; diff --git a/v2rayN/v2rayN/Forms/AddServer2Form.cs b/v2rayN/v2rayN/Forms/AddServer2Form.cs index 823f0137..3b419813 100644 --- a/v2rayN/v2rayN/Forms/AddServer2Form.cs +++ b/v2rayN/v2rayN/Forms/AddServer2Form.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.IO; using System.Windows.Forms; using v2rayN.Handler; using v2rayN.Mode; diff --git a/v2rayN/v2rayN/Forms/AddServerForm.cs b/v2rayN/v2rayN/Forms/AddServerForm.cs index c0f4459f..62f73d6c 100644 --- a/v2rayN/v2rayN/Forms/AddServerForm.cs +++ b/v2rayN/v2rayN/Forms/AddServerForm.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Windows.Forms; using v2rayN.Handler; using v2rayN.Mode; diff --git a/v2rayN/v2rayN/Forms/BaseServerForm.cs b/v2rayN/v2rayN/Forms/BaseServerForm.cs index 9618c480..4abc06c8 100644 --- a/v2rayN/v2rayN/Forms/BaseServerForm.cs +++ b/v2rayN/v2rayN/Forms/BaseServerForm.cs @@ -1,6 +1,4 @@ -using System; -using System.Windows.Forms; -using v2rayN.Mode; +using v2rayN.Mode; namespace v2rayN.Forms { diff --git a/v2rayN/v2rayN/Forms/GlobalHotkeySettingForm.cs b/v2rayN/v2rayN/Forms/GlobalHotkeySettingForm.cs index 0bf81688..f39ef1e4 100644 --- a/v2rayN/v2rayN/Forms/GlobalHotkeySettingForm.cs +++ b/v2rayN/v2rayN/Forms/GlobalHotkeySettingForm.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; -using v2rayN.Base; using v2rayN.Handler; using v2rayN.Mode; using v2rayN.Resx; @@ -18,10 +17,7 @@ namespace v2rayN.Forms private void GlobalHotkeySettingForm_Load(object sender, EventArgs e) { - if (config.globalHotkeys == null) - { - config.globalHotkeys = new List(); - } + config.globalHotkeys ??= new List(); foreach (EGlobalHotkey it in Enum.GetValues(typeof(EGlobalHotkey))) { diff --git a/v2rayN/v2rayN/Forms/GroupSettingControl.cs b/v2rayN/v2rayN/Forms/GroupSettingControl.cs index 07abc73d..66b25794 100644 --- a/v2rayN/v2rayN/Forms/GroupSettingControl.cs +++ b/v2rayN/v2rayN/Forms/GroupSettingControl.cs @@ -1,7 +1,6 @@ using System; using System.Windows.Forms; using v2rayN.Base; -using v2rayN.Handler; using v2rayN.Mode; namespace v2rayN.Forms diff --git a/v2rayN/v2rayN/Forms/GroupSettingForm.cs b/v2rayN/v2rayN/Forms/GroupSettingForm.cs index 77860153..80ae01b6 100644 --- a/v2rayN/v2rayN/Forms/GroupSettingForm.cs +++ b/v2rayN/v2rayN/Forms/GroupSettingForm.cs @@ -18,10 +18,7 @@ namespace v2rayN.Forms private void GroupSettingForm_Load(object sender, EventArgs e) { - if (config.groupItem == null) - { - config.groupItem = new List(); - } + config.groupItem ??= new List(); RefreshGroupsView(); } diff --git a/v2rayN/v2rayN/Forms/MainForm.cs b/v2rayN/v2rayN/Forms/MainForm.cs index 59c8918b..cc36193a 100644 --- a/v2rayN/v2rayN/Forms/MainForm.cs +++ b/v2rayN/v2rayN/Forms/MainForm.cs @@ -63,14 +63,7 @@ namespace v2rayN.Forms private void MainForm_VisibleChanged(object sender, EventArgs e) { if (statistics == null || !statistics.Enable) return; - if ((sender as Form).Visible) - { - statistics.UpdateUI = true; - } - else - { - statistics.UpdateUI = false; - } + statistics.UpdateUI = (sender as Form).Visible; } private void MainForm_Shown(object sender, EventArgs e) @@ -232,10 +225,7 @@ namespace v2rayN.Forms .ToList(); ConfigHandler.SetDefaultServer(config, lstVmess); - BeginInvoke(new Action(() => - { - RefreshServersView(); - })); + BeginInvoke(new Action(RefreshServersView)); RefreshServersMenu(); } @@ -319,7 +309,7 @@ namespace v2rayN.Forms Utils.AddSubItem(lvItem, EServerColName.subRemarks.ToString(), item.GetSubRemarks(config)); Utils.AddSubItem(lvItem, EServerColName.testResult.ToString(), item.testResult); - if (statistics != null && statistics.Enable) + if (statistics is { Enable: true }) { string totalUp = string.Empty, totalDown = string.Empty, @@ -1048,10 +1038,7 @@ namespace v2rayN.Forms { HideForm(); - string result = await Task.Run(() => - { - return Utils.ScanScreen(); - }); + string result = await Task.Run(Utils.ScanScreen); ShowForm(); @@ -1234,7 +1221,7 @@ namespace v2rayN.Forms { up /= (ulong)(config.statisticsFreshRate); down /= (ulong)(config.statisticsFreshRate); - mainMsgControl.SetToolSslInfo("speed", string.Format("{0}/s↑ | {1}/s↓", Utils.HumanFy(up), Utils.HumanFy(down))); + mainMsgControl.SetToolSslInfo("speed", $"{Utils.HumanFy(up)}/s↑ | {Utils.HumanFy(down)}/s↓"); foreach (var it in statistics) { @@ -1560,7 +1547,7 @@ namespace v2rayN.Forms for (int k = 0; k < config.routings.Count; k++) { var item = config.routings[k]; - if (item.locked == true) + if (item.locked) { continue; } diff --git a/v2rayN/v2rayN/Forms/MainMsgControl.cs b/v2rayN/v2rayN/Forms/MainMsgControl.cs index 6696573c..97ef7a68 100644 --- a/v2rayN/v2rayN/Forms/MainMsgControl.cs +++ b/v2rayN/v2rayN/Forms/MainMsgControl.cs @@ -1,12 +1,6 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; using System.Windows.Forms; using v2rayN.Base; using v2rayN.Mode; @@ -89,14 +83,9 @@ namespace v2rayN.Forms sb.Append($"{ResUI.LabLocal}:"); sb.Append($"[{Global.InboundSocks}:{config.GetLocalPort(Global.InboundSocks)}]"); sb.Append(" | "); - if (config.sysProxyType == ESysProxyType.ForcedChange) - { - sb.Append($"[{Global.InboundHttp}({ResUI.SystemProxy}):{config.GetLocalPort(Global.InboundHttp)}]"); - } - else - { - sb.Append($"[{Global.InboundHttp}:{config.GetLocalPort(Global.InboundHttp)}]"); - } + sb.Append(config.sysProxyType == ESysProxyType.ForcedChange + ? $"[{Global.InboundHttp}({ResUI.SystemProxy}):{config.GetLocalPort(Global.InboundHttp)}]" + : $"[{Global.InboundHttp}:{config.GetLocalPort(Global.InboundHttp)}]"); if (config.inbound[0].allowLANConn) { diff --git a/v2rayN/v2rayN/Forms/MsgFilterSetForm.cs b/v2rayN/v2rayN/Forms/MsgFilterSetForm.cs index 926b00cb..01c4f773 100644 --- a/v2rayN/v2rayN/Forms/MsgFilterSetForm.cs +++ b/v2rayN/v2rayN/Forms/MsgFilterSetForm.cs @@ -1,11 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; namespace v2rayN.Forms diff --git a/v2rayN/v2rayN/Forms/OptionSettingForm.cs b/v2rayN/v2rayN/Forms/OptionSettingForm.cs index 4c357b83..98c0d1cb 100644 --- a/v2rayN/v2rayN/Forms/OptionSettingForm.cs +++ b/v2rayN/v2rayN/Forms/OptionSettingForm.cs @@ -106,10 +106,7 @@ namespace v2rayN.Forms private void InitCoreType() { - if (config.coreTypeItem == null) - { - config.coreTypeItem = new List(); - } + config.coreTypeItem ??= new List(); foreach (EConfigType it in Enum.GetValues(typeof(EConfigType))) { diff --git a/v2rayN/v2rayN/Forms/RoutingRuleSettingDetailsForm.cs b/v2rayN/v2rayN/Forms/RoutingRuleSettingDetailsForm.cs index fa600925..c02cccc1 100644 --- a/v2rayN/v2rayN/Forms/RoutingRuleSettingDetailsForm.cs +++ b/v2rayN/v2rayN/Forms/RoutingRuleSettingDetailsForm.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; using v2rayN.Base; -using v2rayN.Handler; using v2rayN.Mode; using v2rayN.Resx; @@ -117,13 +116,10 @@ namespace v2rayN.Forms { EndBindingData(); - bool hasRule = - rulesItem.domain != null - && rulesItem.domain.Count > 0 - || rulesItem.ip != null - && rulesItem.ip.Count > 0 - || rulesItem.protocol != null - && rulesItem.protocol.Count > 0 + bool hasRule = + rulesItem.domain is { Count: > 0 } + || rulesItem.ip is { Count: > 0 } + || rulesItem.protocol is { Count: > 0 } || !Utils.IsNullOrEmpty(rulesItem.port); if (!hasRule) diff --git a/v2rayN/v2rayN/Forms/RoutingRuleSettingForm.cs b/v2rayN/v2rayN/Forms/RoutingRuleSettingForm.cs index b88d67d1..54feb7f7 100644 --- a/v2rayN/v2rayN/Forms/RoutingRuleSettingForm.cs +++ b/v2rayN/v2rayN/Forms/RoutingRuleSettingForm.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading.Tasks; using System.Windows.Forms; -using v2rayN.Base; using v2rayN.Handler; using v2rayN.Mode; using v2rayN.Resx; @@ -26,10 +25,7 @@ namespace v2rayN.Forms private void RoutingRuleSettingForm_Load(object sender, EventArgs e) { routingItem = EditIndex >= 0 ? config.routings[EditIndex] : new RoutingItem(); - if (routingItem.rules == null) - { - routingItem.rules = new List(); - } + routingItem.rules ??= new List(); txtRemarks.Text = routingItem.remarks ?? string.Empty; txtUrl.Text = routingItem.url ?? string.Empty; @@ -351,11 +347,7 @@ namespace v2rayN.Forms } private int AddBatchRoutingRules(ref RoutingItem routingItem, string clipboardData) { - bool blReplace = false; - if (UI.ShowYesNo(ResUI.AddBatchRoutingRulesYesNo) == DialogResult.No) - { - blReplace = true; - } + bool blReplace = UI.ShowYesNo(ResUI.AddBatchRoutingRulesYesNo) == DialogResult.No; return ConfigHandler.AddBatchRoutingRules(ref routingItem, clipboardData, blReplace); } diff --git a/v2rayN/v2rayN/Forms/RoutingSettingForm.cs b/v2rayN/v2rayN/Forms/RoutingSettingForm.cs index a34b01d7..20fd55de 100644 --- a/v2rayN/v2rayN/Forms/RoutingSettingForm.cs +++ b/v2rayN/v2rayN/Forms/RoutingSettingForm.cs @@ -26,10 +26,7 @@ namespace v2rayN.Forms chkenableRoutingAdvanced.Checked = config.enableRoutingAdvanced; cmbdomainMatcher.Text = config.domainMatcher; - if (config.routings == null) - { - config.routings = new List(); - } + config.routings ??= new List(); InitRoutingsView(); RefreshRoutingsView(); @@ -162,7 +159,7 @@ namespace v2rayN.Forms for (int k = 0; k < config.routings.Count; k++) { var item = config.routings[k]; - if (item.locked == true) + if (item.locked) { continue; } diff --git a/v2rayN/v2rayN/Forms/SubSettingControl.cs b/v2rayN/v2rayN/Forms/SubSettingControl.cs index 12f8896c..8fc61226 100644 --- a/v2rayN/v2rayN/Forms/SubSettingControl.cs +++ b/v2rayN/v2rayN/Forms/SubSettingControl.cs @@ -62,14 +62,7 @@ namespace v2rayN.Forms subItem.userAgent = txtUserAgent.Text.TrimEx(); var index = groupItem.FindIndex(t => t.remarks == cmbGroup.Text); - if (index >= 0) - { - subItem.groupId = groupItem[index].id; - } - else - { - subItem.groupId = string.Empty; - } + subItem.groupId = index >= 0 ? groupItem[index].id : string.Empty; } } private void txtRemarks_Leave(object sender, EventArgs e) diff --git a/v2rayN/v2rayN/Forms/SubSettingForm.cs b/v2rayN/v2rayN/Forms/SubSettingForm.cs index 1312c4a0..8eed6ba0 100644 --- a/v2rayN/v2rayN/Forms/SubSettingForm.cs +++ b/v2rayN/v2rayN/Forms/SubSettingForm.cs @@ -18,10 +18,7 @@ namespace v2rayN.Forms private void SubSettingForm_Load(object sender, EventArgs e) { - if (config.subItem == null) - { - config.subItem = new List(); - } + config.subItem ??= new List(); RefreshSubsView(); } diff --git a/v2rayN/v2rayN/Handler/ConfigHandler.cs b/v2rayN/v2rayN/Handler/ConfigHandler.cs index 7fc1a687..f66e7505 100644 --- a/v2rayN/v2rayN/Handler/ConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/ConfigHandler.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; using System.IO; -using System.Net; using v2rayN.Mode; using v2rayN.Base; using System.Linq; using v2rayN.Tool; -using System.Threading.Tasks; namespace v2rayN.Handler { @@ -101,36 +99,22 @@ namespace v2rayN.Handler //} //kcp - if (config.kcpItem == null) + config.kcpItem ??= new KcpItem { - config.kcpItem = new KcpItem - { - mtu = 1350, - tti = 50, - uplinkCapacity = 12, - downlinkCapacity = 100, - readBufferSize = 2, - writeBufferSize = 2, - congestion = false - }; - } - if (config.uiItem == null) + mtu = 1350, + tti = 50, + uplinkCapacity = 12, + downlinkCapacity = 100, + readBufferSize = 2, + writeBufferSize = 2, + congestion = false + }; + config.uiItem ??= new UIItem() { - config.uiItem = new UIItem() - { - enableAutoAdjustMainLvColWidth = true - }; - } - if (config.uiItem.mainLvColWidth == null) - { - config.uiItem.mainLvColWidth = new Dictionary(); - } - - - if (config.constItem == null) - { - config.constItem = new ConstItem(); - } + enableAutoAdjustMainLvColWidth = true + }; + config.uiItem.mainLvColWidth ??= new Dictionary(); + config.constItem ??= new ConstItem(); if (Utils.IsNullOrEmpty(config.constItem.speedTestUrl)) { config.constItem.speedTestUrl = Global.SpeedTestUrl; @@ -148,15 +132,9 @@ namespace v2rayN.Handler // config.remoteDNS = "1.1.1.1"; //} - if (config.subItem == null) - { - config.subItem = new List(); - } - if (config.groupItem == null) - { - config.groupItem = new List(); - } - if (config.statisticsFreshRate > 100 || config.statisticsFreshRate < 1) + config.subItem ??= new List(); + config.groupItem ??= new List(); + if (config.statisticsFreshRate is > 100 or < 1) { config.statisticsFreshRate = 1; } @@ -1260,10 +1238,7 @@ namespace v2rayN.Handler public static int AddformMainLvColWidth(ref Config config, string name, int width) { - if (config.uiItem.mainLvColWidth == null) - { - config.uiItem.mainLvColWidth = new Dictionary(); - } + config.uiItem.mainLvColWidth ??= new Dictionary(); if (config.uiItem.mainLvColWidth.ContainsKey(name)) { config.uiItem.mainLvColWidth[name] = width; @@ -1278,18 +1253,8 @@ namespace v2rayN.Handler } public static int GetformMainLvColWidth(ref Config config, string name, int width) { - if (config.uiItem.mainLvColWidth == null) - { - config.uiItem.mainLvColWidth = new Dictionary(); - } - if (config.uiItem.mainLvColWidth.ContainsKey(name)) - { - return config.uiItem.mainLvColWidth[name]; - } - else - { - return width; - } + config.uiItem.mainLvColWidth ??= new Dictionary(); + return config.uiItem.mainLvColWidth.ContainsKey(name) ? config.uiItem.mainLvColWidth[name] : width; } #endregion @@ -1308,7 +1273,7 @@ namespace v2rayN.Handler } //move locked item - int index = config.routings.FindIndex(it => it.locked == true); + int index = config.routings.FindIndex(it => it.locked); if (index != -1) { var item = Utils.DeepCopy(config.routings[index]); @@ -1339,7 +1304,7 @@ namespace v2rayN.Handler else { config.routings.Add(item); - int indexLocked = config.routings.FindIndex(it => it.locked == true); + int indexLocked = config.routings.FindIndex(it => it.locked); if (indexLocked != -1) { var itemLocked = Utils.DeepCopy(config.routings[indexLocked]); @@ -1370,10 +1335,7 @@ namespace v2rayN.Handler { return -1; } - if (routingItem.rules == null) - { - routingItem.rules = new List(); - } + routingItem.rules ??= new List(); if (blReplace) { routingItem.rules.Clear(); @@ -1485,10 +1447,7 @@ namespace v2rayN.Handler public static int InitBuiltinRouting(ref Config config, bool blImportAdvancedRules = false) { - if (config.routings == null) - { - config.routings = new List(); - } + config.routings ??= new List(); if (blImportAdvancedRules || config.routings.Count(it => it.locked != true) <= 0) { @@ -1543,11 +1502,7 @@ namespace v2rayN.Handler public static RoutingItem GetLockedRoutingItem(ref Config config) { - if (config.routings == null) - { - return null; - } - return config.routings.Find(it => it.locked == true); + return config.routings?.Find(it => it.locked); } #endregion } diff --git a/v2rayN/v2rayN/Handler/DownloadHandle.cs b/v2rayN/v2rayN/Handler/DownloadHandle.cs index 5d4d3caf..86fdc3cc 100644 --- a/v2rayN/v2rayN/Handler/DownloadHandle.cs +++ b/v2rayN/v2rayN/Handler/DownloadHandle.cs @@ -5,7 +5,6 @@ using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Sockets; -using System.Text; using System.Threading; using System.Threading.Tasks; using v2rayN.Base; diff --git a/v2rayN/v2rayN/Handler/LazyConfig.cs b/v2rayN/v2rayN/Handler/LazyConfig.cs index 2a89f526..f4d21e4d 100644 --- a/v2rayN/v2rayN/Handler/LazyConfig.cs +++ b/v2rayN/v2rayN/Handler/LazyConfig.cs @@ -48,11 +48,7 @@ namespace v2rayN.Handler return ECoreType.Xray; } var item = _config.coreTypeItem.FirstOrDefault(it => it.configType == eConfigType); - if (item == null) - { - return ECoreType.Xray; - } - return item.coreType; + return item?.coreType ?? ECoreType.Xray; } public CoreInfo GetCoreInfo(ECoreType coreType) @@ -61,144 +57,135 @@ namespace v2rayN.Handler { InitCoreInfo(); } - return coreInfos.Where(t => t.coreType == coreType).FirstOrDefault(); + return coreInfos.FirstOrDefault(t => t.coreType == coreType); } private void InitCoreInfo() { - coreInfos = new List(); - - coreInfos.Add(new CoreInfo + coreInfos = new List { - coreType = ECoreType.v2rayN, - coreUrl = Global.NUrl, - coreReleaseApiUrl = Global.NUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.NUrl + "/download/{0}/v2rayN.zip", - coreDownloadUrl64 = Global.NUrl + "/download/{0}/v2rayN.zip", - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.v2fly, - coreExes = new List { "wv2ray", "v2ray" }, - arguments = "", - coreUrl = Global.v2flyCoreUrl, - coreReleaseApiUrl = Global.v2flyCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", - coreDownloadUrl64 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", - match = "V2Ray", - versionArg = "-version", - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.SagerNet, - coreExes = new List { "SagerNet", "v2ray" }, - arguments = "run", - coreUrl = Global.SagerNetCoreUrl, - coreReleaseApiUrl = Global.SagerNetCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.SagerNetCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", - coreDownloadUrl64 = Global.SagerNetCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", - match = "V2Ray", - versionArg = "version", - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.v2fly_v5, - coreExes = new List { "v2ray" }, - arguments = "run", - coreUrl = Global.v2flyCoreUrl, - coreReleaseApiUrl = Global.v2flyCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", - coreDownloadUrl64 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", - match = "V2Ray", - versionArg = "version", - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.Xray, - coreExes = new List { "xray" }, - arguments = "", - coreUrl = Global.xrayCoreUrl, - coreReleaseApiUrl = Global.xrayCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.xrayCoreUrl + "/download/{0}/Xray-windows-{1}.zip", - coreDownloadUrl64 = Global.xrayCoreUrl + "/download/{0}/Xray-windows-{1}.zip", - match = "Xray", - versionArg = "-version", - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.clash, - coreExes = new List { "clash-windows-amd64-v3", "clash-windows-amd64", "clash-windows-386", "clash" }, - arguments = "-f config.json", - coreUrl = Global.clashCoreUrl, - coreReleaseApiUrl = Global.clashCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.clashCoreUrl + "/download/{0}/clash-windows-386-{0}.zip", - coreDownloadUrl64 = Global.clashCoreUrl + "/download/{0}/clash-windows-amd64-{0}.zip", - match = "v", - versionArg = "-v", - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.clash_meta, - coreExes = new List { "Clash.Meta-windows-amd64-compatible", "Clash.Meta-windows-amd64", "Clash.Meta-windows-386", "Clash.Meta", "clash" }, - arguments = "-f config.json", - coreUrl = Global.clashMetaCoreUrl, - coreReleaseApiUrl = Global.clashMetaCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.clashMetaCoreUrl + "/download/{0}/Clash.Meta-windows-386-{0}.zip", - coreDownloadUrl64 = Global.clashMetaCoreUrl + "/download/{0}/Clash.Meta-windows-amd64-compatible-{0}.zip", - match = "v", - versionArg = "-v", - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.hysteria, - coreExes = new List { "hysteria-windows-amd64", "hysteria-windows-386", "hysteria" }, - arguments = "", - coreUrl = Global.hysteriaCoreUrl, - coreReleaseApiUrl = Global.hysteriaCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), - coreDownloadUrl32 = Global.hysteriaCoreUrl + "/download/{0}/hysteria-windows-386.exe", - coreDownloadUrl64 = Global.hysteriaCoreUrl + "/download/{0}/hysteria-windows-amd64.exe", - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.naiveproxy, - coreExes = new List { "naiveproxy", "naive" }, - arguments = "config.json", - coreUrl = Global.naiveproxyCoreUrl, - redirectInfo = false, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.tuic, - coreExes = new List { "tuic-client", "tuic" }, - arguments = "-c config.json", - coreUrl = Global.tuicCoreUrl, - redirectInfo = true, - }); - - coreInfos.Add(new CoreInfo - { - coreType = ECoreType.sing_box, - coreExes = new List { "sing-box-client", "sing-box" }, - arguments = "run", - coreUrl = Global.singboxCoreUrl, - redirectInfo = true, - }); + new CoreInfo + { + coreType = ECoreType.v2rayN, + coreUrl = Global.NUrl, + coreReleaseApiUrl = Global.NUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.NUrl + "/download/{0}/v2rayN.zip", + coreDownloadUrl64 = Global.NUrl + "/download/{0}/v2rayN.zip", + }, + new CoreInfo + { + coreType = ECoreType.v2fly, + coreExes = new List { "wv2ray", "v2ray" }, + arguments = "", + coreUrl = Global.v2flyCoreUrl, + coreReleaseApiUrl = Global.v2flyCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", + coreDownloadUrl64 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", + match = "V2Ray", + versionArg = "-version", + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.SagerNet, + coreExes = new List { "SagerNet", "v2ray" }, + arguments = "run", + coreUrl = Global.SagerNetCoreUrl, + coreReleaseApiUrl = Global.SagerNetCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.SagerNetCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", + coreDownloadUrl64 = Global.SagerNetCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", + match = "V2Ray", + versionArg = "version", + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.v2fly_v5, + coreExes = new List { "v2ray" }, + arguments = "run", + coreUrl = Global.v2flyCoreUrl, + coreReleaseApiUrl = Global.v2flyCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", + coreDownloadUrl64 = Global.v2flyCoreUrl + "/download/{0}/v2ray-windows-{1}.zip", + match = "V2Ray", + versionArg = "version", + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.Xray, + coreExes = new List { "xray" }, + arguments = "", + coreUrl = Global.xrayCoreUrl, + coreReleaseApiUrl = Global.xrayCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.xrayCoreUrl + "/download/{0}/Xray-windows-{1}.zip", + coreDownloadUrl64 = Global.xrayCoreUrl + "/download/{0}/Xray-windows-{1}.zip", + match = "Xray", + versionArg = "-version", + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.clash, + coreExes = new List { "clash-windows-amd64-v3", "clash-windows-amd64", "clash-windows-386", "clash" }, + arguments = "-f config.json", + coreUrl = Global.clashCoreUrl, + coreReleaseApiUrl = Global.clashCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.clashCoreUrl + "/download/{0}/clash-windows-386-{0}.zip", + coreDownloadUrl64 = Global.clashCoreUrl + "/download/{0}/clash-windows-amd64-{0}.zip", + match = "v", + versionArg = "-v", + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.clash_meta, + coreExes = new List { "Clash.Meta-windows-amd64-compatible", "Clash.Meta-windows-amd64", "Clash.Meta-windows-386", "Clash.Meta", "clash" }, + arguments = "-f config.json", + coreUrl = Global.clashMetaCoreUrl, + coreReleaseApiUrl = Global.clashMetaCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.clashMetaCoreUrl + "/download/{0}/Clash.Meta-windows-386-{0}.zip", + coreDownloadUrl64 = Global.clashMetaCoreUrl + "/download/{0}/Clash.Meta-windows-amd64-compatible-{0}.zip", + match = "v", + versionArg = "-v", + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.hysteria, + coreExes = new List { "hysteria-windows-amd64", "hysteria-windows-386", "hysteria" }, + arguments = "", + coreUrl = Global.hysteriaCoreUrl, + coreReleaseApiUrl = Global.hysteriaCoreUrl.Replace(@"https://github.com", @"https://api.github.com/repos"), + coreDownloadUrl32 = Global.hysteriaCoreUrl + "/download/{0}/hysteria-windows-386.exe", + coreDownloadUrl64 = Global.hysteriaCoreUrl + "/download/{0}/hysteria-windows-amd64.exe", + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.naiveproxy, + coreExes = new List { "naiveproxy", "naive" }, + arguments = "config.json", + coreUrl = Global.naiveproxyCoreUrl, + redirectInfo = false, + }, + new CoreInfo + { + coreType = ECoreType.tuic, + coreExes = new List { "tuic-client", "tuic" }, + arguments = "-c config.json", + coreUrl = Global.tuicCoreUrl, + redirectInfo = true, + }, + new CoreInfo + { + coreType = ECoreType.sing_box, + coreExes = new List { "sing-box-client", "sing-box" }, + arguments = "run", + coreUrl = Global.singboxCoreUrl, + redirectInfo = true, + } + }; } } diff --git a/v2rayN/v2rayN/Handler/MainFormHandler.cs b/v2rayN/v2rayN/Handler/MainFormHandler.cs index 240d04ff..7327395e 100644 --- a/v2rayN/v2rayN/Handler/MainFormHandler.cs +++ b/v2rayN/v2rayN/Handler/MainFormHandler.cs @@ -1,14 +1,12 @@ using NHotkey; using NHotkey.WindowsForms; using System; -using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using v2rayN.Mode; -using System.Linq; using v2rayN.Resx; namespace v2rayN.Handler diff --git a/v2rayN/v2rayN/Handler/ShareHandler.cs b/v2rayN/v2rayN/Handler/ShareHandler.cs index 55a40eac..31870685 100644 --- a/v2rayN/v2rayN/Handler/ShareHandler.cs +++ b/v2rayN/v2rayN/Handler/ShareHandler.cs @@ -2,10 +2,7 @@ using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; -using System.Net; -using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; using System.Web; using v2rayN.Base; using v2rayN.Mode; @@ -104,7 +101,7 @@ namespace v2rayN.Handler //url = Utils.Base64Encode(url); //new Sip002 var pw = Utils.Base64Encode($"{item.security}:{item.id}"); - url = $"{pw}@{GetIpv6(item.address)}:{ item.port}"; + url = $"{pw}@{GetIpv6(item.address)}:{item.port}"; url = $"{Global.ssProtocol}{url}{remark}"; return url; } @@ -125,7 +122,7 @@ namespace v2rayN.Handler //url = Utils.Base64Encode(url); //new var pw = Utils.Base64Encode($"{item.security}:{item.id}"); - url = $"{pw}@{GetIpv6(item.address)}:{ item.port}"; + url = $"{pw}@{GetIpv6(item.address)}:{item.port}"; url = $"{Global.socksProtocol}{url}{remark}"; return url; } @@ -142,10 +139,7 @@ namespace v2rayN.Handler GetStdTransport(item, null, ref dicQuery); string query = "?" + string.Join("&", dicQuery.Select(x => x.Key + "=" + x.Value).ToArray()); - url = string.Format("{0}@{1}:{2}", - item.id, - GetIpv6(item.address), - item.port); + url = $"{item.id}@{GetIpv6(item.address)}:{item.port}"; url = $"{Global.trojanProtocol}{url}{query}{remark}"; return url; } @@ -158,22 +152,14 @@ namespace v2rayN.Handler { remark = "#" + Utils.UrlEncode(item.remarks); } - var dicQuery = new Dictionary(); - if (!Utils.IsNullOrEmpty(item.security)) + var dicQuery = new Dictionary { - dicQuery.Add("encryption", item.security); - } - else - { - dicQuery.Add("encryption", "none"); - } + { "encryption", !Utils.IsNullOrEmpty(item.security) ? item.security : "none" } + }; GetStdTransport(item, "none", ref dicQuery); string query = "?" + string.Join("&", dicQuery.Select(x => x.Key + "=" + x.Value).ToArray()); - url = string.Format("{0}@{1}:{2}", - item.id, - GetIpv6(item.address), - item.port); + url = $"{item.id}@{GetIpv6(item.address)}:{item.port}"; url = $"{Global.vlessProtocol}{url}{query}{remark}"; return url; } @@ -204,7 +190,7 @@ namespace v2rayN.Handler { dicQuery.Add("sni", item.sni); } - if (item.alpn != null && item.alpn.Count > 0) + if (item.alpn is { Count: > 0 }) { dicQuery.Add("alpn", Utils.UrlEncode(Utils.List2String(item.alpn))); } @@ -261,7 +247,7 @@ namespace v2rayN.Handler if (!Utils.IsNullOrEmpty(item.path)) { dicQuery.Add("serviceName", Utils.UrlEncode(item.path)); - if (item.headerType == Global.GrpcgunMode || item.headerType == Global.GrpcmultiMode) + if (item.headerType is Global.GrpcgunMode or Global.GrpcmultiMode) { dicQuery.Add("mode", Utils.UrlEncode(item.headerType)); } diff --git a/v2rayN/v2rayN/Handler/SpeedtestHandler.cs b/v2rayN/v2rayN/Handler/SpeedtestHandler.cs index e5d6022d..a9f6e2b1 100644 --- a/v2rayN/v2rayN/Handler/SpeedtestHandler.cs +++ b/v2rayN/v2rayN/Handler/SpeedtestHandler.cs @@ -13,10 +13,10 @@ namespace v2rayN.Handler { class SpeedtestHandler { - private Config _config; - private V2rayHandler _v2rayHandler; - private List _selecteds; - Action _updateFunc; + private readonly Config _config; + private readonly V2rayHandler _v2rayHandler; + private readonly List _selecteds; + private readonly Action _updateFunc; public SpeedtestHandler(Config config) { @@ -137,8 +137,7 @@ namespace v2rayN.Handler try { WebProxy webProxy = new WebProxy(Global.Loopback, it.port); - int responseTime = -1; - string status = downloadHandle.GetRealPingTime(_config.constItem.speedPingTestUrl, webProxy, out responseTime); + string status = downloadHandle.GetRealPingTime(_config.constItem.speedPingTestUrl, webProxy, out var responseTime); string output = Utils.IsNullOrEmpty(status) ? FormatOut(responseTime, "ms") : status; _config.GetVmessItem(it.indexId)?.SetTestResult(output); diff --git a/v2rayN/v2rayN/Handler/StatisticsHandler.cs b/v2rayN/v2rayN/Handler/StatisticsHandler.cs index 65b6e687..f8fb70ba 100644 --- a/v2rayN/v2rayN/Handler/StatisticsHandler.cs +++ b/v2rayN/v2rayN/Handler/StatisticsHandler.cs @@ -1,6 +1,7 @@ using Grpc.Core; using System; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; @@ -149,24 +150,15 @@ namespace v2rayN.Handler serverStatistics_ = Utils.FromJson(result); } - if (serverStatistics_ == null) - { - serverStatistics_ = new ServerStatistics(); - } - if (serverStatistics_.server == null) - { - serverStatistics_.server = new List(); - } + serverStatistics_ ??= new ServerStatistics(); + serverStatistics_.server ??= new List(); long ticks = DateTime.Now.Date.Ticks; - foreach (ServerStatItem item in serverStatistics_.server) + foreach (var item in serverStatistics_.server.Where(item => item.dateNow != ticks)) { - if (item.dateNow != ticks) - { - item.todayUp = 0; - item.todayDown = 0; - item.dateNow = ticks; - } + item.todayUp = 0; + item.todayDown = 0; + item.dateNow = ticks; } } catch (Exception ex) diff --git a/v2rayN/v2rayN/Handler/SysProxyHandle.cs b/v2rayN/v2rayN/Handler/SysProxyHandle.cs index 815580ae..edd7a977 100644 --- a/v2rayN/v2rayN/Handler/SysProxyHandle.cs +++ b/v2rayN/v2rayN/Handler/SysProxyHandle.cs @@ -144,85 +144,81 @@ namespace v2rayN.Handler // using event to avoid hanging when redirect standard output/error // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why // and http://blog.csdn.net/zhangweixing0/article/details/7356841 - using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) - using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) + using AutoResetEvent outputWaitHandle = new AutoResetEvent(false); + using AutoResetEvent errorWaitHandle = new AutoResetEvent(false); + using Process process = new Process(); + // Configure the process using the StartInfo properties. + process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe"); + process.StartInfo.Arguments = arguments; + process.StartInfo.WorkingDirectory = Utils.GetTempPath(); + process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.RedirectStandardOutput = true; + + // Need to provide encoding info, or output/error strings we got will be wrong. + process.StartInfo.StandardOutputEncoding = Encoding.Unicode; + process.StartInfo.StandardErrorEncoding = Encoding.Unicode; + + process.StartInfo.CreateNoWindow = true; + + StringBuilder output = new StringBuilder(); + StringBuilder error = new StringBuilder(); + + process.OutputDataReceived += (sender, e) => { - using (Process process = new Process()) + if (e.Data == null) { - // Configure the process using the StartInfo properties. - process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe"); - process.StartInfo.Arguments = arguments; - process.StartInfo.WorkingDirectory = Utils.GetTempPath(); - process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; - process.StartInfo.UseShellExecute = false; - process.StartInfo.RedirectStandardError = true; - process.StartInfo.RedirectStandardOutput = true; - - // Need to provide encoding info, or output/error strings we got will be wrong. - process.StartInfo.StandardOutputEncoding = Encoding.Unicode; - process.StartInfo.StandardErrorEncoding = Encoding.Unicode; - - process.StartInfo.CreateNoWindow = true; - - StringBuilder output = new StringBuilder(); - StringBuilder error = new StringBuilder(); - - process.OutputDataReceived += (sender, e) => - { - if (e.Data == null) - { - outputWaitHandle.Set(); - } - else - { - output.AppendLine(e.Data); - } - }; - process.ErrorDataReceived += (sender, e) => - { - if (e.Data == null) - { - errorWaitHandle.Set(); - } - else - { - error.AppendLine(e.Data); - } - }; - try - { - process.Start(); - - process.BeginErrorReadLine(); - process.BeginOutputReadLine(); - - process.WaitForExit(); - } - catch (System.ComponentModel.Win32Exception e) - { - - // log the arguments - throw new Exception(process.StartInfo.Arguments); - } - string stderr = error.ToString(); - string stdout = output.ToString(); - - int exitCode = process.ExitCode; - if (exitCode != (int)RET_ERRORS.RET_NO_ERROR) - { - throw new Exception(stderr); - } - - //if (arguments == "query") - //{ - // if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty()) - // { - // throw new Exception("failed to query wininet settings"); - // } - // _queryStr = stdout; - //} + outputWaitHandle.Set(); } + else + { + output.AppendLine(e.Data); + } + }; + process.ErrorDataReceived += (sender, e) => + { + if (e.Data == null) + { + errorWaitHandle.Set(); + } + else + { + error.AppendLine(e.Data); + } + }; + try + { + process.Start(); + + process.BeginErrorReadLine(); + process.BeginOutputReadLine(); + + process.WaitForExit(); } + catch (System.ComponentModel.Win32Exception e) + { + + // log the arguments + throw new Exception(process.StartInfo.Arguments); + } + string stderr = error.ToString(); + string stdout = output.ToString(); + + int exitCode = process.ExitCode; + if (exitCode != (int)RET_ERRORS.RET_NO_ERROR) + { + throw new Exception(stderr); + } + + //if (arguments == "query") + //{ + // if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty()) + // { + // throw new Exception("failed to query wininet settings"); + // } + // _queryStr = stdout; + //} } diff --git a/v2rayN/v2rayN/Handler/UpdateHandle.cs b/v2rayN/v2rayN/Handler/UpdateHandle.cs index a6468fc9..69930a4d 100644 --- a/v2rayN/v2rayN/Handler/UpdateHandle.cs +++ b/v2rayN/v2rayN/Handler/UpdateHandle.cs @@ -8,7 +8,6 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; -using Newtonsoft.Json; using v2rayN.Base; using v2rayN.Mode; using v2rayN.Resx; @@ -405,15 +404,7 @@ namespace v2rayN.Handler try { var gitHubReleases = Utils.FromJson>(gitHubReleaseApi); - string version; - if (preRelease) - { - version = gitHubReleases!.First().TagName; - } - else - { - version = gitHubReleases!.First(r => r.Prerelease == false).TagName; - } + var version = preRelease ? gitHubReleases!.First().TagName : gitHubReleases!.First(r => r.Prerelease == false).TagName; var coreInfo = LazyConfig.Instance.GetCoreInfo(type); string curVersion; @@ -437,14 +428,9 @@ namespace v2rayN.Handler { curVersion = getCoreVersion(type); message = string.Format(ResUI.IsLatestCore, curVersion); - if (Environment.Is64BitProcess) - { - url = string.Format(coreInfo.coreDownloadUrl64, version); - } - else - { - url = string.Format(coreInfo.coreDownloadUrl32, version); - } + url = string.Format(Environment.Is64BitProcess + ? coreInfo.coreDownloadUrl64 + : coreInfo.coreDownloadUrl32, version); break; } case ECoreType.v2rayN: diff --git a/v2rayN/v2rayN/Handler/V2rayConfigHandler.cs b/v2rayN/v2rayN/Handler/V2rayConfigHandler.cs index 5e76f664..06603b95 100644 --- a/v2rayN/v2rayN/Handler/V2rayConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/V2rayConfigHandler.cs @@ -246,21 +246,21 @@ namespace v2rayN.Handler { rules.port = null; } - if (rules.domain != null && rules.domain.Count == 0) + if (rules.domain is { Count: 0 }) { rules.domain = null; } - if (rules.ip != null && rules.ip.Count == 0) + if (rules.ip is { Count: 0 }) { rules.ip = null; } - if (rules.protocol != null && rules.protocol.Count == 0) + if (rules.protocol is { Count: 0 }) { rules.protocol = null; } var hasDomainIp = false; - if (rules.domain != null && rules.domain.Count > 0) + if (rules.domain is { Count: > 0 }) { var it = Utils.DeepCopy(rules); it.ip = null; @@ -284,7 +284,7 @@ namespace v2rayN.Handler v2rayConfig.routing.rules.Add(it); hasDomainIp = true; } - if (rules.ip != null && rules.ip.Count > 0) + if (rules.ip is { Count: > 0 }) { var it = Utils.DeepCopy(rules); it.domain = null; @@ -314,7 +314,7 @@ namespace v2rayN.Handler it.type = "field"; v2rayConfig.routing.rules.Add(it); } - else if (rules.protocol != null && rules.protocol.Count > 0) + else if (rules.protocol is { Count: > 0 }) { var it = Utils.DeepCopy(rules); //it.domain = null; @@ -377,14 +377,7 @@ namespace v2rayN.Handler usersItem.id = node.id; usersItem.alterId = node.alterId; usersItem.email = Global.userEMail; - if (Global.vmessSecuritys.Contains(node.security)) - { - usersItem.security = node.security; - } - else - { - usersItem.security = Global.DefaultSecurity; - } + usersItem.security = Global.vmessSecuritys.Contains(node.security) ? node.security : Global.DefaultSecurity; //Mux outbound.mux.enabled = config.muxEnabled; @@ -503,14 +496,7 @@ namespace v2rayN.Handler //if xtls if (node.streamSecurity == Global.StreamSecurityX) { - if (Utils.IsNullOrEmpty(node.flow)) - { - usersItem.flow = Global.xtlsFlows[1]; - } - else - { - usersItem.flow = node.flow.Replace("splice", "direct"); - } + usersItem.flow = Utils.IsNullOrEmpty(node.flow) ? Global.xtlsFlows[1] : node.flow.Replace("splice", "direct"); outbound.mux.enabled = false; outbound.mux.concurrency = -1; @@ -553,14 +539,9 @@ namespace v2rayN.Handler //if xtls if (node.streamSecurity == Global.StreamSecurityX) { - if (Utils.IsNullOrEmpty(node.flow)) - { - serversItem.flow = Global.xtlsFlows[1]; - } - else - { - serversItem.flow = node.flow.Replace("splice", "direct"); - } + serversItem.flow = Utils.IsNullOrEmpty(node.flow) + ? Global.xtlsFlows[1] + : node.flow.Replace("splice", "direct"); outbound.mux.enabled = false; outbound.mux.concurrency = -1; @@ -660,7 +641,7 @@ namespace v2rayN.Handler } else if (iobound.Equals("in")) { - kcpSettings.uplinkCapacity = config.kcpItem.downlinkCapacity; ; + kcpSettings.uplinkCapacity = config.kcpItem.downlinkCapacity; kcpSettings.downlinkCapacity = config.kcpItem.downlinkCapacity; } else @@ -1423,10 +1404,6 @@ namespace v2rayN.Handler if (!Utils.IsNullOrEmpty(request)) { V2rayTcpRequest v2rayTcpRequest = Utils.FromJson(request); - if (v2rayTcpRequest != null - && v2rayTcpRequest.headers != null - && v2rayTcpRequest.headers.Host != null - && v2rayTcpRequest.headers.Host.Count > 0) { vmessItem.requestHost = v2rayTcpRequest.headers.Host[0]; } @@ -1465,17 +1442,14 @@ namespace v2rayN.Handler { vmessItem.path = inbound.streamSettings.httpSettings.path; } - if (inbound.streamSettings.httpSettings.host != null - && inbound.streamSettings.httpSettings.host.Count > 0) + if (inbound.streamSettings.httpSettings.host is { Count: > 0 }) { vmessItem.requestHost = Utils.List2String(inbound.streamSettings.httpSettings.host); } } //tls - if (inbound.streamSettings != null - && inbound.streamSettings.security != null - && inbound.streamSettings.security == Global.StreamSecurity) + if (inbound.streamSettings is { security: Global.StreamSecurity }) { vmessItem.streamSecurity = Global.StreamSecurity; } diff --git a/v2rayN/v2rayN/Handler/V2rayHandler.cs b/v2rayN/v2rayN/Handler/V2rayHandler.cs index 412bf95d..119376e6 100644 --- a/v2rayN/v2rayN/Handler/V2rayHandler.cs +++ b/v2rayN/v2rayN/Handler/V2rayHandler.cs @@ -63,7 +63,7 @@ namespace v2rayN.Handler } //start a socks service - if (_process != null && !_process.HasExited && item.configType == EConfigType.Custom && item.preSocksPort > 0) + if (_process is { HasExited: false } && item.configType == EConfigType.Custom && item.preSocksPort > 0) { var itemSocks = new VmessItem() { diff --git a/v2rayN/v2rayN/Mode/Config.cs b/v2rayN/v2rayN/Mode/Config.cs index 6349b123..4430309d 100644 --- a/v2rayN/v2rayN/Mode/Config.cs +++ b/v2rayN/v2rayN/Mode/Config.cs @@ -275,11 +275,9 @@ namespace v2rayN.Mode public string GetGroupRemarks(string groupId) { - if (string.IsNullOrEmpty(groupId)) - { - return string.Empty; - } - return groupItem.Where(it => it.id == groupId).FirstOrDefault()?.remarks; + return string.IsNullOrEmpty(groupId) + ? string.Empty + : groupItem.FirstOrDefault(it => it.id == groupId)?.remarks; } #endregion @@ -316,21 +314,14 @@ namespace v2rayN.Mode #region function public string GetSummary() { - string summary = string.Format("[{0}] ", (configType).ToString()); + string summary = $"[{(configType).ToString()}] "; string[] arrAddr = address.Split('.'); - string addr; - if (arrAddr.Length > 2) + string addr = arrAddr.Length switch { - addr = $"{arrAddr[0]}***{arrAddr[arrAddr.Length - 1]}"; - } - else if (arrAddr.Length > 1) - { - addr = $"***{arrAddr[arrAddr.Length - 1]}"; - } - else - { - addr = address; - } + > 2 => $"{arrAddr[0]}***{arrAddr[arrAddr.Length - 1]}", + > 1 => $"***{arrAddr[arrAddr.Length - 1]}", + _ => address + }; switch (configType) { case EConfigType.VMess: @@ -338,10 +329,10 @@ namespace v2rayN.Mode case EConfigType.Socks: case EConfigType.VLESS: case EConfigType.Trojan: - summary += string.Format("{0}({1}:{2})", remarks, addr, port); + summary += $"{remarks}({addr}:{port})"; break; default: - summary += string.Format("{0}", remarks); + summary += $"{remarks}"; break; } return summary; @@ -372,23 +363,12 @@ namespace v2rayN.Mode return subRemarks; } var group = config.groupItem.FirstOrDefault(t => t.id == groupId); - if (group != null) - { - return group.remarks; - } - return groupId.Substring(0, 4); + return group != null ? group.remarks : groupId.Substring(0, 4); } public List GetAlpn() { - if (alpn != null && alpn.Count > 0) - { - return alpn; - } - else - { - return null; - } + return alpn is { Count: > 0 } ? alpn : null; } public string GetNetwork() { diff --git a/v2rayN/v2rayN/Mode/RoutingItem.cs b/v2rayN/v2rayN/Mode/RoutingItem.cs index 02a93edf..aa141255 100644 --- a/v2rayN/v2rayN/Mode/RoutingItem.cs +++ b/v2rayN/v2rayN/Mode/RoutingItem.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace v2rayN.Mode { diff --git a/v2rayN/v2rayN/Tool/FileManager.cs b/v2rayN/v2rayN/Tool/FileManager.cs index 42dffbd6..2c9f12d4 100644 --- a/v2rayN/v2rayN/Tool/FileManager.cs +++ b/v2rayN/v2rayN/Tool/FileManager.cs @@ -11,8 +11,8 @@ namespace v2rayN.Tool { try { - using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) - fs.Write(content, 0, content.Length); + using FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); + fs.Write(content, 0, content.Length); return true; } catch (Exception ex) @@ -31,14 +31,12 @@ namespace v2rayN.Tool byte[] buffer = new byte[4096]; int n; - using (FileStream fs = File.Create(fileName)) - using (GZipStream input = new GZipStream(new MemoryStream(content), - CompressionMode.Decompress, false)) + using FileStream fs = File.Create(fileName); + using GZipStream input = new GZipStream(new MemoryStream(content), + CompressionMode.Decompress, false); + while ((n = input.Read(buffer, 0, buffer.Length)) > 0) { - while ((n = input.Read(buffer, 0, buffer.Length)) > 0) - { - fs.Write(buffer, 0, n); - } + fs.Write(buffer, 0, n); } } catch (Exception ex) @@ -56,11 +54,9 @@ namespace v2rayN.Tool { try { - using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - using (StreamReader sr = new StreamReader(fs, encoding)) - { - return sr.ReadToEnd(); - } + using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using StreamReader sr = new StreamReader(fs, encoding); + return sr.ReadToEnd(); } catch (Exception ex) { @@ -111,18 +107,16 @@ namespace v2rayN.Tool { try { - using (ZipArchive archive = ZipFile.OpenRead(fileName)) + using ZipArchive archive = ZipFile.OpenRead(fileName); + foreach (ZipArchiveEntry entry in archive.Entries) { - foreach (ZipArchiveEntry entry in archive.Entries) - { - if (entry.Length == 0) - continue; + if (entry.Length == 0) + continue; - string entryOuputPath = Utils.GetPath(entry.FullName); - FileInfo fileInfo = new FileInfo(entryOuputPath); - fileInfo.Directory.Create(); - entry.ExtractToFile(entryOuputPath, true); - } + string entryOuputPath = Utils.GetPath(entry.FullName); + FileInfo fileInfo = new FileInfo(entryOuputPath); + fileInfo.Directory.Create(); + entry.ExtractToFile(entryOuputPath, true); } } catch (Exception ex) diff --git a/v2rayN/v2rayN/Tool/Job.cs b/v2rayN/v2rayN/Tool/Job.cs index e2569b75..64b021f1 100644 --- a/v2rayN/v2rayN/Tool/Job.cs +++ b/v2rayN/v2rayN/Tool/Job.cs @@ -35,8 +35,7 @@ namespace v2rayN if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint) length)) - throw new Exception(string.Format("Unable to set information. Error: {0}", - Marshal.GetLastWin32Error())); + throw new Exception($"Unable to set information. Error: {Marshal.GetLastWin32Error()}"); } finally { diff --git a/v2rayN/v2rayN/Tool/QueryableExtension.cs b/v2rayN/v2rayN/Tool/QueryableExtension.cs index eefb04d2..ef264b16 100644 --- a/v2rayN/v2rayN/Tool/QueryableExtension.cs +++ b/v2rayN/v2rayN/Tool/QueryableExtension.cs @@ -9,14 +9,14 @@ namespace v2rayN.Tool { public static IOrderedQueryable OrderBy(this IQueryable query, string propertyName) { - return _OrderBy(query, propertyName, false); + return _OrderBy(query, propertyName, false); } public static IOrderedQueryable OrderByDescending(this IQueryable query, string propertyName) { - return _OrderBy(query, propertyName, true); + return _OrderBy(query, propertyName, true); } - static IOrderedQueryable _OrderBy(IQueryable query, string propertyName, bool isDesc) + private static IOrderedQueryable _OrderBy(IQueryable query, string propertyName, bool isDesc) { string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal"; @@ -35,7 +35,8 @@ namespace v2rayN.Tool {//public return query.OrderByDescending(_GetLamba(memberProperty)); } - static Expression> _GetLamba(PropertyInfo memberProperty) + + private static Expression> _GetLamba(PropertyInfo memberProperty) { if (memberProperty.PropertyType != typeof(TProp)) throw new Exception(); diff --git a/v2rayN/v2rayN/Tool/Utils.cs b/v2rayN/v2rayN/Tool/Utils.cs index 39be59a0..cbd963b0 100644 --- a/v2rayN/v2rayN/Tool/Utils.cs +++ b/v2rayN/v2rayN/Tool/Utils.cs @@ -45,11 +45,9 @@ namespace v2rayN try { Assembly assembly = Assembly.GetExecutingAssembly(); - using (Stream stream = assembly.GetManifestResourceStream(res)) - using (StreamReader reader = new StreamReader(stream)) - { - result = reader.ReadToEnd(); - } + using Stream stream = assembly.GetManifestResourceStream(res); + using StreamReader reader = new StreamReader(stream); + result = reader.ReadToEnd(); } catch (Exception ex) { @@ -69,10 +67,8 @@ namespace v2rayN try { - using (StreamReader reader = new StreamReader(res)) - { - result = reader.ReadToEnd(); - } + using StreamReader reader = new StreamReader(res); + result = reader.ReadToEnd(); } catch (Exception ex) { @@ -385,7 +381,7 @@ namespace v2rayN public static string HumanFy(ulong amount) { ToHumanReadable(amount, out double result, out string unit); - return $"{string.Format("{0:f1}", result)} {unit}"; + return $"{$"{result:f1}"} {unit}"; } @@ -545,29 +541,18 @@ namespace v2rayN #region 开机自动启动 - private static string autoRunName - { - get - { - return $"v2rayNAutoRun_{GetMD5(StartupPath())}"; - } - } - private static string autoRunRegPath - { - get - { - return @"Software\Microsoft\Windows\CurrentVersion\Run"; - //if (Environment.Is64BitProcess) - //{ - // return @"Software\Microsoft\Windows\CurrentVersion\Run"; - //} - //else - //{ - // return @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"; - //} - } - } + private static string autoRunName => $"v2rayNAutoRun_{GetMD5(StartupPath())}"; + private static string autoRunRegPath => @"Software\Microsoft\Windows\CurrentVersion\Run"; + + //if (Environment.Is64BitProcess) + //{ + // return @"Software\Microsoft\Windows\CurrentVersion\Run"; + //} + //else + //{ + // return @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"; + //} /// /// 开机自动启动 /// @@ -703,23 +688,16 @@ namespace v2rayN public static bool CheckForDotNetVersion(int release = 528040) { const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; - using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey)) + using RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey); + if (ndpKey != null && ndpKey.GetValue("Release") != null) { - if (ndpKey != null && ndpKey.GetValue("Release") != null) - { - return (int)ndpKey.GetValue("Release") >= release ? true : false; - } - return false; + return (int)ndpKey.GetValue("Release") >= release ? true : false; } + return false; } - public static string MainMsgFilterKey - { - get - { - return $"MainMsgFilter_{GetMD5(StartupPath())}"; - } - } + public static string MainMsgFilterKey => $"MainMsgFilter_{GetMD5(StartupPath())}"; + #endregion #region 测速 @@ -837,14 +815,12 @@ namespace v2rayN string location = GetExePath(); if (blFull) { - return string.Format("v2rayN - V{0} - {1}", - FileVersionInfo.GetVersionInfo(location).FileVersion.ToString(), - File.GetLastWriteTime(location).ToString("yyyy/MM/dd")); + return + $"v2rayN - V{FileVersionInfo.GetVersionInfo(location).FileVersion.ToString()} - {File.GetLastWriteTime(location).ToString("yyyy/MM/dd")}"; } else { - return string.Format("v2rayN/{0}", - FileVersionInfo.GetVersionInfo(location).FileVersion.ToString()); + return $"v2rayN/{FileVersionInfo.GetVersionInfo(location).FileVersion.ToString()}"; } } catch (Exception ex) @@ -1076,42 +1052,40 @@ namespace v2rayN { foreach (Screen screen in Screen.AllScreens) { - using (Bitmap fullImage = new Bitmap(screen.Bounds.Width, - screen.Bounds.Height)) + using Bitmap fullImage = new Bitmap(screen.Bounds.Width, + screen.Bounds.Height); + using (Graphics g = Graphics.FromImage(fullImage)) { - using (Graphics g = Graphics.FromImage(fullImage)) + g.CopyFromScreen(screen.Bounds.X, + screen.Bounds.Y, + 0, 0, + fullImage.Size, + CopyPixelOperation.SourceCopy); + } + int maxTry = 10; + for (int i = 0; i < maxTry; i++) + { + int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry); + int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry); + Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2); + Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height); + + double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width; + using (Graphics g = Graphics.FromImage(target)) { - g.CopyFromScreen(screen.Bounds.X, - screen.Bounds.Y, - 0, 0, - fullImage.Size, - CopyPixelOperation.SourceCopy); + g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height), + cropRect, + GraphicsUnit.Pixel); } - int maxTry = 10; - for (int i = 0; i < maxTry; i++) + + BitmapLuminanceSource source = new BitmapLuminanceSource(target); + BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + QRCodeReader reader = new QRCodeReader(); + Result result = reader.decode(bitmap); + if (result != null) { - int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry); - int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry); - Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2); - Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height); - - double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width; - using (Graphics g = Graphics.FromImage(target)) - { - g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height), - cropRect, - GraphicsUnit.Pixel); - } - - BitmapLuminanceSource source = new BitmapLuminanceSource(target); - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); - QRCodeReader reader = new QRCodeReader(); - Result result = reader.decode(bitmap); - if (result != null) - { - string ret = result.Text; - return ret; - } + string ret = result.Text; + return ret; } } } @@ -1128,13 +1102,7 @@ namespace v2rayN #region Windows API - public static string WindowHwndKey - { - get - { - return $"WindowHwnd_{GetMD5(StartupPath())}"; - } - } + public static string WindowHwndKey => $"WindowHwnd_{GetMD5(StartupPath())}"; [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();