Skip to content

Commit

Permalink
Refactor and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
thohng committed Nov 18, 2024
1 parent 69ffb19 commit d65a2e7
Show file tree
Hide file tree
Showing 16 changed files with 113 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
10 changes: 8 additions & 2 deletions src/NetLah.Extensions.Configuration/AddFileOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand All @@ -26,7 +29,10 @@ public LogLevel GetLogLevel()
};
}

public void ResetCache() => _logLevel = default;
public void ResetCache()
{
_logLevel = default;
}
}

public class AddFileOptions : AddFileOptionsBase
Expand Down
37 changes: 29 additions & 8 deletions src/NetLah.Extensions.Configuration/ConfigurationBuilderBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,15 +93,21 @@ 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();

[Obsolete("This property is obsolete. Use " + nameof(Manager) + " instead.")]
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<IConfigurationBuilder> addConfiguration)
Expand All @@ -122,15 +128,21 @@ public ConfigurationBuilderBuilder WithAppSecrets(Assembly assembly)
return ResetBuilder();
}

public ConfigurationBuilderBuilder WithAppSecrets<TStartup>() => WithAppSecrets(typeof(TStartup).Assembly);
public ConfigurationBuilderBuilder WithAppSecrets<TStartup>()
{
return WithAppSecrets(typeof(TStartup).Assembly);
}

public ConfigurationBuilderBuilder WithBasePath(string basePath)
{
_basePath = !string.IsNullOrWhiteSpace(basePath) ? Path.GetFullPath(basePath) : null;
return ResetBuilder();
}

public ConfigurationBuilderBuilder WithBaseDirectory() => WithBasePath(AppDomain.CurrentDomain.BaseDirectory);
public ConfigurationBuilderBuilder WithBaseDirectory()
{
return WithBasePath(AppDomain.CurrentDomain.BaseDirectory);
}

public ConfigurationBuilderBuilder WithClearAddedConfiguration(bool clear = true)
{
Expand All @@ -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)
{
Expand Down Expand Up @@ -192,18 +207,24 @@ public ConfigurationBuilderBuilder WithMapConfiguration(string sectionKey = "Map
}

public static ConfigurationBuilderBuilder Create<TStartup>(string[]? args = null)
=> new ConfigurationBuilderBuilder()
{
return new ConfigurationBuilderBuilder()
.WithCommandLines(args)
.WithAppSecrets<TStartup>();
}

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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,9 @@ internal static TConfigurationBuilder AddAddFileConfiguration<TConfigurationBuil
if (optionsBuilder?.SectionKey == null)
{
#if !NETSTANDARD
#pragma warning disable CA2208 // incorrect string argument is passed to a parameterized constructor
#endif
throw new ArgumentNullException(nameof(optionsBuilder.SectionKey));
#if !NETSTANDARD
#pragma warning restore CA2208 // incorrect string argument is passed to a parameterized constructor
#endif
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public IConnectionStringManager CloneWithKeyPreserveSpace()
internal static ProviderName? ParseSelectProviderName(object? selectingProvider)
{
return selectingProvider == null
? (global::NetLah.Extensions.Configuration.ProviderName?)default
? default
: selectingProvider is DbProviders select1
? new ProviderName(select1)
: selectingProvider is string selectingProviderStr
Expand Down
19 changes: 12 additions & 7 deletions src/NetLah.Extensions.Configuration/ConnectionStringParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,25 @@ internal partial class ConnectionStringParser(IEnumerable<KeyValuePair<string, s
private readonly Func<string, string> _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<string, string>[] ParseConfigurationKeyValue(IConfiguration configuration)
=> configuration
{
return configuration
.GetChildren()
.Where(s => s.Value != null)
.Select(s => new KeyValuePair<string, string>(s.Key, s.Value!))
.ToArray();
}

public Dictionary<string, ProviderConnectionString> Parse()
{
Expand Down
13 changes: 10 additions & 3 deletions src/NetLah.Extensions.Configuration/ConnectionStringUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<KeyValuePair<string, object>>()
.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<TOptions>(string connectionString)
{
Expand Down
19 changes: 15 additions & 4 deletions src/NetLah.Extensions.Configuration/ConnectionStringsRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,27 @@ public IDictionary<string, ProviderConnectionString> this[ProviderName? provider
get
{
return providerName == null ? (Default ??= ConnStrFactory()) : Cache.GetOrAdd(providerName, _ => ConnStrFactory());
IDictionary<string, ProviderConnectionString> ConnStrFactory() => Factory(Configuration, KeyNormalizer, providerName);
IDictionary<string, ProviderConnectionString> 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<string, ProviderConnectionString> ConnectionStringFactory(KeyValuePair<string, string>[] configuration,
Func<string, string> keyNormalizer,
ProviderName? providerName)
=> new ConnectionStringParser(configuration, providerName, keyNormalizer).Parse();
{
return new ConnectionStringParser(configuration, providerName, keyNormalizer).Parse();
}
}
13 changes: 5 additions & 8 deletions src/NetLah.Extensions.Configuration/ProviderName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string?> GetInMemory() => new()
private static Dictionary<string, string?> 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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class ConnectionStringManagerTest

private static IConnectionStringManager GetService()
{
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>()).Build();
var configuration = new ConfigurationBuilder().AddInMemoryCollection([]).Build();
return new ConnectionStringManager(configuration);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ArgumentNullException>(() => QuoteTokenRegex.Replace(null, ""));
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.

Assert.Equal("input", ex.ParamName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,12 @@ void SetupMock(ProviderName? input, Dictionary<string, ProviderConnectionString>
}

void Verify(int times)
=> mockFactory.Verify(
{
mockFactory.Verify(
s => s.Invoke(It.IsAny<KeyValuePair<string, string>[]>(),
It.IsAny<Func<string, string>>(),
It.IsAny<ProviderName>()
), Times.Exactly(times));
}
}
}
26 changes: 14 additions & 12 deletions test/NetLah.Extensions.Configuration.Test/EntryAndComparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,19 @@ internal class EntryComparer : IEqualityComparer<Entry>

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 &&
ConnStrComparer.Equals(a, 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<ProviderConnectionString>
Expand All @@ -42,16 +43,17 @@ internal class ProviderConnectionStringComparer : IEqualityComparer<ProviderConn

public bool Equals([AllowNull] ProviderConnectionString x, [AllowNull] ProviderConnectionString y)
{
if (x == null || y == null)
return x == null && y == null;

return string.Equals(x.Name, y.Name) &&
return x == null || y == null
? x == null && y == null
: string.Equals(x.Name, y.Name) &&
string.Equals(x.Value, y.Value) &&
DefaultProviderNameComparer.Equals(x, y);
}

public int GetHashCode([DisallowNull] ProviderConnectionString obj)
=> obj.Name.GetHashCode() ^
(obj.Value?.GetHashCode() ?? 0) ^
DefaultProviderNameComparer.GetHashCode(obj);
{
return obj.Name.GetHashCode() ^
(obj.Value?.GetHashCode() ?? 0) ^
DefaultProviderNameComparer.GetHashCode(obj);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ namespace NetLah.Extensions.Configuration.Test;
public class EnumParseBindTest
{
private static IConfiguration NewConfig(Dictionary<string, string?> initialData)
=> new ConfigurationBuilder()
{
return new ConfigurationBuilder()
.AddInMemoryCollection(initialData)
.Build();
}

[Fact]
public void Null()
Expand Down

0 comments on commit d65a2e7

Please sign in to comment.