From d65a2e7871b8fc64e8e9323f1de3af6adb990d7e Mon Sep 17 00:00:00 2001 From: Tho Ho Date: Mon, 18 Nov 2024 16:48:06 +0800 Subject: [PATCH] Refactor and cleanup --- .../AddFileConfigurationSource.cs | 2 - .../AddFileOptions.cs | 10 ++++- .../ConfigurationBuilderBuilder.cs | 37 +++++++++++++++---- .../ConfigurationBuilderExtensions.cs | 2 - .../ConnectionStringManager.cs | 2 +- .../ConnectionStringParser.cs | 19 ++++++---- .../ConnectionStringUtilities.cs | 13 +++++-- .../ConnectionStringsRoot.cs | 19 ++++++++-- .../ProviderName.cs | 13 +++---- .../CertificateLoaderMutualTlsTest.cs | 2 +- .../ConfigurationBuilderBuilderTest.cs | 16 +++++--- .../ConnectionStringManagerTest.cs | 2 +- .../ConnectionStringParserTest.cs | 3 -- .../ConnectionStringsRootTest.cs | 4 +- .../EntryAndComparer.cs | 26 +++++++------ .../EnumParseBindTest.cs | 4 +- 16 files changed, 113 insertions(+), 61 deletions(-) diff --git a/src/NetLah.Extensions.Configuration/AddFileConfigurationSource.cs b/src/NetLah.Extensions.Configuration/AddFileConfigurationSource.cs index 3cf2f66..af05c42 100644 --- a/src/NetLah.Extensions.Configuration/AddFileConfigurationSource.cs +++ b/src/NetLah.Extensions.Configuration/AddFileConfigurationSource.cs @@ -23,11 +23,9 @@ public AddFileConfigurationSource(AddFileConfigurationSourceOptionsBuilder optio if (options.ConfigurationSection == null) { #if !NETSTANDARD -#pragma warning disable CA2208 // incorrect string argument is passed to a parameterized constructor #endif throw new ArgumentNullException(nameof(options.ConfigurationSection)); #if !NETSTANDARD -#pragma warning restore CA2208 // incorrect string argument is passed to a parameterized constructor #endif } _defaultOptions = new AddFileOptions { Optional = true, ReloadOnChange = true }; diff --git a/src/NetLah.Extensions.Configuration/AddFileOptions.cs b/src/NetLah.Extensions.Configuration/AddFileOptions.cs index 8bf3bbf..7571b32 100644 --- a/src/NetLah.Extensions.Configuration/AddFileOptions.cs +++ b/src/NetLah.Extensions.Configuration/AddFileOptions.cs @@ -9,7 +9,10 @@ public abstract class AddFileOptionsBase public bool ReloadOnChange { get; set; } = true; public string? LoggingLevel { get; set; } - public bool IsEnableLogging() => GetLogLevel() != LogLevel.None; + public bool IsEnableLogging() + { + return GetLogLevel() != LogLevel.None; + } public LogLevel GetLogLevel() { @@ -26,7 +29,10 @@ public LogLevel GetLogLevel() }; } - public void ResetCache() => _logLevel = default; + public void ResetCache() + { + _logLevel = default; + } } public class AddFileOptions : AddFileOptionsBase diff --git a/src/NetLah.Extensions.Configuration/ConfigurationBuilderBuilder.cs b/src/NetLah.Extensions.Configuration/ConfigurationBuilderBuilder.cs index 8bb0672..6599f8d 100644 --- a/src/NetLah.Extensions.Configuration/ConfigurationBuilderBuilder.cs +++ b/src/NetLah.Extensions.Configuration/ConfigurationBuilderBuilder.cs @@ -93,7 +93,10 @@ private ConfigurationBuilderBuilder ResetBuilder() #if NETSTANDARD public IConfigurationBuilder Builder => _builderOrManager ??= ConfigureBuilder(); - public IConfigurationRoot Build() => Builder.Build(); + public IConfigurationRoot Build() + { + return Builder.Build(); + } #else public ConfigurationManager Manager => _builderOrManager ??= ConfigureBuilder(); @@ -101,7 +104,10 @@ private ConfigurationBuilderBuilder ResetBuilder() public IConfigurationBuilder Builder => Manager; [Obsolete("This method is obsolete. Use property " + nameof(Manager) + " instead.")] - public IConfigurationRoot Build() => Manager; + public IConfigurationRoot Build() + { + return Manager; + } #endif public ConfigurationBuilderBuilder WithAddConfiguration(Action addConfiguration) @@ -122,7 +128,10 @@ public ConfigurationBuilderBuilder WithAppSecrets(Assembly assembly) return ResetBuilder(); } - public ConfigurationBuilderBuilder WithAppSecrets() => WithAppSecrets(typeof(TStartup).Assembly); + public ConfigurationBuilderBuilder WithAppSecrets() + { + return WithAppSecrets(typeof(TStartup).Assembly); + } public ConfigurationBuilderBuilder WithBasePath(string basePath) { @@ -130,7 +139,10 @@ public ConfigurationBuilderBuilder WithBasePath(string basePath) return ResetBuilder(); } - public ConfigurationBuilderBuilder WithBaseDirectory() => WithBasePath(AppDomain.CurrentDomain.BaseDirectory); + public ConfigurationBuilderBuilder WithBaseDirectory() + { + return WithBasePath(AppDomain.CurrentDomain.BaseDirectory); + } public ConfigurationBuilderBuilder WithClearAddedConfiguration(bool clear = true) { @@ -154,7 +166,10 @@ public ConfigurationBuilderBuilder WithConfiguration(IConfiguration configuratio return ResetBuilder(); } - public ConfigurationBuilderBuilder WithCurrentDirectory() => WithBasePath(Directory.GetCurrentDirectory()); + public ConfigurationBuilderBuilder WithCurrentDirectory() + { + return WithBasePath(Directory.GetCurrentDirectory()); + } public ConfigurationBuilderBuilder WithEnvironment(string environmentName) { @@ -192,18 +207,24 @@ public ConfigurationBuilderBuilder WithMapConfiguration(string sectionKey = "Map } public static ConfigurationBuilderBuilder Create(string[]? args = null) - => new ConfigurationBuilderBuilder() + { + return new ConfigurationBuilderBuilder() .WithCommandLines(args) .WithAppSecrets(); + } public static ConfigurationBuilderBuilder Create(Assembly assembly, string[]? args = null) - => new ConfigurationBuilderBuilder() + { + return new ConfigurationBuilderBuilder() .WithCommandLines(args) .WithAppSecrets(assembly); + } public static ConfigurationBuilderBuilder Create(string[]? args = null) - => new ConfigurationBuilderBuilder() + { + return new ConfigurationBuilderBuilder() .WithCommandLines(args); + } private void ConfigureAddFile(IConfigurationBuilder builder) { diff --git a/src/NetLah.Extensions.Configuration/ConfigurationBuilderExtensions.cs b/src/NetLah.Extensions.Configuration/ConfigurationBuilderExtensions.cs index a1ad82d..68ee1db 100644 --- a/src/NetLah.Extensions.Configuration/ConfigurationBuilderExtensions.cs +++ b/src/NetLah.Extensions.Configuration/ConfigurationBuilderExtensions.cs @@ -61,11 +61,9 @@ internal static TConfigurationBuilder AddAddFileConfiguration _keyNormalizer = keyNormalizer; // https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Configuration.EnvironmentVariables/src/EnvironmentVariablesConfigurationProvider.cs#L15-L18 - internal static ProviderName ParseProviderName(string? providerName) => (providerName?.ToUpperInvariant()) switch + internal static ProviderName ParseProviderName(string? providerName) { - "MICROSOFT.DATA.SQLCLIENT" or "MSSQL" or "SQLAZURE" or "SQLSERVER" or "SYSTEM.DATA.SQLCLIENT" => new ProviderName(DbProviders.SQLServer), - "MYSQL" or "MYSQLCONNECTOR" or "MYSQL.DATA.MYSQLCLIENT" => new ProviderName(DbProviders.MySQL), - "NPGSQL" or "POSTGRES" or "POSTGRESQL" => new ProviderName(DbProviders.PostgreSQL), - _ => new ProviderName(providerName), - }; + return (providerName?.ToUpperInvariant()) switch + { + "MICROSOFT.DATA.SQLCLIENT" or "MSSQL" or "SQLAZURE" or "SQLSERVER" or "SYSTEM.DATA.SQLCLIENT" => new ProviderName(DbProviders.SQLServer), + "MYSQL" or "MYSQLCONNECTOR" or "MYSQL.DATA.MYSQLCLIENT" => new ProviderName(DbProviders.MySQL), + "NPGSQL" or "POSTGRES" or "POSTGRESQL" => new ProviderName(DbProviders.PostgreSQL), + _ => new ProviderName(providerName), + }; + } internal static KeyValuePair[] ParseConfigurationKeyValue(IConfiguration configuration) - => configuration + { + return configuration .GetChildren() .Where(s => s.Value != null) .Select(s => new KeyValuePair(s.Key, s.Value!)) .ToArray(); + } public Dictionary Parse() { diff --git a/src/NetLah.Extensions.Configuration/ConnectionStringUtilities.cs b/src/NetLah.Extensions.Configuration/ConnectionStringUtilities.cs index 87f861d..4a06595 100644 --- a/src/NetLah.Extensions.Configuration/ConnectionStringUtilities.cs +++ b/src/NetLah.Extensions.Configuration/ConnectionStringUtilities.cs @@ -6,17 +6,24 @@ namespace NetLah.Extensions.Configuration; public static class ConnectionStringUtilities { - private static string? ConvertToString(object value) => value == null ? null : Convert.ToString(value, CultureInfo.InvariantCulture); + private static string? ConvertToString(object value) + { + return value == null ? null : Convert.ToString(value, CultureInfo.InvariantCulture); + } public static IConfiguration ToConfiguration(string connectionString) - => new ConfigurationBuilder() + { + return new ConfigurationBuilder() .AddInMemoryCollection(new DbConnectionStringBuilder { ConnectionString = connectionString } .Cast>() .ToDictionary(kv => kv.Key, kv => ConvertToString(kv.Value))) .Build(); + } public static IConfiguration ToConfiguration(this ProviderConnectionString providerConnectionString) - => providerConnectionString.Configuration ??= ToConfiguration(providerConnectionString.Value); + { + return providerConnectionString.Configuration ??= ToConfiguration(providerConnectionString.Value); + } public static TOptions? Get(string connectionString) { diff --git a/src/NetLah.Extensions.Configuration/ConnectionStringsRoot.cs b/src/NetLah.Extensions.Configuration/ConnectionStringsRoot.cs index 579ba23..1cdfb4e 100644 --- a/src/NetLah.Extensions.Configuration/ConnectionStringsRoot.cs +++ b/src/NetLah.Extensions.Configuration/ConnectionStringsRoot.cs @@ -21,16 +21,27 @@ public IDictionary this[ProviderName? provider get { return providerName == null ? (Default ??= ConnStrFactory()) : Cache.GetOrAdd(providerName, _ => ConnStrFactory()); - IDictionary ConnStrFactory() => Factory(Configuration, KeyNormalizer, providerName); + IDictionary ConnStrFactory() + { + return Factory(Configuration, KeyNormalizer, providerName); + } } } - internal static string KeyTrimNormalizer(string s) => s.Trim(); + internal static string KeyTrimNormalizer(string s) + { + return s.Trim(); + } - public static string KeyPreserveSpaceNormalizer(string s) => s; + public static string KeyPreserveSpaceNormalizer(string s) + { + return s; + } internal static IDictionary ConnectionStringFactory(KeyValuePair[] configuration, Func keyNormalizer, ProviderName? providerName) - => new ConnectionStringParser(configuration, providerName, keyNormalizer).Parse(); + { + return new ConnectionStringParser(configuration, providerName, keyNormalizer).Parse(); + } } diff --git a/src/NetLah.Extensions.Configuration/ProviderName.cs b/src/NetLah.Extensions.Configuration/ProviderName.cs index df62a3f..3ac15f6 100644 --- a/src/NetLah.Extensions.Configuration/ProviderName.cs +++ b/src/NetLah.Extensions.Configuration/ProviderName.cs @@ -34,7 +34,9 @@ private ProviderNameComparer() { } public bool Equals(ProviderName? x, ProviderName? y) { if (x == null || y == null) + { return x == null && y == null; + } var result = x.Provider == y.Provider; var isNotCustom = x.Provider != DbProviders.Custom; @@ -54,14 +56,9 @@ public int GetHashCode(ProviderName? obj) if (obj != null) { var hash1 = obj.Provider.GetHashCode(); - if (obj.Provider != DbProviders.Custom || string.IsNullOrEmpty(obj.Custom)) - { - return hash1; - } - else - { - return hash1 ^ DefaultStringComparer.GetHashCode(obj.Custom); - } + return obj.Provider != DbProviders.Custom || string.IsNullOrEmpty(obj.Custom) + ? hash1 + : hash1 ^ DefaultStringComparer.GetHashCode(obj.Custom); } return 0; } diff --git a/test/NetLah.Extensions.Configuration.Test/CertificateLoaderMutualTlsTest.cs b/test/NetLah.Extensions.Configuration.Test/CertificateLoaderMutualTlsTest.cs index acdd31d..553c475 100644 --- a/test/NetLah.Extensions.Configuration.Test/CertificateLoaderMutualTlsTest.cs +++ b/test/NetLah.Extensions.Configuration.Test/CertificateLoaderMutualTlsTest.cs @@ -128,7 +128,7 @@ async Task DoServer(PortBox port, CancellationToken token, Task taskWaitClientCo if (flags[port0 - port1]) { maxTry--; - TcpListener server = null; + TcpListener? server = null; try { var server0 = new TcpListener(IPAddress.Loopback, port0); diff --git a/test/NetLah.Extensions.Configuration.Test/ConfigurationBuilderBuilderTest.cs b/test/NetLah.Extensions.Configuration.Test/ConfigurationBuilderBuilderTest.cs index 48a4d68..26c007f 100644 --- a/test/NetLah.Extensions.Configuration.Test/ConfigurationBuilderBuilderTest.cs +++ b/test/NetLah.Extensions.Configuration.Test/ConfigurationBuilderBuilderTest.cs @@ -10,13 +10,19 @@ namespace NetLah.Extensions.Configuration.Test; public class ConfigurationBuilderBuilderTest { - private static string[] GetCommandLines() => ["--CommandLineKey", "CommandLineValue1", "/arg2", "value2b", "--arg3=value3c", "/arg4=value4d", "--Key5:Sub6", "value7e"]; + private static string[] GetCommandLines() + { + return ["--CommandLineKey", "CommandLineValue1", "/arg2", "value2b", "--arg3=value3c", "/arg4=value4d", "--Key5:Sub6", "value7e"]; + } - private static Dictionary GetInMemory() => new() + private static Dictionary GetInMemory() { - ["Key1"] = "Value2", - ["Key3:Sub4"] = "Value5", - }; + return new() + { + ["Key1"] = "Value2", + ["Key3:Sub4"] = "Value5", + }; + } private static ConfigurationBuilder CreateDefaultBuilder(string[]? args = null, string? environmentName = null, Assembly? assembly = null, Type? type = null, string? basePath = null) { diff --git a/test/NetLah.Extensions.Configuration.Test/ConnectionStringManagerTest.cs b/test/NetLah.Extensions.Configuration.Test/ConnectionStringManagerTest.cs index bfca558..08e2ea8 100644 --- a/test/NetLah.Extensions.Configuration.Test/ConnectionStringManagerTest.cs +++ b/test/NetLah.Extensions.Configuration.Test/ConnectionStringManagerTest.cs @@ -13,7 +13,7 @@ public class ConnectionStringManagerTest private static IConnectionStringManager GetService() { - var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary()).Build(); + var configuration = new ConfigurationBuilder().AddInMemoryCollection([]).Build(); return new ConnectionStringManager(configuration); } diff --git a/test/NetLah.Extensions.Configuration.Test/ConnectionStringParserTest.cs b/test/NetLah.Extensions.Configuration.Test/ConnectionStringParserTest.cs index c442edc..652dad4 100644 --- a/test/NetLah.Extensions.Configuration.Test/ConnectionStringParserTest.cs +++ b/test/NetLah.Extensions.Configuration.Test/ConnectionStringParserTest.cs @@ -252,10 +252,7 @@ public void Regex_Test(string input, string expected, bool isMatchedExpected) [Fact] public void RegexNullInputTest() { -#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. var ex = Assert.Throws(() => QuoteTokenRegex.Replace(null, "")); -#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. - Assert.Equal("input", ex.ParamName); } } diff --git a/test/NetLah.Extensions.Configuration.Test/ConnectionStringsRootTest.cs b/test/NetLah.Extensions.Configuration.Test/ConnectionStringsRootTest.cs index 00db32b..2897bcf 100644 --- a/test/NetLah.Extensions.Configuration.Test/ConnectionStringsRootTest.cs +++ b/test/NetLah.Extensions.Configuration.Test/ConnectionStringsRootTest.cs @@ -68,10 +68,12 @@ void SetupMock(ProviderName? input, Dictionary } void Verify(int times) - => mockFactory.Verify( + { + mockFactory.Verify( s => s.Invoke(It.IsAny[]>(), It.IsAny>(), It.IsAny() ), Times.Exactly(times)); + } } } diff --git a/test/NetLah.Extensions.Configuration.Test/EntryAndComparer.cs b/test/NetLah.Extensions.Configuration.Test/EntryAndComparer.cs index b0a7586..8312ef3 100644 --- a/test/NetLah.Extensions.Configuration.Test/EntryAndComparer.cs +++ b/test/NetLah.Extensions.Configuration.Test/EntryAndComparer.cs @@ -21,10 +21,9 @@ internal class EntryComparer : IEqualityComparer public bool Equals([AllowNull] Entry x, [AllowNull] Entry y) { - if (x == null || y == null) - return x == null && y == null; - - return x.GetType() == y.GetType() && + return x == null || y == null + ? x == null && y == null + : x.GetType() == y.GetType() && string.Equals(x.Name, y.Name) && x.ConnStr is ProviderConnectionString a && y.ConnStr is ProviderConnectionString b && @@ -32,7 +31,9 @@ y.ConnStr is ProviderConnectionString b && } public int GetHashCode([DisallowNull] Entry obj) - => obj.Name.GetHashCode() ^ (obj.ConnStr is { } a ? ConnStrComparer.GetHashCode(a) : 0); + { + return obj.Name.GetHashCode() ^ (obj.ConnStr is { } a ? ConnStrComparer.GetHashCode(a) : 0); + } } internal class ProviderConnectionStringComparer : IEqualityComparer @@ -42,16 +43,17 @@ internal class ProviderConnectionStringComparer : IEqualityComparer obj.Name.GetHashCode() ^ - (obj.Value?.GetHashCode() ?? 0) ^ - DefaultProviderNameComparer.GetHashCode(obj); + { + return obj.Name.GetHashCode() ^ + (obj.Value?.GetHashCode() ?? 0) ^ + DefaultProviderNameComparer.GetHashCode(obj); + } } diff --git a/test/NetLah.Extensions.Configuration.Test/EnumParseBindTest.cs b/test/NetLah.Extensions.Configuration.Test/EnumParseBindTest.cs index c8c6734..22b4332 100644 --- a/test/NetLah.Extensions.Configuration.Test/EnumParseBindTest.cs +++ b/test/NetLah.Extensions.Configuration.Test/EnumParseBindTest.cs @@ -7,9 +7,11 @@ namespace NetLah.Extensions.Configuration.Test; public class EnumParseBindTest { private static IConfiguration NewConfig(Dictionary initialData) - => new ConfigurationBuilder() + { + return new ConfigurationBuilder() .AddInMemoryCollection(initialData) .Build(); + } [Fact] public void Null()