Skip to content

Commit

Permalink
Refactor for new C# 12
Browse files Browse the repository at this point in the history
  • Loading branch information
thohng committed May 17, 2024
1 parent ff6c804 commit 61eb206
Show file tree
Hide file tree
Showing 11 changed files with 56 additions and 90 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class AddFileConfigurationSourceOptions : IConfigureAddFiles
{
public IDictionary<string, ConfigureAddFileOptions> ConfigureAddFiles { get; } = new Dictionary<string, ConfigureAddFileOptions>(StringComparer.OrdinalIgnoreCase);

public List<Action<AddFileContext>> Handlers { get; } = new List<Action<AddFileContext>>();
public List<Action<AddFileContext>> Handlers { get; } = [];

public string SectionKey { get; set; } = string.Empty;

Expand Down
11 changes: 3 additions & 8 deletions src/NetLah.Extensions.Configuration/CertificateConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

namespace NetLah.Extensions.Configuration;

#pragma warning disable S125 // Sections of code should not be commented out
//#pragma warning disable S125 // Sections of code should not be commented out
// "Certificate": {
// "Path": "testCert.pfx"
// "Password": "testPassword"
// }
#pragma warning restore S125 // Sections of code should not be commented out
//#pragma warning restore S125 // Sections of code should not be commented out

public class CertificateConfig
{
Expand Down Expand Up @@ -42,11 +42,6 @@ public class CertificateConfig

public override string? ToString()
{
if (IsFileCert)
{
return Path;
}

return IsStoreThumbprint ? Thumbprint : Subject;
return IsFileCert ? Path : IsStoreThumbprint ? Thumbprint : Subject;
}
}
6 changes: 1 addition & 5 deletions src/NetLah.Extensions.Configuration/CertificateLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,11 @@ public static class CertificateLoader
{
var isMacOs = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);

#pragma warning disable S3358 // Ternary operators should not be nested
var keyStorageFlag = !requiredPrivateKey || isMacOs
? X509KeyStorageFlags.DefaultKeySet
: certInfo.KeyStorageFlags is { } keyStorageFlags
? (X509KeyStorageFlags)((int)keyStorageFlags & 63)
: X509KeyStorageFlags.Exportable | X509KeyStorageFlags.EphemeralKeySet;
#pragma warning restore S3358 // Ternary operators should not be nested

var cert = new X509Certificate2(certInfo.Path, certInfo.Password, keyStorageFlag);

Expand Down Expand Up @@ -64,7 +62,7 @@ public static class CertificateLoader
var storeLocation = StoreLocation.CurrentUser;
if (!string.IsNullOrEmpty(location))
{
storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), location, ignoreCase: true);
storeLocation = Enum.Parse<StoreLocation>(location, ignoreCase: true);
}
var allowInvalid = certInfo.AllowInvalid ?? true; // default is allow invalid

Expand Down Expand Up @@ -122,15 +120,13 @@ internal static bool IsCertificateAllowedFor(X509Certificate2 certificate, strin
foreach (var extension in certificate.Extensions.OfType<X509EnhancedKeyUsageExtension>())
{
hasEkuExtension = true;
#pragma warning disable S3267 // Loops should be simplified with "LINQ" expressions
foreach (var oid in extension.EnhancedKeyUsages)
{
if (string.Equals(oid.Value, expectedOid, StringComparison.Ordinal))
{
return true;
}
}
#pragma warning restore S3267 // Loops should be simplified with "LINQ" expressions
}

return !hasEkuExtension;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ namespace NetLah.Extensions.Configuration;

public sealed class ConfigurationBuilderBuilder
{
private readonly List<Action<IConfigurationBuilder>> _configureConfigActions = new();
private readonly List<Action<IConfigurationBuilder>> _configurePostConfigActions = new();
private readonly List<Action<IConfigurationBuilder>> _configureConfigActions = [];
private readonly List<Action<IConfigurationBuilder>> _configurePostConfigActions = [];
private string[]? _args;
private Assembly? _assembly;
private string? _basePath;
Expand All @@ -35,10 +35,7 @@ private BuilderOrManager ConfigureBuilder()
.AddEnvironmentVariables(prefix: "DOTNET_")
.AddEnvironmentVariables(prefix: "ASPNETCORE_");

if (_environmentName == null)
{
_environmentName = ((IConfigurationBuilder)configBuilder).Build()[HostDefaults.EnvironmentKey];
}
_environmentName ??= ((IConfigurationBuilder)configBuilder).Build()[HostDefaults.EnvironmentKey];

if (!string.IsNullOrEmpty(_basePath))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ 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
}

var configuration = configBuilder is IConfigurationRoot configurationRoot
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public IConnectionStringManager CloneWithKeyPreserveSpace()
{
get
{
var names = connectionNames == null ? new[] { connectionName } : connectionNames.Prepend(connectionName);
var names = connectionNames == null ? [connectionName] : connectionNames.Prepend(connectionName);
foreach (var item in names)
{
if (item != null && ConnectionStrings.TryGetValue(Root.KeyNormalizer(item), out var result))
Expand Down
51 changes: 26 additions & 25 deletions src/NetLah.Extensions.Configuration/ConnectionStringParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,29 @@

namespace NetLah.Extensions.Configuration;

internal class ConnectionStringParser
internal partial class ConnectionStringParser(IEnumerable<KeyValuePair<string, string>> configuration, ProviderName? providerName, Func<string, string> keyNormalizer)
{
#if NET7_0_OR_GREATER
internal static readonly Regex QuoteTokenRegex = QuoteTokenGeneratedRegex();
private static readonly Regex NameAndProviderRegex = NameAndProviderGeneratedRegex();

[GeneratedRegex("(?<quote>([$%])\\1)|[$%]{(?<token>[a-zA-Z0-9_\\-\\s]{1,64})}|[$%]\\((?<token>[a-zA-Z0-9_\\-\\s]{1,64})\\)|[$%]\\[(?<token>[a-zA-Z0-9_\\-\\s]{1,64})\\]", RegexOptions.Compiled)]
private static partial Regex QuoteTokenGeneratedRegex();


[GeneratedRegex("^(?<connectionName>.+)_(?<providerName>[^_]+)$", RegexOptions.Compiled)]
private static partial Regex NameAndProviderGeneratedRegex();
#else
internal static readonly Regex QuoteTokenRegex = new("(?<quote>([$%])\\1)|[$%]{(?<token>[a-zA-Z0-9_\\-\\s]{1,64})}|[$%]\\((?<token>[a-zA-Z0-9_\\-\\s]{1,64})\\)|[$%]\\[(?<token>[a-zA-Z0-9_\\-\\s]{1,64})\\]", RegexOptions.Compiled);
private static readonly Regex NameAndProviderRegex = new("^(?<connectionName>.+)_(?<providerName>[^_]+)$", RegexOptions.Compiled);
#endif

private static readonly StringComparer DefaultStringComparer = ProviderNameComparer.DefaultStringComparer;
private static readonly StringComparison DefaultStringComparison = StringComparison.OrdinalIgnoreCase;

private readonly IEnumerable<KeyValuePair<string, string>> _configuration;
private readonly ProviderName? _selection;
private readonly Func<string, string> _keyNormalizer;

public ConnectionStringParser(IEnumerable<KeyValuePair<string, string>> configuration, ProviderName? providerName, Func<string, string> keyNormalizer)
{
_configuration = configuration;
_selection = providerName;
_keyNormalizer = keyNormalizer;
}
private readonly IEnumerable<KeyValuePair<string, string>> _configuration = configuration;
private readonly ProviderName? _selection = providerName;
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
Expand Down Expand Up @@ -51,14 +57,14 @@ internal IEnumerable<ProviderConnectionString> ListConnections()
.GroupBy(kv => kv.normalizedKey)
.ToDictionary(g => g.Key, g => g.First(), DefaultStringComparer);

var normalizedkeys = lookup.Keys.OrderBy(k => k.Length).ToArray();
var normalizedKeys = lookup.Keys.OrderBy(k => k.Length).ToArray();

var selectedProvider = _selection?.Provider;
var selectedCustom = _selection?.Custom;

var conns = new List<ProviderConnectionString>();

foreach (var key in normalizedkeys)
foreach (var key in normalizedKeys)
{
if (lookup.Remove(key, out var kv) && kv.value != null)
{
Expand Down Expand Up @@ -94,7 +100,9 @@ ProviderName Add(string connectionName, string? providerName)
if (_selection == null || (selectedProvider == provider.Provider && (!isExactCustom || isSameCustom)))
{
if (isExactCustom && isSameCustom)
{
customProviderName = selectedCustom;
}

conns.Add(new ProviderConnectionString(connectionName, kv.value, provider.Provider, customProviderName));
}
Expand Down Expand Up @@ -139,7 +147,7 @@ internal Dictionary<string, ProviderConnectionString> ExpandValue(IEnumerable<Pr

void Resolve(Entry entry)
{
if (entry.HasQuotes || entry.Tokens.Any())
if (entry.HasQuotes || entry.Tokens.Count > 0)
{
entry.ConnStr.Value = QuoteTokenRegex.Replace(entry.Raw, ExpandMatchEvaluator);
}
Expand Down Expand Up @@ -182,20 +190,13 @@ internal Entry NewEntry(ProviderConnectionString connStr)
return new Entry(connStr, hasQuotes, tokens);
}

internal class Entry
internal class Entry(ProviderConnectionString connStr, bool hasQuotes, HashSet<string> tokens)
{
public Entry(ProviderConnectionString connStr, bool hasQuotes, HashSet<string> tokens)
{
ConnStr = connStr;
HasQuotes = hasQuotes;
Tokens = tokens;
}

public string Name => ConnStr.Name; // for easier to debug and usage
public string Raw => ConnStr.Raw; // for easier to debug and usage
public ProviderConnectionString ConnStr { get; }
public bool HasQuotes { get; }
public HashSet<string> Tokens { get; }
public ProviderConnectionString ConnStr { get; } = connStr;
public bool HasQuotes { get; } = hasQuotes;
public HashSet<string> Tokens { get; } = tokens;
public int Remaining { get; set; }
}
}
28 changes: 8 additions & 20 deletions src/NetLah.Extensions.Configuration/ConnectionStringsRoot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,25 @@

namespace NetLah.Extensions.Configuration;

internal class ConnectionStringsRoot
internal class ConnectionStringsRoot(KeyValuePair<string, string>[] configuration,
Func<string, string>? keyNormalizer,
Func<KeyValuePair<string, string>[], Func<string, string>, ProviderName?, IDictionary<string, ProviderConnectionString>>? factory = null)
{
public ConnectionStringsRoot(KeyValuePair<string, string>[] configuration,
Func<string, string>? keyNormalizer,
Func<KeyValuePair<string, string>[], Func<string, string>, ProviderName?, IDictionary<string, ProviderConnectionString>>? factory = null)
{
Configuration = configuration;
KeyNormalizer = keyNormalizer ?? KeyTrimNormalizer;
Factory = factory ?? ConnectionStringFactory;
Cache = new ConcurrentDictionary<ProviderName, IDictionary<string, ProviderConnectionString>>(ProviderNameComparer.Instance);
}

public KeyValuePair<string, string>[] Configuration { get; }
public KeyValuePair<string, string>[] Configuration { get; } = configuration;

public Func<string, string> KeyNormalizer { get; }
public Func<string, string> KeyNormalizer { get; } = keyNormalizer ?? KeyTrimNormalizer;

public Func<KeyValuePair<string, string>[], Func<string, string>, ProviderName?, IDictionary<string, ProviderConnectionString>> Factory { get; }
public Func<KeyValuePair<string, string>[], Func<string, string>, ProviderName?, IDictionary<string, ProviderConnectionString>> Factory { get; } = factory ?? ConnectionStringFactory;

public IDictionary<string, ProviderConnectionString>? Default { get; private set; } // for providerName is null

public ConcurrentDictionary<ProviderName, IDictionary<string, ProviderConnectionString>> Cache { get; }
public ConcurrentDictionary<ProviderName, IDictionary<string, ProviderConnectionString>> Cache { get; } = new ConcurrentDictionary<ProviderName, IDictionary<string, ProviderConnectionString>>(ProviderNameComparer.Instance);

public IDictionary<string, ProviderConnectionString> this[ProviderName? providerName]
{
get
{
if (providerName == null)
return Default ??= ConnStrFactory();

return Cache.GetOrAdd(providerName, _ => ConnStrFactory());

return providerName == null ? (Default ??= ConnStrFactory()) : Cache.GetOrAdd(providerName, _ => ConnStrFactory());
IDictionary<string, ProviderConnectionString> ConnStrFactory() => Factory(Configuration, KeyNormalizer, providerName);
}
}
Expand Down
13 changes: 3 additions & 10 deletions src/NetLah.Extensions.Configuration/ProviderConnectionString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,14 @@ namespace NetLah.Extensions.Configuration;
/// <summary>
/// Provider and connection string
/// </summary>
public sealed class ProviderConnectionString : ProviderName
public sealed class ProviderConnectionString(string name, string connectionString, DbProviders provider = DbProviders.Custom, string? custom = null) : ProviderName(provider, custom)
{
private string? _expanded;

public ProviderConnectionString(string name, string connectionString, DbProviders provider = DbProviders.Custom, string? custom = null)
: base(provider, custom)
{
Name = name;
Raw = connectionString;
}

/// <summary>
/// Connection string name
/// </summary>
public string Name { get; }
public string Name { get; } = name;

/// <summary>
/// Expanded connection string value
Expand All @@ -29,7 +22,7 @@ public ProviderConnectionString(string name, string connectionString, DbProvider
/// <summary>
/// Raw connection string value
/// </summary>
public string Raw { get; }
public string Raw { get; } = connectionString;

public IConfiguration? Configuration { get; internal set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,12 @@

namespace NetLah.Extensions.Configuration;

public class TransformConfigurationProvider : ConfigurationProvider
public class TransformConfigurationProvider(IConfigurationSection configurationSection) : ConfigurationProvider
{
private readonly IConfigurationSection _configurationSection;
private readonly IConfigurationSection _configurationSection = configurationSection;
private object? _lock = null;
private IChangeToken? _token;

public TransformConfigurationProvider(IConfigurationSection configurationSection)
{
_configurationSection = configurationSection;
}

private void OnChange(object? obj)
{
Data.Clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,9 @@

namespace NetLah.Extensions.Configuration;

public class TransformConfigurationSource : IConfigurationSource
public class TransformConfigurationSource(IConfigurationSection configurationSection) : IConfigurationSource
{
private readonly IConfigurationSection _configurationSection;

public TransformConfigurationSource(IConfigurationSection configurationSection)
{
_configurationSection = configurationSection;
}
private readonly IConfigurationSection _configurationSection = configurationSection;

public IConfigurationProvider Build(IConfigurationBuilder builder)
{
Expand Down

0 comments on commit 61eb206

Please sign in to comment.