From 6a89be2e893cf5de4e0c5a0b253f5499fc66b9d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E4=BB=99=E5=A5=B3?= Date: Sun, 19 Feb 2023 13:34:22 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- v2rayN/v2rayN/Base/HttpClientHelper.cs | 16 +- v2rayN/v2rayN/Base/SqliteHelper.cs | 2 +- .../v2rayN/Converters/DelayColorConverter.cs | 2 +- .../v2rayN/Converters/MaterialDesignFonts.cs | 5 +- v2rayN/v2rayN/Global.cs | 50 +++--- v2rayN/v2rayN/Handler/ConfigHandler.cs | 12 +- v2rayN/v2rayN/Handler/CoreConfigHandler.cs | 56 ++++--- v2rayN/v2rayN/Handler/CoreHandler.cs | 6 +- v2rayN/v2rayN/Handler/DownloadHandle.cs | 13 +- v2rayN/v2rayN/Handler/LazyConfig.cs | 4 +- v2rayN/v2rayN/Handler/MainFormHandler.cs | 42 +++-- v2rayN/v2rayN/Handler/ProfileExHandler.cs | 2 +- v2rayN/v2rayN/Handler/ProxySetting.cs | 12 +- v2rayN/v2rayN/Handler/QRCodeHelper.cs | 4 +- v2rayN/v2rayN/Handler/ShareHandler.cs | 46 +++--- v2rayN/v2rayN/Handler/SpeedtestHandler.cs | 21 ++- v2rayN/v2rayN/Handler/StatisticsHandler.cs | 2 +- v2rayN/v2rayN/Handler/SysProxyHandle.cs | 147 +++++++++--------- v2rayN/v2rayN/Handler/TunHandler.cs | 10 +- v2rayN/v2rayN/Handler/UpdateHandle.cs | 10 +- v2rayN/v2rayN/Tool/Job.cs | 6 +- v2rayN/v2rayN/Tool/Logging.cs | 4 +- .../v2rayN/ViewModels/AddServer2ViewModel.cs | 7 +- .../v2rayN/ViewModels/MainWindowViewModel.cs | 30 ++-- 24 files changed, 244 insertions(+), 265 deletions(-) diff --git a/v2rayN/v2rayN/Base/HttpClientHelper.cs b/v2rayN/v2rayN/Base/HttpClientHelper.cs index 0c8bdab0..04139c76 100644 --- a/v2rayN/v2rayN/Base/HttpClientHelper.cs +++ b/v2rayN/v2rayN/Base/HttpClientHelper.cs @@ -26,9 +26,9 @@ namespace v2rayN.Base } else { - HttpClientHelper httpClientHelper = new HttpClientHelper(); + HttpClientHelper httpClientHelper = new(); - HttpClientHandler handler = new HttpClientHandler() { UseCookies = false }; + HttpClientHandler handler = new() { UseCookies = false }; httpClientHelper.httpClient = new HttpClient(handler); return httpClientHelper; } @@ -71,11 +71,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)) { @@ -89,10 +89,10 @@ namespace v2rayN.Base throw new Exception(string.Format("{0}", 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(token); using var file = File.Create(fileName); var totalRead = 0L; var buffer = new byte[1024 * 1024]; @@ -103,7 +103,7 @@ namespace v2rayN.Base { token.ThrowIfCancellationRequested(); - var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); + var read = await stream.ReadAsync(buffer, token); if (read == 0) { @@ -176,7 +176,7 @@ namespace v2rayN.Base } } - var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); + var read = await stream.ReadAsync(buffer, token); if (read == 0) { diff --git a/v2rayN/v2rayN/Base/SqliteHelper.cs b/v2rayN/v2rayN/Base/SqliteHelper.cs index eeb7b8e5..4b6a2c3c 100644 --- a/v2rayN/v2rayN/Base/SqliteHelper.cs +++ b/v2rayN/v2rayN/Base/SqliteHelper.cs @@ -6,7 +6,7 @@ namespace v2rayN.Base { public sealed class SqliteHelper { - private static readonly Lazy _instance = new Lazy(() => new()); + private static readonly Lazy _instance = new(() => new()); public static SqliteHelper Instance => _instance.Value; private string _connstr; public SQLiteConnection _db; diff --git a/v2rayN/v2rayN/Converters/DelayColorConverter.cs b/v2rayN/v2rayN/Converters/DelayColorConverter.cs index ab43c991..0044a28e 100644 --- a/v2rayN/v2rayN/Converters/DelayColorConverter.cs +++ b/v2rayN/v2rayN/Converters/DelayColorConverter.cs @@ -17,7 +17,7 @@ namespace v2rayN.Converters return new SolidColorBrush(Colors.IndianRed); } - public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) + public object? ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return null; } diff --git a/v2rayN/v2rayN/Converters/MaterialDesignFonts.cs b/v2rayN/v2rayN/Converters/MaterialDesignFonts.cs index cb346795..0b6908d1 100644 --- a/v2rayN/v2rayN/Converters/MaterialDesignFonts.cs +++ b/v2rayN/v2rayN/Converters/MaterialDesignFonts.cs @@ -21,10 +21,7 @@ namespace v2rayN.Converters catch { } - if (MyFont is null) - { - MyFont = new FontFamily("Microsoft YaHei"); - } + MyFont ??= new FontFamily("Microsoft YaHei"); } } } \ No newline at end of file diff --git a/v2rayN/v2rayN/Global.cs b/v2rayN/v2rayN/Global.cs index ed6d0673..9746e15d 100644 --- a/v2rayN/v2rayN/Global.cs +++ b/v2rayN/v2rayN/Global.cs @@ -80,26 +80,26 @@ public const string SpeedUnit = ""; public const int MinFontSize = 10; - public static readonly List IEProxyProtocols = new List { + public static readonly List IEProxyProtocols = new() { "{ip}:{http_port}", "socks={ip}:{socks_port}", "http={ip}:{http_port};https={ip}:{http_port};ftp={ip}:{http_port};socks={ip}:{socks_port}", "http=http://{ip}:{http_port};https=http://{ip}:{http_port}", "" }; - public static readonly List vmessSecuritys = new List { "aes-128-gcm", "chacha20-poly1305", "auto", "none", "zero" }; - public static readonly List ssSecuritys = new List { "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "none", "plain" }; - public static readonly List ssSecuritysInSagerNet = new List { "none", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", "aes-128-gcm", "aes-192-gcm", "aes-256-gcm", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", "rc4", "rc4-md5", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "aes-128-cfb8", "aes-192-cfb8", "aes-256-cfb8", "aes-128-ofb", "aes-192-ofb", "aes-256-ofb", "bf-cfb", "cast5-cfb", "des-cfb", "idea-cfb", "rc2-cfb", "seed-cfb", "camellia-128-cfb", "camellia-192-cfb", "camellia-256-cfb", "camellia-128-cfb8", "camellia-192-cfb8", "camellia-256-cfb8", "salsa20", "chacha20", "chacha20-ietf", "xchacha20" }; - public static readonly List ssSecuritysInXray = new List { "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "xchacha20-poly1305", "xchacha20-ietf-poly1305", "none", "plain", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305" }; - public static readonly List xtlsFlows = new List { "", "xtls-rprx-origin", "xtls-rprx-origin-udp443", "xtls-rprx-direct", "xtls-rprx-direct-udp443", "xtls-rprx-vision", "xtls-rprx-vision-udp443" }; - public static readonly List networks = new List { "tcp", "kcp", "ws", "h2", "quic", "grpc" }; - public static readonly List kcpHeaderTypes = new List { "srtp", "utp", "wechat-video", "dtls", "wireguard" }; - public static readonly List coreTypes = new List { "v2fly", "SagerNet", "Xray", "v2fly_v5" }; - public static readonly List domainStrategys = new List { "AsIs", "IPIfNonMatch", "IPOnDemand" }; - public static readonly List domainMatchers = new List { "linear", "mph", "" }; - public static readonly List fingerprints = new List { "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized", "" }; - public static readonly List userAgent = new List { "chrome", "firefox", "safari", "edge", "none" }; - public static readonly Dictionary userAgentTxt = new Dictionary + public static readonly List vmessSecuritys = new() { "aes-128-gcm", "chacha20-poly1305", "auto", "none", "zero" }; + public static readonly List ssSecuritys = new() { "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "none", "plain" }; + public static readonly List ssSecuritysInSagerNet = new() { "none", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305", "aes-128-gcm", "aes-192-gcm", "aes-256-gcm", "chacha20-ietf-poly1305", "xchacha20-ietf-poly1305", "rc4", "rc4-md5", "aes-128-ctr", "aes-192-ctr", "aes-256-ctr", "aes-128-cfb", "aes-192-cfb", "aes-256-cfb", "aes-128-cfb8", "aes-192-cfb8", "aes-256-cfb8", "aes-128-ofb", "aes-192-ofb", "aes-256-ofb", "bf-cfb", "cast5-cfb", "des-cfb", "idea-cfb", "rc2-cfb", "seed-cfb", "camellia-128-cfb", "camellia-192-cfb", "camellia-256-cfb", "camellia-128-cfb8", "camellia-192-cfb8", "camellia-256-cfb8", "salsa20", "chacha20", "chacha20-ietf", "xchacha20" }; + public static readonly List ssSecuritysInXray = new() { "aes-256-gcm", "aes-128-gcm", "chacha20-poly1305", "chacha20-ietf-poly1305", "xchacha20-poly1305", "xchacha20-ietf-poly1305", "none", "plain", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305" }; + public static readonly List xtlsFlows = new() { "", "xtls-rprx-origin", "xtls-rprx-origin-udp443", "xtls-rprx-direct", "xtls-rprx-direct-udp443", "xtls-rprx-vision", "xtls-rprx-vision-udp443" }; + public static readonly List networks = new() { "tcp", "kcp", "ws", "h2", "quic", "grpc" }; + public static readonly List kcpHeaderTypes = new() { "srtp", "utp", "wechat-video", "dtls", "wireguard" }; + public static readonly List coreTypes = new() { "v2fly", "SagerNet", "Xray", "v2fly_v5" }; + public static readonly List domainStrategys = new() { "AsIs", "IPIfNonMatch", "IPOnDemand" }; + public static readonly List domainMatchers = new() { "linear", "mph", "" }; + public static readonly List fingerprints = new() { "chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized", "" }; + public static readonly List userAgent = new() { "chrome", "firefox", "safari", "edge", "none" }; + public static readonly Dictionary userAgentTxt = new() { {"chrome","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36" }, {"firefox","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0" }, @@ -107,17 +107,17 @@ {"edge","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.70" }, {"none",""} }; - public static readonly List allowInsecures = new List { "true", "false", "" }; - public static readonly List domainStrategy4Freedoms = new List { "AsIs", "UseIP", "UseIPv4", "UseIPv6", "" }; - public static readonly List Languages = new List { "zh-Hans", "en", "fa-Ir", "ru" }; - public static readonly List alpns = new List { "h2", "http/1.1", "h2,http/1.1", "" }; - public static readonly List LogLevel = new List { "debug", "info", "warning", "error", "none" }; - public static readonly List InboundTags = new List { "socks", "http", "socks2", "http2" }; - public static readonly List Protocols = new List { "http", "tls", "bittorrent" }; - public static readonly List TunMtus = new List { "9000", "1500" }; - public static readonly List TunStacks = new List { "gvisor", "system" }; - public static readonly List PresetMsgFilters = new List { "proxy", "direct", "block", "" }; - public static readonly List SpeedTestUrls = new List { @"http://cachefly.cachefly.net/100mb.test", @"http://cachefly.cachefly.net/10mb.test" }; + public static readonly List allowInsecures = new() { "true", "false", "" }; + public static readonly List domainStrategy4Freedoms = new() { "AsIs", "UseIP", "UseIPv4", "UseIPv6", "" }; + public static readonly List Languages = new() { "zh-Hans", "en", "fa-Ir", "ru" }; + public static readonly List alpns = new() { "h2", "http/1.1", "h2,http/1.1", "" }; + public static readonly List LogLevel = new() { "debug", "info", "warning", "error", "none" }; + public static readonly List InboundTags = new() { "socks", "http", "socks2", "http2" }; + public static readonly List Protocols = new() { "http", "tls", "bittorrent" }; + public static readonly List TunMtus = new() { "9000", "1500" }; + public static readonly List TunStacks = new() { "gvisor", "system" }; + public static readonly List PresetMsgFilters = new() { "proxy", "direct", "block", "" }; + public static readonly List SpeedTestUrls = new() { @"http://cachefly.cachefly.net/100mb.test", @"http://cachefly.cachefly.net/10mb.test" }; #endregion diff --git a/v2rayN/v2rayN/Handler/ConfigHandler.cs b/v2rayN/v2rayN/Handler/ConfigHandler.cs index 59e1bc5e..78d95e15 100644 --- a/v2rayN/v2rayN/Handler/ConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/ConfigHandler.cs @@ -13,7 +13,7 @@ namespace v2rayN.Handler class ConfigHandler { private static string configRes = Global.ConfigFileName; - private static readonly object objLock = new object(); + private static readonly object objLock = new(); #region ConfigHandler @@ -61,7 +61,7 @@ namespace v2rayN.Handler if (config.inbound == null) { config.inbound = new List(); - InItem inItem = new InItem + InItem inItem = new() { protocol = Global.InboundSocks, localPort = 10808, @@ -190,7 +190,7 @@ namespace v2rayN.Handler config.speedTestItem.speedPingTestUrl = Global.SpeedPingTestUrl; } - if (config.guiItem.statisticsFreshRate > 100 || config.guiItem.statisticsFreshRate < 1) + if (config.guiItem.statisticsFreshRate is > 100 or < 1) { config.guiItem.statisticsFreshRate = 1; } @@ -548,7 +548,7 @@ namespace v2rayN.Handler { return 0; } - sort = ProfileExHandler.Instance.GetSort(lstProfile[lstProfile.Count - 1].indexId) + 1; + sort = ProfileExHandler.Instance.GetSort(lstProfile[^1].indexId) + 1; break; } @@ -810,7 +810,7 @@ namespace v2rayN.Handler List source = lstProfile; bool keepOlder = config.guiItem.keepOlderDedupl; - List list = new List(); + List list = new(); if (!keepOlder) source.Reverse(); // Remove the early items first foreach (ProfileItem item in source) @@ -1221,7 +1221,7 @@ namespace v2rayN.Handler return 0; } - SubItem subItem = new SubItem + SubItem subItem = new() { id = string.Empty, remarks = "import_sub", diff --git a/v2rayN/v2rayN/Handler/CoreConfigHandler.cs b/v2rayN/v2rayN/Handler/CoreConfigHandler.cs index 1dc417fd..b0d18e31 100644 --- a/v2rayN/v2rayN/Handler/CoreConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/CoreConfigHandler.cs @@ -90,8 +90,8 @@ namespace v2rayN.Handler { var dtNow = DateTime.Now; v2rayConfig.log.loglevel = config.coreBasicItem.loglevel; - v2rayConfig.log.access = Utils.GetLogPath($"Vaccess_{dtNow.ToString("yyyy-MM-dd")}.txt"); - v2rayConfig.log.error = Utils.GetLogPath($"Verror_{dtNow.ToString("yyyy-MM-dd")}.txt"); + v2rayConfig.log.access = Utils.GetLogPath($"Vaccess_{dtNow:yyyy-MM-dd}.txt"); + v2rayConfig.log.error = Utils.GetLogPath($"Verror_{dtNow:yyyy-MM-dd}.txt"); } else { @@ -405,7 +405,7 @@ namespace v2rayN.Handler if (!Utils.IsNullOrEmpty(node.security) && !Utils.IsNullOrEmpty(node.id)) { - SocksUsersItem socksUsersItem = new SocksUsersItem + SocksUsersItem socksUsersItem = new() { user = node.security, pass = node.id, @@ -565,7 +565,7 @@ namespace v2rayN.Handler { streamSettings.security = node.streamSecurity; - TlsSettings tlsSettings = new TlsSettings + TlsSettings tlsSettings = new() { allowInsecure = Utils.ToBool(node.allowInsecure.IsNullOrEmpty() ? config.coreBasicItem.defAllowInsecure.ToString().ToLower() : node.allowInsecure), alpn = node.GetAlpn(), @@ -587,7 +587,7 @@ namespace v2rayN.Handler { streamSettings.security = node.streamSecurity; - TlsSettings xtlsSettings = new TlsSettings + TlsSettings xtlsSettings = new() { allowInsecure = Utils.ToBool(node.allowInsecure.IsNullOrEmpty() ? config.coreBasicItem.defAllowInsecure.ToString().ToLower() : node.allowInsecure), alpn = node.GetAlpn(), @@ -608,7 +608,7 @@ namespace v2rayN.Handler switch (node.GetNetwork()) { case "kcp": - KcpSettings kcpSettings = new KcpSettings + KcpSettings kcpSettings = new() { mtu = config.kcpItem.mtu, tti = config.kcpItem.tti @@ -644,12 +644,8 @@ namespace v2rayN.Handler break; //ws case "ws": - WsSettings wsSettings = new WsSettings - { - }; - wsSettings.headers = new Headers - { - }; + WsSettings wsSettings = new(); + wsSettings.headers = new Headers(); string path = node.path; if (!string.IsNullOrWhiteSpace(host)) { @@ -675,7 +671,7 @@ namespace v2rayN.Handler break; //h2 case "h2": - HttpSettings httpSettings = new HttpSettings(); + HttpSettings httpSettings = new(); if (!string.IsNullOrWhiteSpace(host)) { @@ -691,7 +687,7 @@ namespace v2rayN.Handler break; //quic case "quic": - QuicSettings quicsettings = new QuicSettings + QuicSettings quicsettings = new() { security = host, key = node.path, @@ -714,7 +710,7 @@ namespace v2rayN.Handler } break; case "grpc": - var grpcSettings = new GrpcSettings + GrpcSettings grpcSettings = new() { serviceName = node.path, multiMode = (node.headerType == Global.GrpcmultiMode), @@ -730,7 +726,7 @@ namespace v2rayN.Handler //tcp if (node.headerType.Equals(Global.TcpHeaderHttp)) { - TcpSettings tcpSettings = new TcpSettings + TcpSettings tcpSettings = new() { header = new Header { @@ -799,7 +795,7 @@ namespace v2rayN.Handler } else { - List servers = new List(); + List servers = new(); string[] arrDNS = config.remoteDNS.Split(','); foreach (string str in arrDNS) @@ -828,9 +824,9 @@ namespace v2rayN.Handler if (config.guiItem.enableStatistics) { string tag = Global.InboundAPITagName; - API apiObj = new API(); - Policy policyObj = new Policy(); - SystemPolicy policySystemSetting = new SystemPolicy(); + API apiObj = new(); + Policy policyObj = new(); + SystemPolicy policySystemSetting = new(); string[] services = { "StatsService" }; @@ -847,8 +843,8 @@ namespace v2rayN.Handler if (!v2rayConfig.inbounds.Exists(item => item.tag == tag)) { - Inbounds apiInbound = new Inbounds(); - Inboundsettings apiInboundSettings = new Inboundsettings(); + Inbounds apiInbound = new(); + Inboundsettings apiInboundSettings = new(); apiInbound.tag = tag; apiInbound.listen = Global.Loopback; apiInbound.port = Global.statePort; @@ -860,7 +856,7 @@ namespace v2rayN.Handler if (!v2rayConfig.routing.rules.Exists(item => item.outboundTag == tag)) { - RulesItem apiRoutingRule = new RulesItem + RulesItem apiRoutingRule = new() { inboundTag = new List { tag }, outboundTag = tag, @@ -1126,7 +1122,7 @@ namespace v2rayN.Handler public static ProfileItem? ImportFromClientConfig(string fileName, out string msg) { msg = string.Empty; - ProfileItem profileItem = new ProfileItem(); + ProfileItem profileItem = new(); try { @@ -1265,7 +1261,7 @@ namespace v2rayN.Handler public static ProfileItem? ImportFromServerConfig(string fileName, out string msg) { msg = string.Empty; - ProfileItem profileItem = new ProfileItem(); + ProfileItem profileItem = new(); try { @@ -1446,8 +1442,8 @@ namespace v2rayN.Handler msg = ResUI.FailedGenDefaultConfiguration; return ""; } - List lstIpEndPoints = new List(); - List lstTcpConns = new List(); + List lstIpEndPoints = new(); + List lstTcpConns = new(); try { lstIpEndPoints.AddRange(IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()); @@ -1477,7 +1473,7 @@ namespace v2rayN.Handler { continue; } - if (it.configType == EConfigType.VMess || it.configType == EConfigType.VLESS) + if (it.configType is EConfigType.VMess or EConfigType.VLESS) { var item2 = LazyConfig.Instance.GetProfileItem(it.indexId); if (item2 is null || Utils.IsNullOrEmpty(item2.id) || !Utils.IsGuidByParse(item2.id)) @@ -1513,7 +1509,7 @@ namespace v2rayN.Handler it.allowTest = true; //inbound - Inbounds inbound = new Inbounds + Inbounds inbound = new() { listen = Global.Loopback, port = port, @@ -1540,7 +1536,7 @@ namespace v2rayN.Handler v2rayConfig.outbounds.Add(v2rayConfigCopy.outbounds[0]); //rule - RulesItem rule = new RulesItem + RulesItem rule = new() { inboundTag = new List { inbound.tag }, outboundTag = v2rayConfigCopy.outbounds[0].tag, diff --git a/v2rayN/v2rayN/Handler/CoreHandler.cs b/v2rayN/v2rayN/Handler/CoreHandler.cs index 87d7f063..4dc2ca6a 100644 --- a/v2rayN/v2rayN/Handler/CoreHandler.cs +++ b/v2rayN/v2rayN/Handler/CoreHandler.cs @@ -173,8 +173,8 @@ namespace v2rayN.Handler string fileName = CoreFindexe(_coreInfo); if (fileName == "") return; - var displayLog = node.configType == EConfigType.Custom ? node.displayLog : true; - Process p = new Process + var displayLog = node.configType != EConfigType.Custom || node.displayLog; + Process p = new() { StartInfo = new ProcessStartInfo { @@ -232,7 +232,7 @@ namespace v2rayN.Handler string fileName = CoreFindexe(coreInfo); if (fileName == "") return -1; - Process p = new Process + Process p = new() { StartInfo = new ProcessStartInfo { diff --git a/v2rayN/v2rayN/Handler/DownloadHandle.cs b/v2rayN/v2rayN/Handler/DownloadHandle.cs index 66fb7316..bdd70373 100644 --- a/v2rayN/v2rayN/Handler/DownloadHandle.cs +++ b/v2rayN/v2rayN/Handler/DownloadHandle.cs @@ -76,7 +76,7 @@ namespace v2rayN.Handler if (UpdateCompleted != null) { string msg = $"...{value}%"; - UpdateCompleted(this, new ResultEventArgs(value > 100 ? true : false, msg)); + UpdateCompleted(this, new ResultEventArgs(value > 100, msg)); } }; @@ -107,7 +107,7 @@ namespace v2rayN.Handler AllowAutoRedirect = false, Proxy = GetWebProxy(blProxy) }; - HttpClient client = new HttpClient(webRequestHandler); + HttpClient client = new(webRequestHandler); HttpResponseMessage response = await client.GetAsync(url); if (response.StatusCode.ToString() == "Redirect") @@ -203,7 +203,7 @@ namespace v2rayN.Handler } client.DefaultRequestHeaders.UserAgent.TryParseAdd(userAgent); - Uri uri = new Uri(url); + Uri uri = new(url); //Authorization Header if (!Utils.IsNullOrEmpty(uri.UserInfo)) { @@ -300,12 +300,11 @@ namespace v2rayN.Handler myHttpWebRequest.Timeout = downloadTimeout * 1000; myHttpWebRequest.Proxy = webProxy; - Stopwatch timer = new Stopwatch(); + Stopwatch timer = new(); timer.Start(); HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); - if (myHttpWebResponse.StatusCode != HttpStatusCode.OK - && myHttpWebResponse.StatusCode != HttpStatusCode.NoContent) + if (myHttpWebResponse.StatusCode is not HttpStatusCode.OK and not HttpStatusCode.NoContent) { msg = myHttpWebResponse.StatusDescription; } @@ -343,7 +342,7 @@ namespace v2rayN.Handler try { IPAddress ipa = IPAddress.Parse(ip); - IPEndPoint point = new IPEndPoint(ipa, port); + IPEndPoint point = new(ipa, port); sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(point); return true; diff --git a/v2rayN/v2rayN/Handler/LazyConfig.cs b/v2rayN/v2rayN/Handler/LazyConfig.cs index f0947dbf..101f433e 100644 --- a/v2rayN/v2rayN/Handler/LazyConfig.cs +++ b/v2rayN/v2rayN/Handler/LazyConfig.cs @@ -5,7 +5,7 @@ namespace v2rayN.Handler { public sealed class LazyConfig { - private static readonly Lazy _instance = new Lazy(() => new()); + private static readonly Lazy _instance = new(() => new()); private Config _config; private List coreInfos; @@ -193,7 +193,7 @@ namespace v2rayN.Handler private void InitCoreInfo() { - coreInfos = new List(); + coreInfos = new(16); coreInfos.Add(new CoreInfo { diff --git a/v2rayN/v2rayN/Handler/MainFormHandler.cs b/v2rayN/v2rayN/Handler/MainFormHandler.cs index 9c942757..cdf7215c 100644 --- a/v2rayN/v2rayN/Handler/MainFormHandler.cs +++ b/v2rayN/v2rayN/Handler/MainFormHandler.cs @@ -12,7 +12,7 @@ namespace v2rayN.Handler { public sealed class MainFormHandler { - private static readonly Lazy instance = new Lazy(() => new MainFormHandler()); + private static readonly Lazy instance = new(() => new()); //Action _updateUI; //private DownloadHandle downloadHandle2; @@ -42,19 +42,14 @@ namespace v2rayN.Handler { return new Icon(fileName); } - switch (index) + return index switch { - case 0: - return Properties.Resources.NotifyIcon1; - case 1: - return Properties.Resources.NotifyIcon2; - case 2: - return Properties.Resources.NotifyIcon3; - case 3: - return Properties.Resources.NotifyIcon2; - } - - return Properties.Resources.NotifyIcon1; + 0 => Properties.Resources.NotifyIcon1, + 1 => Properties.Resources.NotifyIcon2, + 2 => Properties.Resources.NotifyIcon3, + 3 => Properties.Resources.NotifyIcon2, + _ => Properties.Resources.NotifyIcon1, // default + }; } catch (Exception ex) { @@ -107,9 +102,9 @@ namespace v2rayN.Handler int width = 128; int height = 128; - Bitmap bitmap = new Bitmap(width, height); + Bitmap bitmap = new(width, height); Graphics graphics = Graphics.FromImage(bitmap); - SolidBrush drawBrush = new SolidBrush(color); + SolidBrush drawBrush = new(color); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //graphics.FillRectangle(drawBrush, new Rectangle(0, 0, width, height)); @@ -143,7 +138,7 @@ namespace v2rayN.Handler return; } - SaveFileDialog fileDialog = new SaveFileDialog + SaveFileDialog fileDialog = new() { Filter = "Config|*.json", FilterIndex = 2, @@ -176,14 +171,13 @@ namespace v2rayN.Handler { return; } - if (item.configType != EConfigType.VMess - && item.configType != EConfigType.VLESS) + if (item.configType is not EConfigType.VMess and not EConfigType.VLESS) { UI.Show(ResUI.NonVmessService); return; } - SaveFileDialog fileDialog = new SaveFileDialog + SaveFileDialog fileDialog = new() { Filter = "Config|*.json", FilterIndex = 2, @@ -212,14 +206,14 @@ namespace v2rayN.Handler public void BackupGuiNConfig(Config config, bool auto = false) { - string fileName = $"guiNConfig_{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff")}.json"; + string fileName = $"guiNConfig_{DateTime.Now:yyyy_MM_dd_HH_mm_ss_fff}.json"; if (auto) { fileName = Utils.GetBackupPath(fileName); } else { - SaveFileDialog fileDialog = new SaveFileDialog + SaveFileDialog fileDialog = new() { FileName = fileName, Filter = "guiNConfig|*.json", @@ -254,7 +248,7 @@ namespace v2rayN.Handler public bool RestoreGuiNConfig(ref Config config) { var fileContent = string.Empty; - using (OpenFileDialog fileDialog = new OpenFileDialog()) + using (OpenFileDialog fileDialog = new()) { fileDialog.InitialDirectory = Utils.GetBackupPath(""); fileDialog.Filter = "guiNConfig|*.json|All|*.*"; @@ -381,12 +375,12 @@ namespace v2rayN.Handler try { HotkeyManager.Current.AddOrReplace(((int)item.eGlobalHotkey).ToString(), gesture, handler); - var msg = string.Format(ResUI.RegisterGlobalHotkeySuccessfully, $"{item.eGlobalHotkey.ToString()}"); + var msg = string.Format(ResUI.RegisterGlobalHotkeySuccessfully, $"{item.eGlobalHotkey}"); update(false, msg); } catch (Exception ex) { - var msg = string.Format(ResUI.RegisterGlobalHotkeyFailed, $"{item.eGlobalHotkey.ToString()}", ex.Message); + var msg = string.Format(ResUI.RegisterGlobalHotkeyFailed, $"{item.eGlobalHotkey}", ex.Message); update(false, msg); Utils.SaveLog(msg); } diff --git a/v2rayN/v2rayN/Handler/ProfileExHandler.cs b/v2rayN/v2rayN/Handler/ProfileExHandler.cs index 4d7b15c8..7851b5cf 100644 --- a/v2rayN/v2rayN/Handler/ProfileExHandler.cs +++ b/v2rayN/v2rayN/Handler/ProfileExHandler.cs @@ -5,7 +5,7 @@ namespace v2rayN.Handler { class ProfileExHandler { - private static readonly Lazy _instance = new Lazy(() => new()); + private static readonly Lazy _instance = new(() => new()); private List _lstProfileEx; public List ProfileExs => _lstProfileEx; public static ProfileExHandler Instance => _instance.Value; diff --git a/v2rayN/v2rayN/Handler/ProxySetting.cs b/v2rayN/v2rayN/Handler/ProxySetting.cs index 446b1caa..5e82b8a5 100644 --- a/v2rayN/v2rayN/Handler/ProxySetting.cs +++ b/v2rayN/v2rayN/Handler/ProxySetting.cs @@ -12,14 +12,14 @@ namespace v2rayN.Handler public static bool SetProxy(string? strProxy, string? exceptions, int type) { - InternetPerConnOptionList list = new InternetPerConnOptionList(); + InternetPerConnOptionList list = new(); int optionCount = 1; if (type == 1) { optionCount = 1; } - else if (type == 2 || type == 4) + else if (type is 2 or 4) { optionCount = Utils.IsNullOrEmpty(exceptions) ? 2 : 3; } @@ -71,12 +71,12 @@ namespace v2rayN.Handler { if (Environment.Is64BitOperatingSystem) { - IntPtr opt = new IntPtr(optionsPtr.ToInt64() + (i * optSize)); + IntPtr opt = new(optionsPtr.ToInt64() + (i * optSize)); Marshal.StructureToPtr(options[i], opt, false); } else { - IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize)); + IntPtr opt = new(optionsPtr.ToInt32() + (i * optSize)); Marshal.StructureToPtr(options[i], opt, false); } } @@ -84,7 +84,7 @@ namespace v2rayN.Handler list.options = optionsPtr; // and then make a pointer out of the whole list - IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((int)list.dwSize); + IntPtr ipcoListPtr = Marshal.AllocCoTaskMem(list.dwSize); Marshal.StructureToPtr(list, ipcoListPtr, false); // and finally, call the API method! @@ -200,7 +200,7 @@ namespace v2rayN.Handler } } //获得代理的IP和端口 - public static string GetProxyProxyServer() + public static string? GetProxyProxyServer() { using RegistryKey? rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); string ProxyServer = rk.GetValue("ProxyServer").ToString(); diff --git a/v2rayN/v2rayN/Handler/QRCodeHelper.cs b/v2rayN/v2rayN/Handler/QRCodeHelper.cs index ff5528d2..bbd8c7ee 100644 --- a/v2rayN/v2rayN/Handler/QRCodeHelper.cs +++ b/v2rayN/v2rayN/Handler/QRCodeHelper.cs @@ -13,9 +13,9 @@ namespace v2rayN.Handler { try { - QRCodeGenerator qrGenerator = new QRCodeGenerator(); + QRCodeGenerator qrGenerator = new(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(strContent, QRCodeGenerator.ECCLevel.H); - XamlQRCode qrCode = new XamlQRCode(qrCodeData); + XamlQRCode qrCode = new(qrCodeData); DrawingImage qrCodeAsXaml = qrCode.GetGraphic(40); return qrCodeAsXaml; } diff --git a/v2rayN/v2rayN/Handler/ShareHandler.cs b/v2rayN/v2rayN/Handler/ShareHandler.cs index d76b201b..fab53a60 100644 --- a/v2rayN/v2rayN/Handler/ShareHandler.cs +++ b/v2rayN/v2rayN/Handler/ShareHandler.cs @@ -46,7 +46,7 @@ namespace v2rayN.Handler { string url = string.Empty; - VmessQRCode vmessQRCode = new VmessQRCode + VmessQRCode vmessQRCode = new() { v = item.configVersion.ToString(), ps = item.remarks.TrimEx(), //备注也许很长 ; @@ -250,7 +250,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)); } @@ -273,7 +273,7 @@ namespace v2rayN.Handler public static ProfileItem? ImportFromClipboardConfig(string clipboardData, out string msg) { msg = string.Empty; - ProfileItem profileItem = new ProfileItem(); + ProfileItem profileItem = new(); try { @@ -365,7 +365,7 @@ namespace v2rayN.Handler configType = EConfigType.VMess }; - result = result.Substring(Global.vmessProtocol.Length); + result = result[Global.vmessProtocol.Length..]; result = Utils.Base64Decode(result); //转成Json @@ -409,7 +409,7 @@ namespace v2rayN.Handler private static ProfileItem? ResolveVmess4Kitsunebi(string result) { - ProfileItem profileItem = new ProfileItem + ProfileItem profileItem = new() { configType = EConfigType.VMess }; @@ -428,7 +428,7 @@ namespace v2rayN.Handler } string[] arr21 = arr1[0].Split(':'); string[] arr22 = arr1[1].Split(':'); - if (arr21.Length != 2 || arr21.Length != 2) + if (arr21.Length != 2 || arr22.Length != 2) { return null; } @@ -447,13 +447,13 @@ namespace v2rayN.Handler private static ProfileItem? ResolveStdVmess(string result) { - ProfileItem i = new ProfileItem + ProfileItem i = new() { configType = EConfigType.VMess, security = "auto" }; - Uri u = new Uri(result); + Uri u = new(result); i.address = u.IdnHost; i.port = u.Port; @@ -537,7 +537,7 @@ namespace v2rayN.Handler { return null; } - ProfileItem server = new ProfileItem + ProfileItem server = new() { remarks = parsedUrl.GetComponents(UriComponents.Fragment, UriFormat.Unescaped), address = parsedUrl.IdnHost, @@ -589,8 +589,8 @@ namespace v2rayN.Handler return server; } - private static readonly Regex UrlFinder = new Regex(@"ss://(?[A-Za-z0-9+-/=_]+)(?:#(?\S+))?", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex DetailsParser = new Regex(@"^((?.+?):(?.*)@(?.+?):(?\d+?))$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex UrlFinder = new(@"ss://(?[A-Za-z0-9+-/=_]+)(?:#(?\S+))?", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex DetailsParser = new(@"^((?.+?):(?.*)@(?.+?):(?\d+?))$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static ProfileItem? ResolveSSLegacy(string result) { @@ -598,7 +598,7 @@ namespace v2rayN.Handler if (!match.Success) return null; - ProfileItem server = new ProfileItem(); + ProfileItem server = new(); var base64 = match.Groups["base64"].Value.TrimEnd('/'); var tag = match.Groups["tag"].Value; if (!Utils.IsNullOrEmpty(tag)) @@ -624,16 +624,16 @@ namespace v2rayN.Handler } - private static readonly Regex StdVmessUserInfo = new Regex( + private static readonly Regex StdVmessUserInfo = new( @"^(?[a-z]+)(\+(?[a-z]+))?:(?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$", RegexOptions.Compiled); private static ProfileItem? ResolveSocks(string result) { - ProfileItem profileItem = new ProfileItem + ProfileItem profileItem = new() { configType = EConfigType.Socks }; - result = result.Substring(Global.socksProtocol.Length); + result = result[Global.socksProtocol.Length..]; //remark int indexRemark = result.IndexOf("#"); if (indexRemark > 0) @@ -643,7 +643,7 @@ namespace v2rayN.Handler profileItem.remarks = Utils.UrlDecode(result.Substring(indexRemark + 1, result.Length - indexRemark - 1)); } catch { } - result = result.Substring(0, indexRemark); + result = result[..indexRemark]; } //part decode int indexS = result.IndexOf("@"); @@ -667,8 +667,8 @@ namespace v2rayN.Handler { return null; } - profileItem.address = arr1[1].Substring(0, indexPort); - profileItem.port = Utils.ToInt(arr1[1].Substring(indexPort + 1, arr1[1].Length - (indexPort + 1))); + profileItem.address = arr1[1][..indexPort]; + profileItem.port = Utils.ToInt(arr1[1][(indexPort + 1)..]); profileItem.security = arr21[0]; profileItem.id = arr21[1]; @@ -686,7 +686,7 @@ namespace v2rayN.Handler { return null; } - ProfileItem server = new ProfileItem + ProfileItem server = new() { remarks = parsedUrl.GetComponents(UriComponents.Fragment, UriFormat.Unescaped), address = parsedUrl.IdnHost, @@ -708,12 +708,12 @@ namespace v2rayN.Handler private static ProfileItem ResolveTrojan(string result) { - ProfileItem item = new ProfileItem + ProfileItem item = new() { configType = EConfigType.Trojan }; - Uri url = new Uri(result); + Uri url = new(result); item.address = url.IdnHost; item.port = url.Port; @@ -727,13 +727,13 @@ namespace v2rayN.Handler } private static ProfileItem ResolveStdVLESS(string result) { - ProfileItem item = new ProfileItem + ProfileItem item = new() { configType = EConfigType.VLESS, security = "none" }; - Uri url = new Uri(result); + Uri url = new(result); item.address = url.IdnHost; item.port = url.Port; diff --git a/v2rayN/v2rayN/Handler/SpeedtestHandler.cs b/v2rayN/v2rayN/Handler/SpeedtestHandler.cs index 531780f3..20dae157 100644 --- a/v2rayN/v2rayN/Handler/SpeedtestHandler.cs +++ b/v2rayN/v2rayN/Handler/SpeedtestHandler.cs @@ -150,7 +150,7 @@ namespace v2rayN.Handler DownloadHandle downloadHandle = new DownloadHandle(); //Thread.Sleep(5000); - List tasks = new List(); + List tasks = new(); foreach (var it in _selecteds) { if (!it.allowTest) @@ -166,7 +166,7 @@ namespace v2rayN.Handler try { - WebProxy webProxy = new WebProxy(Global.Loopback, it.port); + WebProxy webProxy = new(Global.Loopback, it.port); string output = GetRealPingTime(downloadHandle, webProxy); await ProfileExHandler.Instance.SetTestDelay(it.indexId, output); @@ -214,7 +214,7 @@ namespace v2rayN.Handler string url = _config.speedTestItem.speedTestUrl; var timeout = _config.speedTestItem.speedTestTimeout; - DownloadHandle downloadHandle = new DownloadHandle(); + DownloadHandle downloadHandle = new(); foreach (var it in _selecteds) { @@ -236,7 +236,7 @@ namespace v2rayN.Handler var item = LazyConfig.Instance.GetProfileItem(it.indexId); if (item is null) continue; - WebProxy webProxy = new WebProxy(Global.Loopback, it.port); + WebProxy webProxy = new(Global.Loopback, it.port); await downloadHandle.DownloadDataAsync(url, webProxy, timeout, async (bool success, string msg) => { @@ -270,7 +270,7 @@ namespace v2rayN.Handler string url = _config.speedTestItem.speedTestUrl; var timeout = _config.speedTestItem.speedTestTimeout; - DownloadHandle downloadHandle = new DownloadHandle(); + DownloadHandle downloadHandle = new(); foreach (var it in _selecteds) { @@ -287,7 +287,7 @@ namespace v2rayN.Handler var item = LazyConfig.Instance.GetProfileItem(it.indexId); if (item is null) continue; - WebProxy webProxy = new WebProxy(Global.Loopback, it.port); + WebProxy webProxy = new(Global.Loopback, it.port); _ = downloadHandle.DownloadDataAsync(url, webProxy, timeout, async (bool success, string msg) => { decimal.TryParse(msg, out decimal dec); @@ -338,11 +338,11 @@ namespace v2rayN.Handler ipAddress = ipHostInfo.AddressList[0]; } - Stopwatch timer = new Stopwatch(); + Stopwatch timer = new(); timer.Start(); - IPEndPoint endPoint = new IPEndPoint(ipAddress, port); - Socket clientSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + IPEndPoint endPoint = new(ipAddress, port); + using Socket clientSocket = new(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = clientSocket.BeginConnect(endPoint, null, null); if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5))) @@ -351,7 +351,6 @@ namespace v2rayN.Handler timer.Stop(); responseTime = timer.Elapsed.Milliseconds; - clientSocket.Close(); } catch (Exception ex) { @@ -373,7 +372,7 @@ namespace v2rayN.Handler { int timeout = 30; int echoNum = 2; - Ping pingSender = new Ping(); + using Ping pingSender = new(); for (int i = 0; i < echoNum; i++) { PingReply reply = pingSender.Send(host, timeout); diff --git a/v2rayN/v2rayN/Handler/StatisticsHandler.cs b/v2rayN/v2rayN/Handler/StatisticsHandler.cs index 1421f239..fbd1eabc 100644 --- a/v2rayN/v2rayN/Handler/StatisticsHandler.cs +++ b/v2rayN/v2rayN/Handler/StatisticsHandler.cs @@ -229,7 +229,7 @@ namespace v2rayN.Handler try { // TCP stack please do me a favor - TcpListener l = new TcpListener(IPAddress.Loopback, 0); + TcpListener l = new(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); diff --git a/v2rayN/v2rayN/Handler/SysProxyHandle.cs b/v2rayN/v2rayN/Handler/SysProxyHandle.cs index 1c979b8e..eba43439 100644 --- a/v2rayN/v2rayN/Handler/SysProxyHandle.cs +++ b/v2rayN/v2rayN/Handler/SysProxyHandle.cs @@ -154,85 +154,82 @@ 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(false); + using AutoResetEvent errorWaitHandle = new(false); + using Process process = new(); + + // 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(1024); + StringBuilder error = new(1024); + + 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(1024); - StringBuilder error = new StringBuilder(1024); - - 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/TunHandler.cs b/v2rayN/v2rayN/Handler/TunHandler.cs index 04c0075b..eee1086c 100644 --- a/v2rayN/v2rayN/Handler/TunHandler.cs +++ b/v2rayN/v2rayN/Handler/TunHandler.cs @@ -8,7 +8,7 @@ namespace v2rayN.Base { public sealed class TunHandler { - private static readonly Lazy _instance = new Lazy(() => new()); + private static readonly Lazy _instance = new(() => new()); public static TunHandler Instance => _instance.Value; private string _tunConfigName = "tunConfig.json"; private static Config _config; @@ -108,7 +108,7 @@ namespace v2rayN.Base else { var dtNow = DateTime.Now; - var log_output = $"\"output\": \"{Utils.GetLogPath($"singbox_{dtNow.ToString("yyyy-MM-dd")}.txt")}\", "; + var log_output = $"\"output\": \"{Utils.GetLogPath($"singbox_{dtNow:yyyy-MM-dd}.txt")}\", "; configStr = configStr.Replace("$log_output$", $"{log_output.Replace(@"\", @"\\")}"); } @@ -116,8 +116,8 @@ namespace v2rayN.Base configStr = configStr.Replace("$socksPort$", $"{_socksPort}"); //exe - List lstDnsExe = new List(); - List lstDirectExe = new List(); + List lstDnsExe = new(); + List lstDirectExe = new(); var coreInfos = LazyConfig.Instance.GetCoreInfos(); foreach (var it in coreInfos) { @@ -240,7 +240,7 @@ namespace v2rayN.Base return; } var showWindow = _config.tunModeItem.showWindow; - Process p = new Process + Process p = new() { StartInfo = new ProcessStartInfo { diff --git a/v2rayN/v2rayN/Handler/UpdateHandle.cs b/v2rayN/v2rayN/Handler/UpdateHandle.cs index 0172fe5e..8075eef6 100644 --- a/v2rayN/v2rayN/Handler/UpdateHandle.cs +++ b/v2rayN/v2rayN/Handler/UpdateHandle.cs @@ -35,7 +35,7 @@ namespace v2rayN.Handler _updateFunc = update; var url = string.Empty; - DownloadHandle downloadHandle = new DownloadHandle(); + DownloadHandle downloadHandle = new(); downloadHandle.UpdateCompleted += (sender2, args) => { if (args.Success) @@ -46,7 +46,7 @@ namespace v2rayN.Handler { string fileName = Utils.GetTempPath(Utils.GetDownloadFileName(url)); fileName = Utils.UrlEncode(fileName); - Process process = new Process + Process process = new() { StartInfo = new ProcessStartInfo { @@ -101,7 +101,7 @@ namespace v2rayN.Handler _updateFunc = update; var url = string.Empty; - DownloadHandle downloadHandle = new DownloadHandle(); + DownloadHandle downloadHandle = new(); downloadHandle.UpdateCompleted += (sender2, args) => { if (args.Success) @@ -253,7 +253,7 @@ namespace v2rayN.Handler _updateFunc = update; var url = string.Format(Global.geoUrl, geoName); - DownloadHandle downloadHandle = new DownloadHandle(); + DownloadHandle downloadHandle = new(); downloadHandle.UpdateCompleted += (sender2, args) => { if (args.Success) @@ -360,7 +360,7 @@ namespace v2rayN.Handler return ""; } - Process p = new Process(); + using Process p = new(); p.StartInfo.FileName = filePath; p.StartInfo.Arguments = coreInfo.versionArg; p.StartInfo.WorkingDirectory = Utils.StartupPath(); diff --git a/v2rayN/v2rayN/Tool/Job.cs b/v2rayN/v2rayN/Tool/Job.cs index 8f9351b7..3120d515 100644 --- a/v2rayN/v2rayN/Tool/Job.cs +++ b/v2rayN/v2rayN/Tool/Job.cs @@ -16,12 +16,12 @@ namespace v2rayN { handle = CreateJobObject(IntPtr.Zero, null); IntPtr extendedInfoPtr = IntPtr.Zero; - JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION + JOBOBJECT_BASIC_LIMIT_INFORMATION info = new() { LimitFlags = 0x2000 }; - JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION + JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new() { BasicLimitInformation = info }; @@ -100,7 +100,7 @@ namespace v2rayN #region Interop [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - private static extern IntPtr CreateJobObject(IntPtr a, string lpName); + private static extern IntPtr CreateJobObject(IntPtr a, string? lpName); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, UInt32 cbJobObjectInfoLength); diff --git a/v2rayN/v2rayN/Tool/Logging.cs b/v2rayN/v2rayN/Tool/Logging.cs index 6759a2d4..be43a2bb 100644 --- a/v2rayN/v2rayN/Tool/Logging.cs +++ b/v2rayN/v2rayN/Tool/Logging.cs @@ -9,8 +9,8 @@ namespace v2rayN.Tool { public static void Setup() { - LoggingConfiguration config = new LoggingConfiguration(); - FileTarget fileTarget = new FileTarget(); + LoggingConfiguration config = new(); + FileTarget fileTarget = new(); config.AddTarget("file", fileTarget); fileTarget.Layout = "${longdate}-${level:uppercase=true} ${message}"; fileTarget.FileName = Utils.GetLogPath("${shortdate}.txt"); diff --git a/v2rayN/v2rayN/ViewModels/AddServer2ViewModel.cs b/v2rayN/v2rayN/ViewModels/AddServer2ViewModel.cs index 78f78b6f..6d739108 100644 --- a/v2rayN/v2rayN/ViewModels/AddServer2ViewModel.cs +++ b/v2rayN/v2rayN/ViewModels/AddServer2ViewModel.cs @@ -106,7 +106,7 @@ namespace v2rayN.ViewModels { UI.Show(ResUI.CustomServerTips); - OpenFileDialog fileDialog = new OpenFileDialog + OpenFileDialog fileDialog = new() { Multiselect = false, Filter = "Config|*.json|YAML|*.yaml;*.yml|All|*.*" @@ -121,10 +121,7 @@ namespace v2rayN.ViewModels return; } var item = LazyConfig.Instance.GetProfileItem(SelectedSource.indexId); - if (item is null) - { - item = SelectedSource; - } + item ??= SelectedSource; item.address = fileName; if (ConfigHandler.AddCustomServer(ref _config, item, false) == 0) { diff --git a/v2rayN/v2rayN/ViewModels/MainWindowViewModel.cs b/v2rayN/v2rayN/ViewModels/MainWindowViewModel.cs index 9dd0ccb2..79be3452 100644 --- a/v2rayN/v2rayN/ViewModels/MainWindowViewModel.cs +++ b/v2rayN/v2rayN/ViewModels/MainWindowViewModel.cs @@ -37,7 +37,7 @@ namespace v2rayN.ViewModels private string _serverFilter = string.Empty; private static Config _config; private NoticeHandler? _noticeHandler; - private readonly PaletteHelper _paletteHelper = new PaletteHelper(); + private readonly PaletteHelper _paletteHelper = new(); private Dictionary _dicHeaderSort = new(); private Action _updateView; @@ -254,7 +254,7 @@ namespace v2rayN.ViewModels SystemProxySelected = (int)_config.sysProxyType; this.WhenAnyValue( x => x.SystemProxySelected, - y => y != null && y >= 0) + y => y >= 0) .Subscribe(c => DoSystemProxySelected(c)); this.WhenAnyValue( @@ -820,7 +820,7 @@ namespace v2rayN.ViewModels private int GetProfileItems(out List lstSelecteds) { lstSelecteds = new List(); - if (SelectedProfiles == null || SelectedProfiles.Count() <= 0) + if (SelectedProfiles == null || SelectedProfiles.Count <= 0) { return -1; } @@ -1169,7 +1169,7 @@ namespace v2rayN.ViewModels return; } - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var it in lstSelecteds) { string url = ShareHandler.GetShareUrl(it); @@ -1194,10 +1194,10 @@ namespace v2rayN.ViewModels return; } - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); foreach (var it in lstSelecteds) { - string url = ShareHandler.GetShareUrl(it); + string? url = ShareHandler.GetShareUrl(it); if (Utils.IsNullOrEmpty(url)) { continue; @@ -1268,7 +1268,7 @@ namespace v2rayN.ViewModels private void ImportOldGuiConfig() { - OpenFileDialog fileDialog = new OpenFileDialog + OpenFileDialog fileDialog = new() { Multiselect = false, Filter = "guiNConfig|*.json|All|*.*" @@ -1532,7 +1532,7 @@ namespace v2rayN.ViewModels public void ShowHideWindow(bool? blShow) { - var bl = blShow.HasValue ? blShow.Value : !Global.ShowInTaskbar; + var bl = blShow ?? !Global.ShowInTaskbar; if (bl) { //Application.Current.MainWindow.ShowInTaskbar = true; @@ -1651,7 +1651,7 @@ namespace v2rayN.ViewModels public void InboundDisplayStaus() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); sb.Append($"[{Global.InboundSocks}:{LazyConfig.Instance.GetLocalPort(Global.InboundSocks)}]"); sb.Append(" | "); //if (_config.sysProxyType == ESysProxyType.ForcedChange) @@ -1662,21 +1662,21 @@ namespace v2rayN.ViewModels //{ sb.Append($"[{Global.InboundHttp}:{LazyConfig.Instance.GetLocalPort(Global.InboundHttp)}]"); //} - InboundDisplay = $"{ResUI.LabLocal}:{sb.ToString()}"; + InboundDisplay = $"{ResUI.LabLocal}:{sb}"; if (_config.inbound[0].allowLANConn) { if (_config.inbound[0].newPort4LAN) { - StringBuilder sb2 = new StringBuilder(); + StringBuilder sb2 = new(); sb2.Append($"[{Global.InboundSocks}:{LazyConfig.Instance.GetLocalPort(Global.InboundSocks2)}]"); sb2.Append(" | "); sb2.Append($"[{Global.InboundHttp}:{LazyConfig.Instance.GetLocalPort(Global.InboundHttp2)}]"); - InboundLanDisplay = $"{ResUI.LabLAN}:{sb2.ToString()}"; + InboundLanDisplay = $"{ResUI.LabLAN}:{sb2}"; } else { - InboundLanDisplay = $"{ResUI.LabLAN}:{sb.ToString()}"; + InboundLanDisplay = $"{ResUI.LabLAN}:{sb}"; } } else @@ -1713,10 +1713,10 @@ namespace v2rayN.ViewModels .Delay(TimeSpan.FromSeconds(1)) .Subscribe(x => { - Application.Current.Dispatcher.Invoke((Action)(() => + Application.Current.Dispatcher.Invoke(() => { ShowHideWindow(false); - })); + }); }); } }