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 b99f507f..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; } @@ -205,7 +205,7 @@ namespace v2rayN.Handler } - LazyConfig.Instance.SetConfig(ref config); + LazyConfig.Instance.SetConfig(config); return 0; } /// @@ -438,7 +438,7 @@ namespace v2rayN.Handler /// /// /// - public static int SetDefaultServerIndex(ref Config config, string indexId) + public static int SetDefaultServerIndex(ref Config config, string? indexId) { if (Utils.IsNullOrEmpty(indexId)) { @@ -460,7 +460,7 @@ namespace v2rayN.Handler return 0; } var allItems = LazyConfig.Instance.ProfileItemIndexs(""); - if (allItems.Where(t => t == config.indexId).Count() > 0) + if (allItems.Where(t => t == config.indexId).Any()) { return 0; } @@ -468,13 +468,13 @@ namespace v2rayN.Handler { return SetDefaultServerIndex(ref config, lstProfile[0].indexId); } - if (allItems.Count() > 0) + if (allItems.Count > 0) { return SetDefaultServerIndex(ref config, allItems.FirstOrDefault()); } return -1; } - public static ProfileItem GetDefaultServer(ref Config config) + public static ProfileItem? GetDefaultServer(ref Config config) { var item = LazyConfig.Instance.GetProfileItem(config.indexId); if (item is null) @@ -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) @@ -1041,7 +1041,7 @@ namespace v2rayN.Handler ProfileItem profileItem = new(); //Is v2ray configuration - V2rayConfig v2rayConfig = Utils.FromJson(clipboardData); + V2rayConfig? v2rayConfig = Utils.FromJson(clipboardData); if (v2rayConfig != null && v2rayConfig.inbounds != null && v2rayConfig.inbounds.Count > 0 @@ -1176,7 +1176,7 @@ namespace v2rayN.Handler public static int AddBatchServers(ref Config config, string clipboardData, string subid, bool isSub) { - List lstOriSub = null; + List? lstOriSub = null; if (isSub && !Utils.IsNullOrEmpty(subid)) { lstOriSub = LazyConfig.Instance.ProfileItems(subid); @@ -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 be92a35b..b0d18e31 100644 --- a/v2rayN/v2rayN/Handler/CoreConfigHandler.cs +++ b/v2rayN/v2rayN/Handler/CoreConfigHandler.cs @@ -25,7 +25,7 @@ namespace v2rayN.Handler /// /// /// - public static int GenerateClientConfig(ProfileItem node, string fileName, out string msg, out string content) + public static int GenerateClientConfig(ProfileItem node, string? fileName, out string msg, out string content) { content = string.Empty; try @@ -43,7 +43,7 @@ namespace v2rayN.Handler } else { - V2rayConfig v2rayConfig = null; + V2rayConfig? v2rayConfig = null; if (GenerateClientConfigContent(node, false, ref v2rayConfig, out msg) != 0) { return -1; @@ -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 { @@ -114,11 +114,11 @@ namespace v2rayN.Handler { v2rayConfig.inbounds = new List(); - Inbounds inbound = GetInbound(config.inbound[0], Global.InboundSocks, 0, true); + Inbounds? inbound = GetInbound(config.inbound[0], Global.InboundSocks, 0, true); v2rayConfig.inbounds.Add(inbound); //http - Inbounds inbound2 = GetInbound(config.inbound[0], Global.InboundHttp, 1, false); + Inbounds? inbound2 = GetInbound(config.inbound[0], Global.InboundHttp, 1, false); v2rayConfig.inbounds.Add(inbound2); if (config.inbound[0].allowLANConn) @@ -157,7 +157,7 @@ namespace v2rayN.Handler return 0; } - private static Inbounds GetInbound(InItem inItem, string tag, int offset, bool bSocks) + private static Inbounds? GetInbound(InItem inItem, string tag, int offset, bool bSocks) { string result = Utils.GetEmbedText(Global.v2raySampleInbound); if (Utils.IsNullOrEmpty(result)) @@ -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, @@ -957,7 +953,7 @@ namespace v2rayN.Handler return 0; } - public static int GenerateClientConfigContent(ProfileItem node, bool blExport, ref V2rayConfig v2rayConfig, out string msg) + public static int GenerateClientConfigContent(ProfileItem node, bool blExport, ref V2rayConfig? v2rayConfig, out string msg) { try { @@ -1034,7 +1030,7 @@ namespace v2rayN.Handler return -1; } - V2rayConfig v2rayConfig = Utils.FromJson(result); + V2rayConfig? v2rayConfig = Utils.FromJson(result); if (v2rayConfig == null) { msg = ResUI.FailedGenDefaultConfiguration; @@ -1123,10 +1119,10 @@ namespace v2rayN.Handler #region Import (export) client/server configuration - public static ProfileItem ImportFromClientConfig(string fileName, out string msg) + public static ProfileItem? ImportFromClientConfig(string fileName, out string msg) { msg = string.Empty; - ProfileItem profileItem = new ProfileItem(); + ProfileItem profileItem = new(); try { @@ -1137,7 +1133,7 @@ namespace v2rayN.Handler return null; } - V2rayConfig v2rayConfig = Utils.FromJson(result); + V2rayConfig? v2rayConfig = Utils.FromJson(result); if (v2rayConfig == null) { msg = ResUI.FailedConversionConfiguration; @@ -1262,10 +1258,10 @@ namespace v2rayN.Handler return profileItem; } - public static ProfileItem ImportFromServerConfig(string fileName, out string msg) + public static ProfileItem? ImportFromServerConfig(string fileName, out string msg) { msg = string.Empty; - ProfileItem profileItem = new ProfileItem(); + ProfileItem profileItem = new(); try { @@ -1276,7 +1272,7 @@ namespace v2rayN.Handler return null; } - V2rayConfig v2rayConfig = Utils.FromJson(result); + V2rayConfig? v2rayConfig = Utils.FromJson(result); if (v2rayConfig == null) { msg = ResUI.FailedConversionConfiguration; @@ -1401,7 +1397,7 @@ namespace v2rayN.Handler public static int Export2ClientConfig(ProfileItem node, string fileName, out string msg) { - V2rayConfig v2rayConfig = null; + V2rayConfig? v2rayConfig = null; if (GenerateClientConfigContent(node, true, ref v2rayConfig, out msg) != 0) { return -1; @@ -1440,14 +1436,14 @@ namespace v2rayN.Handler return ""; } - V2rayConfig v2rayConfig = Utils.FromJson(result); + V2rayConfig? v2rayConfig = Utils.FromJson(result); if (v2rayConfig == null) { 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, @@ -1523,7 +1519,7 @@ namespace v2rayN.Handler v2rayConfig.inbounds.Add(inbound); //outbound - V2rayConfig v2rayConfigCopy = Utils.FromJson(result); + V2rayConfig? v2rayConfigCopy = Utils.FromJson(result); var item = LazyConfig.Instance.GetProfileItem(it.indexId); if (item is null) { @@ -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 f5ac0957..4dc2ca6a 100644 --- a/v2rayN/v2rayN/Handler/CoreHandler.cs +++ b/v2rayN/v2rayN/Handler/CoreHandler.cs @@ -12,9 +12,9 @@ namespace v2rayN.Handler class CoreHandler { private static string _coreCConfigRes = Global.coreConfigFileName; - private CoreInfo _coreInfo; + private CoreInfo? _coreInfo; private int _processId = 0; - private Process _process; + private Process? _process; Action _updateFunc; public CoreHandler(Action update) @@ -108,7 +108,7 @@ namespace v2rayN.Handler Process[] existing = Process.GetProcessesByName(vName); foreach (Process p in existing) { - string path = p.MainModule.FileName; + string? path = p.MainModule?.FileName; if (path == $"{Utils.GetBinPath(vName, _coreInfo.coreType)}.exe") { KillProcess(p); @@ -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 { @@ -193,7 +193,7 @@ namespace v2rayN.Handler { p.OutputDataReceived += (sender, e) => { - if (!String.IsNullOrEmpty(e.Data)) + if (!string.IsNullOrEmpty(e.Data)) { string msg = e.Data + Environment.NewLine; ShowMsg(false, msg); @@ -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 caa463ea..bdd70373 100644 --- a/v2rayN/v2rayN/Handler/DownloadHandle.cs +++ b/v2rayN/v2rayN/Handler/DownloadHandle.cs @@ -16,7 +16,7 @@ namespace v2rayN.Handler { public event EventHandler UpdateCompleted; - public event ErrorEventHandler Error; + public event ErrorEventHandler? Error; public class ResultEventArgs : EventArgs @@ -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)); } }; @@ -99,7 +99,7 @@ namespace v2rayN.Handler } } - public async Task UrlRedirectAsync(string url, bool blProxy) + public async Task UrlRedirectAsync(string url, bool blProxy) { Utils.SetSecurityProtocol(LazyConfig.Instance.GetConfig().guiItem.enableSecurityProtocolTls13); var webRequestHandler = new SocketsHttpHandler @@ -107,12 +107,12 @@ 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") { - return response.Headers.Location.ToString(); + return response.Headers.Location?.ToString(); } else { @@ -121,7 +121,7 @@ namespace v2rayN.Handler } } - public async Task TryDownloadString(string url, bool blProxy, string userAgent) + public async Task TryDownloadString(string url, bool blProxy, string userAgent) { try { @@ -161,14 +161,12 @@ namespace v2rayN.Handler try { - using (var wc = new WebClient()) + using var wc = new WebClient(); + wc.Proxy = GetWebProxy(blProxy); + var result3 = await wc.DownloadStringTaskAsync(url); + if (!Utils.IsNullOrEmpty(result3)) { - wc.Proxy = GetWebProxy(blProxy); - var result3 = await wc.DownloadStringTaskAsync(url); - if (!Utils.IsNullOrEmpty(result3)) - { - return result3; - } + return result3; } } catch (Exception ex) @@ -189,7 +187,7 @@ namespace v2rayN.Handler /// DownloadString /// /// - public async Task DownloadStringAsync(string url, bool blProxy, string userAgent) + public async Task DownloadStringAsync(string url, bool blProxy, string userAgent) { try { @@ -205,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)) { @@ -234,7 +232,7 @@ namespace v2rayN.Handler /// DownloadString /// /// - public async Task DownloadStringViaDownloader(string url, bool blProxy, string userAgent) + public async Task DownloadStringViaDownloader(string url, bool blProxy, string userAgent) { try { @@ -262,7 +260,7 @@ namespace v2rayN.Handler } - public int RunAvailabilityCheck(WebProxy webProxy) + public int RunAvailabilityCheck(WebProxy? webProxy) { try { @@ -302,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; } @@ -324,7 +321,7 @@ namespace v2rayN.Handler return msg; } - private WebProxy GetWebProxy(bool blProxy) + private WebProxy? GetWebProxy(bool blProxy) { if (!blProxy) { @@ -341,11 +338,11 @@ namespace v2rayN.Handler private bool SocketCheck(string ip, int port) { - Socket sock = null; + Socket? sock = null; 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 f1fe5093..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; @@ -22,7 +22,7 @@ namespace v2rayN.Handler #region Config - public void SetConfig(ref Config config) + public void SetConfig(Config config) { _config = config; } @@ -118,7 +118,7 @@ namespace v2rayN.Handler return SqliteHelper.Instance.Query(sql).ToList(); } - public ProfileItem GetProfileItem(string indexId) + public ProfileItem? GetProfileItem(string indexId) { if (Utils.IsNullOrEmpty(indexId)) { @@ -173,7 +173,7 @@ namespace v2rayN.Handler return item.coreType; } - public CoreInfo GetCoreInfo(ECoreType coreType) + public CoreInfo? GetCoreInfo(ECoreType coreType) { if (coreInfos == null) { @@ -182,7 +182,7 @@ namespace v2rayN.Handler return coreInfos.Where(t => t.coreType == coreType).FirstOrDefault(); } - public List GetCoreInfos() + public List? GetCoreInfos() { if (coreInfos == null) { @@ -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 96c15478..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) { @@ -82,7 +77,7 @@ namespace v2rayN.Handler return BitmapFrame.Create(new Uri($"pack://application:,,,/Resources/NotifyIcon{index}.ico", UriKind.RelativeOrAbsolute)); } - private Icon GetNotifyIcon4Routing(Config config) + private Icon? GetNotifyIcon4Routing(Config config) { try { @@ -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|*.*"; @@ -286,7 +280,7 @@ namespace v2rayN.Handler BackupGuiNConfig(config, true); config = resConfig; - LazyConfig.Instance.SetConfig(ref config); + LazyConfig.Instance.SetConfig(config); return true; } @@ -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 74957b04..9d19502e 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 045f6039..5e82b8a5 100644 --- a/v2rayN/v2rayN/Handler/ProxySetting.cs +++ b/v2rayN/v2rayN/Handler/ProxySetting.cs @@ -10,16 +10,16 @@ namespace v2rayN.Handler return SetProxy(null, null, 1); } - public static bool SetProxy(string strProxy, string exceptions, int type) + 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! @@ -189,8 +189,8 @@ namespace v2rayN.Handler //判断是否使用代理 public static bool UsedProxy() { - using RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); - if (rk.GetValue("ProxyEnable").ToString() == "1") + using RegistryKey? rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); + if (rk?.GetValue("ProxyEnable")?.ToString() == "1") { return true; } @@ -200,9 +200,9 @@ 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); + using RegistryKey? rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); string ProxyServer = rk.GetValue("ProxyServer").ToString(); return ProxyServer; diff --git a/v2rayN/v2rayN/Handler/QRCodeHelper.cs b/v2rayN/v2rayN/Handler/QRCodeHelper.cs index 643b7e7e..bbd8c7ee 100644 --- a/v2rayN/v2rayN/Handler/QRCodeHelper.cs +++ b/v2rayN/v2rayN/Handler/QRCodeHelper.cs @@ -9,13 +9,13 @@ namespace v2rayN.Handler /// public class QRCodeHelper { - public static DrawingImage GetQRCode(string strContent) + public static DrawingImage? GetQRCode(string strContent) { 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 13b162bc..cee723b6 100644 --- a/v2rayN/v2rayN/Handler/ShareHandler.cs +++ b/v2rayN/v2rayN/Handler/ShareHandler.cs @@ -17,7 +17,7 @@ namespace v2rayN.Handler /// /// /// - public static string GetShareUrl(ProfileItem item) + public static string? GetShareUrl(ProfileItem item) { try { @@ -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(), //备注也许很长 ; @@ -167,7 +167,7 @@ namespace v2rayN.Handler return Utils.IsIpv6(address) ? $"[{address}]" : address; } - private static int GetStdTransport(ProfileItem item, string securityDef, ref Dictionary dicQuery) + private static int GetStdTransport(ProfileItem item, string? securityDef, ref Dictionary dicQuery) { if (!Utils.IsNullOrEmpty(item.flow)) { @@ -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)); } @@ -270,10 +270,11 @@ namespace v2rayN.Handler /// /// /// - public static ProfileItem ImportFromClipboardConfig(string clipboardData, out string msg) + public static ProfileItem? ImportFromClipboardConfig(string clipboardData, out string msg) { msg = string.Empty; - ProfileItem profileItem = new ProfileItem(); + + ProfileItem profileItem = new(); try { @@ -357,7 +358,7 @@ namespace v2rayN.Handler return profileItem; } - private static ProfileItem ResolveVmess(string result, out string msg) + private static ProfileItem? ResolveVmess(string result, out string msg) { msg = string.Empty; var profileItem = new ProfileItem @@ -365,11 +366,11 @@ namespace v2rayN.Handler configType = EConfigType.VMess }; - result = result.Substring(Global.vmessProtocol.Length); + result = result[Global.vmessProtocol.Length..]; result = Utils.Base64Decode(result); //转成Json - VmessQRCode vmessQRCode = Utils.FromJson(result); + VmessQRCode? vmessQRCode = Utils.FromJson(result); if (vmessQRCode == null) { msg = ResUI.FailedConversionConfiguration; @@ -407,17 +408,17 @@ namespace v2rayN.Handler return profileItem; } - private static ProfileItem ResolveVmess4Kitsunebi(string result) + private static ProfileItem? ResolveVmess4Kitsunebi(string result) { - ProfileItem profileItem = new ProfileItem + ProfileItem profileItem = new() { configType = EConfigType.VMess }; - result = result.Substring(Global.vmessProtocol.Length); + result = result[Global.vmessProtocol.Length..]; int indexSplit = result.IndexOf("?"); if (indexSplit > 0) { - result = result.Substring(0, indexSplit); + result = result[..indexSplit]; } result = Utils.Base64Decode(result); @@ -428,7 +429,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; } @@ -445,15 +446,15 @@ namespace v2rayN.Handler return profileItem; } - private static ProfileItem ResolveStdVmess(string result) + 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; @@ -526,7 +527,7 @@ namespace v2rayN.Handler return i; } - private static ProfileItem ResolveSip002(string result) + private static ProfileItem? ResolveSip002(string result) { Uri parsedUrl; try @@ -537,7 +538,7 @@ namespace v2rayN.Handler { return null; } - ProfileItem server = new ProfileItem + ProfileItem server = new() { remarks = parsedUrl.GetComponents(UriComponents.Fragment, UriFormat.Unescaped), address = parsedUrl.IdnHost, @@ -545,7 +546,7 @@ namespace v2rayN.Handler }; string rawUserInfo = parsedUrl.GetComponents(UriComponents.UserInfo, UriFormat.UriEscaped); //2022-blake3 - if (rawUserInfo.Contains(":")) + if (rawUserInfo.Contains(':')) { string[] userInfoParts = rawUserInfo.Split(new[] { ':' }, 2); if (userInfoParts.Length != 2) @@ -589,16 +590,16 @@ namespace v2rayN.Handler return server; } - private static readonly Regex UrlFinder = new Regex(@"ss://(?[A-Za-z0-9+-/=_]+)(?:#(?\S+))?", RegexOptions.IgnoreCase); - private static readonly Regex DetailsParser = new Regex(@"^((?.+?):(?.*)@(?.+?):(?\d+?))$", RegexOptions.IgnoreCase); + 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) + private static ProfileItem? ResolveSSLegacy(string result) { var match = UrlFinder.Match(result); 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 +625,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) + 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 +644,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,15 +668,15 @@ 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]; return profileItem; } - private static ProfileItem ResolveSocksNew(string result) + private static ProfileItem? ResolveSocksNew(string result) { Uri parsedUrl; try @@ -686,7 +687,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 +709,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 +728,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 cb747f46..fbd1eabc 100644 --- a/v2rayN/v2rayN/Handler/StatisticsHandler.cs +++ b/v2rayN/v2rayN/Handler/StatisticsHandler.cs @@ -13,7 +13,7 @@ namespace v2rayN.Handler private Channel channel_; private StatsService.StatsServiceClient client_; private bool exitFlag_; - private ServerStatItem _serverStatItem; + private ServerStatItem? _serverStatItem; private List _lstServerStat; public List ServerStat => _lstServerStat; @@ -70,7 +70,7 @@ namespace v2rayN.Handler { if (Enable && channel_.State == ChannelState.Ready) { - QueryStatsResponse res = null; + QueryStatsResponse? res = null; try { res = client_.QueryStats(new QueryStatsRequest() { Pattern = "", Reset = true }); @@ -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 c0dd4f8d..eba43439 100644 --- a/v2rayN/v2rayN/Handler/SysProxyHandle.cs +++ b/v2rayN/v2rayN/Handler/SysProxyHandle.cs @@ -20,7 +20,7 @@ namespace v2rayN.Handler // // // - private static SysproxyConfig _userSettings = null; + private static SysproxyConfig? _userSettings = null; enum RET_ERRORS : int { @@ -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(); - 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/TunHandler.cs b/v2rayN/v2rayN/Handler/TunHandler.cs index 91340244..54d8a4fe 100644 --- a/v2rayN/v2rayN/Handler/TunHandler.cs +++ b/v2rayN/v2rayN/Handler/TunHandler.cs @@ -9,12 +9,12 @@ 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; private CoreInfo coreInfo; - private Process _process; + private Process? _process; private static int _socksPort; private static bool _needRestart = true; private static bool _isRunning = false; @@ -111,7 +111,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(@"\", @"\\")}"); } @@ -119,8 +119,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) { @@ -244,7 +244,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 a3ba3777..8075eef6 100644 --- a/v2rayN/v2rayN/Handler/UpdateHandle.cs +++ b/v2rayN/v2rayN/Handler/UpdateHandle.cs @@ -35,51 +35,46 @@ namespace v2rayN.Handler _updateFunc = update; var url = string.Empty; - DownloadHandle downloadHandle = null; - if (downloadHandle == null) + DownloadHandle downloadHandle = new(); + downloadHandle.UpdateCompleted += (sender2, args) => { - downloadHandle = new DownloadHandle(); - - downloadHandle.UpdateCompleted += (sender2, args) => + if (args.Success) { - if (args.Success) - { - _updateFunc(false, ResUI.MsgDownloadV2rayCoreSuccessfully); + _updateFunc(false, ResUI.MsgDownloadV2rayCoreSuccessfully); - try + try + { + string fileName = Utils.GetTempPath(Utils.GetDownloadFileName(url)); + fileName = Utils.UrlEncode(fileName); + Process process = new() { - string fileName = Utils.GetTempPath(Utils.GetDownloadFileName(url)); - fileName = Utils.UrlEncode(fileName); - Process process = new Process + StartInfo = new ProcessStartInfo { - StartInfo = new ProcessStartInfo - { - FileName = "v2rayUpgrade.exe", - Arguments = $"\"{fileName}\"", - WorkingDirectory = Utils.StartupPath() - } - }; - process.Start(); - if (process.Id > 0) - { - _updateFunc(true, ""); + FileName = "v2rayUpgrade.exe", + Arguments = $"\"{fileName}\"", + WorkingDirectory = Utils.StartupPath() } - } - catch (Exception ex) + }; + process.Start(); + if (process.Id > 0) { - _updateFunc(false, ex.Message); + _updateFunc(true, ""); } } - else + catch (Exception ex) { - _updateFunc(false, args.Msg); + _updateFunc(false, ex.Message); } - }; - downloadHandle.Error += (sender2, args) => + } + else { - _updateFunc(false, args.GetException().Message); - }; - } + _updateFunc(false, args.Msg); + } + }; + downloadHandle.Error += (sender2, args) => + { + _updateFunc(false, args.GetException().Message); + }; AbsoluteCompleted += (sender2, args) => { if (args.Success) @@ -106,36 +101,32 @@ namespace v2rayN.Handler _updateFunc = update; var url = string.Empty; - DownloadHandle downloadHandle = null; - if (downloadHandle == null) + DownloadHandle downloadHandle = new(); + downloadHandle.UpdateCompleted += (sender2, args) => { - downloadHandle = new DownloadHandle(); - downloadHandle.UpdateCompleted += (sender2, args) => + if (args.Success) { - if (args.Success) - { - _updateFunc(false, ResUI.MsgDownloadV2rayCoreSuccessfully); - _updateFunc(false, ResUI.MsgUnpacking); + _updateFunc(false, ResUI.MsgDownloadV2rayCoreSuccessfully); + _updateFunc(false, ResUI.MsgUnpacking); - try - { - _updateFunc(true, url); - } - catch (Exception ex) - { - _updateFunc(false, ex.Message); - } - } - else + try { - _updateFunc(false, args.Msg); + _updateFunc(true, url); } - }; - downloadHandle.Error += (sender2, args) => + catch (Exception ex) + { + _updateFunc(false, ex.Message); + } + } + else { - _updateFunc(true, args.GetException().Message); - }; - } + _updateFunc(false, args.Msg); + } + }; + downloadHandle.Error += (sender2, args) => + { + _updateFunc(true, args.GetException().Message); + }; AbsoluteCompleted += (sender2, args) => { @@ -226,7 +217,7 @@ namespace v2rayN.Handler else { _updateFunc(false, $"{hashCode}{ResUI.MsgGetSubscriptionSuccessfully}"); - if (result.Length < 99) + if (result!.Length < 99) { _updateFunc(false, $"{hashCode}{result}"); } @@ -262,49 +253,44 @@ namespace v2rayN.Handler _updateFunc = update; var url = string.Format(Global.geoUrl, geoName); - DownloadHandle downloadHandle = null; - if (downloadHandle == null) + DownloadHandle downloadHandle = new(); + downloadHandle.UpdateCompleted += (sender2, args) => { - downloadHandle = new DownloadHandle(); - - downloadHandle.UpdateCompleted += (sender2, args) => + if (args.Success) { - if (args.Success) + _updateFunc(false, string.Format(ResUI.MsgDownloadGeoFileSuccessfully, geoName)); + + try { - _updateFunc(false, string.Format(ResUI.MsgDownloadGeoFileSuccessfully, geoName)); - - try + string fileName = Utils.GetTempPath(Utils.GetDownloadFileName(url)); + if (File.Exists(fileName)) { - string fileName = Utils.GetTempPath(Utils.GetDownloadFileName(url)); - if (File.Exists(fileName)) - { - //Global.coreTypes.ForEach(it => - //{ - // string targetPath = Utils.GetBinPath($"{geoName}.dat", (ECoreType)Enum.Parse(typeof(ECoreType), it)); - // File.Copy(fileName, targetPath, true); - //}); - string targetPath = Utils.GetBinPath($"{geoName}.dat"); - File.Copy(fileName, targetPath, true); + //Global.coreTypes.ForEach(it => + //{ + // string targetPath = Utils.GetBinPath($"{geoName}.dat", (ECoreType)Enum.Parse(typeof(ECoreType), it)); + // File.Copy(fileName, targetPath, true); + //}); + string targetPath = Utils.GetBinPath($"{geoName}.dat"); + File.Copy(fileName, targetPath, true); - File.Delete(fileName); - //_updateFunc(true, ""); - } - } - catch (Exception ex) - { - _updateFunc(false, ex.Message); + File.Delete(fileName); + //_updateFunc(true, ""); } } - else + catch (Exception ex) { - _updateFunc(false, args.Msg); + _updateFunc(false, ex.Message); } - }; - downloadHandle.Error += (sender2, args) => + } + else { - _updateFunc(false, args.GetException().Message); - }; - } + _updateFunc(false, args.Msg); + } + }; + downloadHandle.Error += (sender2, args) => + { + _updateFunc(false, args.GetException().Message); + }; askToDownload(downloadHandle, url, false); } @@ -374,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/Tool/Utils.cs b/v2rayN/v2rayN/Tool/Utils.cs index 43359be6..6f4e5e69 100644 --- a/v2rayN/v2rayN/Tool/Utils.cs +++ b/v2rayN/v2rayN/Tool/Utils.cs @@ -48,7 +48,8 @@ namespace v2rayN try { Assembly assembly = Assembly.GetExecutingAssembly(); - using Stream stream = assembly.GetManifestResourceStream(res); + using Stream? stream = assembly.GetManifestResourceStream(res); + ArgumentNullException.ThrowIfNull(stream); using StreamReader reader = new(stream); result = reader.ReadToEnd(); } @@ -90,7 +91,7 @@ namespace v2rayN /// /// /// - public static T FromJson(string strJson) + public static T? FromJson(string strJson) { try { @@ -98,8 +99,7 @@ namespace v2rayN { return default; } - T obj = JsonConvert.DeserializeObject(strJson); - return obj; + return JsonConvert.DeserializeObject(strJson); } catch { @@ -112,7 +112,7 @@ namespace v2rayN /// /// /// - public static string ToJson(object obj, bool indented = true) + public static string ToJson(object? obj, bool indented = true) { string result = string.Empty; try @@ -141,7 +141,7 @@ namespace v2rayN /// /// /// - public static int ToJsonFile(object obj, string filePath, bool nullValue = true) + public static int ToJsonFile(object? obj, string filePath, bool nullValue = true) { int result; try @@ -168,7 +168,7 @@ namespace v2rayN return result; } - public static JObject ParseJson(string strJson) + public static JObject? ParseJson(string strJson) { try { @@ -676,7 +676,7 @@ namespace v2rayN return Application.StartupPath; } - public static string RegReadValue(string path, string name, string def) + public static string? RegReadValue(string path, string name, string def) { RegistryKey? regKey = null; try @@ -737,7 +737,7 @@ 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) { return (int)ndpKey.GetValue("Release") >= release ? true : false; @@ -908,7 +908,7 @@ namespace v2rayN /// 获取剪贴板数 /// /// - public static string GetClipboardData() + public static string? GetClipboardData() { string strData = string.Empty; try @@ -995,7 +995,7 @@ namespace v2rayN return fileName; } - public static IPAddress GetDefaultGateway() + public static IPAddress? GetDefaultGateway() { return NetworkInterface .GetAllNetworkInterfaces() 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 e8a687ad..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( @@ -532,7 +532,7 @@ namespace v2rayN.ViewModels { _noticeHandler?.SendMessage(msg); } - private async void UpdateTaskHandler(bool success, string msg) + private void UpdateTaskHandler(bool success, string msg) { _noticeHandler?.SendMessage(msg); if (success) @@ -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); - })); + }); }); } }