From 1f8cdb08e78b8a824305fa67476dc429d46b9657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20L=2E=20Charlier?= Date: Mon, 6 Nov 2023 20:54:52 +0100 Subject: [PATCH] style: fix many style issues (#647) * style: switch private fields to properties * style: add missing scope for attributes * style: switch private fields to properties * style: fix order of modifiers * style: add static modifier when not using any fields/properties * style: add missing Assert.Multiple * style: improve consistency in naming conventions when using private fields * style: remove pragma where not needed anymore * style: [WIP] improve exception messages for ArgumentException * style: use compound assignment * style: remove unused parameter * style: prefer TryGetValue call * style: prefer Any than Count * style: mark as static if not using any field/property * style: decrease exposition of some methods * style: improve exception messages * style: naming rules violations * style: remove unused internal constructors * style: add style enforcement --- DubUrl.Adomd/Discovery/NativeMethods.cs | 10 +++----- DubUrl.Adomd/Discovery/TcpDiscoverer.cs | 10 ++++---- DubUrl.Adomd/Discovery/WindowTitle.cs | 8 ++----- DubUrl.Adomd/Querying/DaxRenderer.cs | 6 ++--- .../Rewriting/PowerBiDesktopRewriter.cs | 6 ++--- DubUrl.Core/ConnectionUrl.cs | 4 ++-- .../ProviderInvariantNameAttribute.cs | 1 + DubUrl.Core/Locating/BaseLocatorFactory.cs | 6 ++--- .../Locating/OdbcDriver/BaseDriverLocator.cs | 2 +- .../Locating/OdbcDriver/DriverLister.cs | 6 ++--- .../OdbcDriver/DriverLocatorFactory.cs | 4 ++-- .../Implementation/DrillDriverLocator.cs | 4 ++-- .../Implementation/DuckdbDriverLocator.cs | 2 +- .../Implementation/MariaDbDriverLocator.cs | 4 ++-- .../Implementation/MsExcelDriverLocator.cs | 4 ++-- .../Implementation/MssqlDriverLocator.cs | 4 ++-- .../MySqlConnectorDriverLocator.cs | 4 ++-- .../Implementation/PostgresqlDriverLocator.cs | 2 +- .../Implementation/TextDriverLocator.cs | 4 ++-- .../Implementation/TrinoDriverLocator.cs | 4 ++-- .../RegexUtils/StringBuilderExtensions.cs | 4 ++-- .../Mapping/AlternativeMapperAttribute.cs | 2 +- DubUrl.Core/Mapping/BrandAttribute.cs | 1 + DubUrl.Core/Mapping/DatabaseAttribute.cs | 2 +- .../Mapping/Implementation/OdbcDbqMapper.cs | 3 --- DubUrl.Core/Mapping/MapperAttribute.cs | 2 +- DubUrl.Core/Mapping/SchemeMapperBuilder.cs | 3 +-- .../Mapping/WrapperConnectivityAttribute.cs | 1 + DubUrl.Core/Mapping/WrapperMapperAttribute.cs | 2 +- .../Dialects/Casters/ReturnCasterAttribute.cs | 3 ++- .../Querying/Dialects/DialectBuilder.cs | 8 +++---- .../Formatters/IntervalTrinoFormatter.cs | 2 +- .../Formatters/ReservedKeywordsReader.cs | 2 +- .../Dialects/Renderers/AnsiRenderer.cs | 6 ++--- .../Dialects/Renderers/RendererAttribute.cs | 2 +- .../Parametrizing/DubUrlParameterFactory.cs | 12 ++++------ .../Parametrizing/IDubUrlParameterFactory.cs | 13 ++++++++++ .../Parametrizing/ParametrizerFactory.cs | 6 ++--- .../Parametrizing/TypeMappingAttribute.cs | 1 + .../Reading/EmbeddedSqlFileResourceManager.cs | 4 ++-- DubUrl.Core/Querying/Reading/InlineCommand.cs | 2 +- .../EmbeddedSqlTemplateResourceManager.cs | 7 +++--- .../Querying/Templating/IRenderingEngine.cs | 15 ++++++++++++ .../Templating/InlineTemplateCommand.cs | 2 +- .../Templating/StringTemplateEngine.cs | 10 ++------ DubUrl.Core/Registering/BinFolderDiscover.cs | 4 ++-- .../Implementation/DuckdbRewriter.cs | 4 ++-- .../Implementation/OdbcDbqRewriter.cs | 5 ++-- .../Rewriting/Implementation/OdbcRewriter.cs | 3 +-- .../Implementation/QuestDbRewriter.cs | 4 ++-- .../Implementation/SqliteRewriter.cs | 4 ++-- .../Rewriting/Tokening/BaseTokenMapper.cs | 6 ++--- DubUrl.QA/BaseAdoProvider.cs | 24 ++++++++++++------- .../Templating/StringTemplateEngineTest.cs | 2 +- Duburl.OleDb/ProviderAttribute.cs | 8 +++---- Duburl.OleDb/ProviderLocatorFactory.cs | 4 ++-- Duburl.OleDb/Providers/AceProviderLocator.cs | 2 +- .../Providers/MssqlNCliProviderLocator.cs | 11 +-------- .../Providers/MssqlOleDbProviderLocator.cs | 10 +------- .../Providers/MySqlProviderLocator.cs | 11 +-------- 60 files changed, 152 insertions(+), 160 deletions(-) create mode 100644 DubUrl.Core/Querying/Parametrizing/IDubUrlParameterFactory.cs create mode 100644 DubUrl.Core/Querying/Templating/IRenderingEngine.cs diff --git a/DubUrl.Adomd/Discovery/NativeMethods.cs b/DubUrl.Adomd/Discovery/NativeMethods.cs index 6349cf1e..91551f57 100644 --- a/DubUrl.Adomd/Discovery/NativeMethods.cs +++ b/DubUrl.Adomd/Discovery/NativeMethods.cs @@ -28,7 +28,7 @@ internal static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate #pragma warning disable CA1838 // Avoid 'StringBuilder' parameters for P/Invokes [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal unsafe static extern int SendMessageTimeout( + internal static extern unsafe int SendMessageTimeout( IntPtr hWnd, uint uMsg, uint wParam, @@ -36,6 +36,7 @@ internal unsafe static extern int SendMessageTimeout( uint fuFlags, uint uTimeout, void* lpdwResult); +#pragma warning restore CA1838 // Avoid 'StringBuilder' parameters for P/Invokes [DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, @@ -44,14 +45,9 @@ internal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] internal static extern int GetWindowTextLength(IntPtr hWnd); +#pragma warning disable CA1838 // Avoid 'StringBuilder' parameters for P/Invokes [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern long GetWindowText(IntPtr hwnd, StringBuilder lpString, long cch); #pragma warning restore CA1838 // Avoid 'StringBuilder' parameters for P/Invokes - - public const int WM_COPYDATA = 0x4A; - - [DllImport("user32", CharSet = CharSet.Auto)] - public extern static int SendMessage(IntPtr hwnd, int wMsg, - int wParam, ref COPYDATASTRUCT lParam); } } diff --git a/DubUrl.Adomd/Discovery/TcpDiscoverer.cs b/DubUrl.Adomd/Discovery/TcpDiscoverer.cs index e073e74c..8c5f33a6 100644 --- a/DubUrl.Adomd/Discovery/TcpDiscoverer.cs +++ b/DubUrl.Adomd/Discovery/TcpDiscoverer.cs @@ -25,13 +25,14 @@ public static TcpTable GetExtendedTcpTable(bool sorted) if (UnmanagedTcpDiscoverer.GetExtendedTcpTable(tcpTable, ref tcpTableLength, true, UnmanagedTcpDiscoverer.AfInet, UnmanagedTcpDiscoverer.TcpTableType.OwnerPidAll, 0) == 0) { var table = (UnmanagedTcpDiscoverer.TcpTable)(Marshal.PtrToStructure(tcpTable, typeof(UnmanagedTcpDiscoverer.TcpTable)) ?? throw new NullReferenceException()); - +#pragma warning disable CA2020 var rowPtr = (IntPtr)((long)tcpTable + Marshal.SizeOf(table.length)); for (int i = 0; i < table.length; ++i) { tcpRows.Add(new TcpRow((UnmanagedTcpDiscoverer.TcpRow)(Marshal.PtrToStructure(rowPtr, typeof(UnmanagedTcpDiscoverer.TcpRow)) ?? throw new NullReferenceException()))); rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(typeof(UnmanagedTcpDiscoverer.TcpRow))); } +#pragma warning restore CA2020 } } finally @@ -58,12 +59,13 @@ public static Dictionary GetExtendedTcpDictionary() tcpTable = Marshal.AllocHGlobal(tcpTableLength); if (UnmanagedTcpDiscoverer.GetExtendedTcpTable(tcpTable, ref tcpTableLength, true, UnmanagedTcpDiscoverer.AfInet, UnmanagedTcpDiscoverer.TcpTableType.OwnerPidAll, 0) == 0) { - UnmanagedTcpDiscoverer.TcpTable table = (UnmanagedTcpDiscoverer.TcpTable)(Marshal.PtrToStructure(tcpTable, typeof(UnmanagedTcpDiscoverer.TcpTable)) ?? throw new NullReferenceException()); - + var table = (UnmanagedTcpDiscoverer.TcpTable)(Marshal.PtrToStructure(tcpTable, typeof(UnmanagedTcpDiscoverer.TcpTable)) ?? throw new NullReferenceException()); +#pragma warning disable CA2020 var rowPtr = (IntPtr)((long)tcpTable + Marshal.SizeOf(table.length)); +#pragma warning restore CA2020 for (int i = 0; i < table.length; ++i) { - TcpRow row = new TcpRow((UnmanagedTcpDiscoverer.TcpRow)(Marshal.PtrToStructure(rowPtr, typeof(UnmanagedTcpDiscoverer.TcpRow)) ?? throw new NullReferenceException())); + var row = new TcpRow((UnmanagedTcpDiscoverer.TcpRow)(Marshal.PtrToStructure(rowPtr, typeof(UnmanagedTcpDiscoverer.TcpRow)) ?? throw new NullReferenceException())); // HACK: only add first row that is in a Listening state if (row.State == TcpState.Listen) { diff --git a/DubUrl.Adomd/Discovery/WindowTitle.cs b/DubUrl.Adomd/Discovery/WindowTitle.cs index a92e0107..77941ec7 100644 --- a/DubUrl.Adomd/Discovery/WindowTitle.cs +++ b/DubUrl.Adomd/Discovery/WindowTitle.cs @@ -49,9 +49,7 @@ public static string GetWindowTitleTimeout(int procId, uint timeout) // ignore it and skip to the next one in the collection title = GetWindowTextTimeout(handle, timeout); } -#pragma warning disable CA1031 - catch (Exception) -#pragma warning restore CA1031 + catch { title = string.Empty; } @@ -94,13 +92,11 @@ private static string GetCaptionOfWindow(IntPtr hwnd) if (!string.IsNullOrWhiteSpace(windowText.ToString())) caption = windowText.ToString(); } -#pragma warning disable CA1031 catch (Exception ex) -#pragma warning restore CA1031 { caption = ex.Message; } return caption; } } -} \ No newline at end of file +} diff --git a/DubUrl.Adomd/Querying/DaxRenderer.cs b/DubUrl.Adomd/Querying/DaxRenderer.cs index 384f67c1..914c5239 100644 --- a/DubUrl.Adomd/Querying/DaxRenderer.cs +++ b/DubUrl.Adomd/Querying/DaxRenderer.cs @@ -27,7 +27,7 @@ public string Render(object? obj, string format) return obj?.ToString() ?? ""; if (format.ToLowerInvariant() == "identity") - return Identity.Format(obj ?? throw new ArgumentNullException()); + return Identity.Format(obj ?? throw new ArgumentNullException(nameof(obj))); if (format.ToLowerInvariant() == "value") { @@ -36,10 +36,10 @@ public string Render(object? obj, string format) if (Value.Values.TryGetValue(obj.GetType(), out var formatter)) return formatter.Format(obj); else - throw new ArgumentException(); + throw new ArgumentException($"No value formatter was found for the type '{obj.GetType().Name}'", nameof(format)); } else - throw new ArgumentException($"The format '{format}' is not a supported format. Only 'identifty' and 'value' are supported."); + throw new ArgumentException($"The format '{format}' is not a supported format. Only 'identifty' and 'value' are supported.", nameof(format)); } } } diff --git a/DubUrl.Adomd/Rewriting/PowerBiDesktopRewriter.cs b/DubUrl.Adomd/Rewriting/PowerBiDesktopRewriter.cs index c013911c..7e24af42 100644 --- a/DubUrl.Adomd/Rewriting/PowerBiDesktopRewriter.cs +++ b/DubUrl.Adomd/Rewriting/PowerBiDesktopRewriter.cs @@ -18,7 +18,7 @@ internal class PowerBiDesktopRewriter : ConnectionStringRewriter protected internal const string SERVER_KEYWORD = "Data Source"; protected internal const string DEFAULT_LOCALHOST = "localhost"; - protected internal readonly static string[] VALID_HOSTS = + protected internal static readonly string[] VALID_HOSTS = new[] { "127.0.0.1", ".", string.Empty, DEFAULT_LOCALHOST }; public PowerBiDesktopRewriter(DbConnectionStringBuilder csb) @@ -58,7 +58,7 @@ public int GetPortFromSegments(string[] segments) { var pbiName = segments.Length == 1 ? segments[0] - : throw new InvalidConnectionUrlException("A single segment is expected when using a Power BI Desktop connection-url"); + : throw new ArgumentOutOfRangeException(nameof(segments)); var processes = Discoverer.GetPowerBiProcesses(); if (processes.Any(x => x.Name == pbiName)) @@ -67,4 +67,4 @@ public int GetPortFromSegments(string[] segments) } } } -} \ No newline at end of file +} diff --git a/DubUrl.Core/ConnectionUrl.cs b/DubUrl.Core/ConnectionUrl.cs index 0dc050d5..421ace33 100644 --- a/DubUrl.Core/ConnectionUrl.cs +++ b/DubUrl.Core/ConnectionUrl.cs @@ -18,8 +18,8 @@ namespace DubUrl public class ConnectionUrl { private record ParseResult(string ConnectionString, UrlInfo UrlInfo, IDialect Dialect, IConnectivity Connectivity, IParametrizer Parametrizer) { } - private ParseResult? _result; - private ParseResult Result { get => _result ??= ParseDetail(); } + private ParseResult? result; + private ParseResult Result { get => result ??= ParseDetail(); } private SchemeMapperBuilder SchemeMapperBuilder { get; } private IMapper? Mapper { get; set; } private IParser Parser { get; } diff --git a/DubUrl.Core/Extensions/ProviderInvariantNameAttribute.cs b/DubUrl.Core/Extensions/ProviderInvariantNameAttribute.cs index 1936fae6..5a591916 100644 --- a/DubUrl.Core/Extensions/ProviderInvariantNameAttribute.cs +++ b/DubUrl.Core/Extensions/ProviderInvariantNameAttribute.cs @@ -6,6 +6,7 @@ namespace DubUrl.Extensions { + [AttributeUsage(AttributeTargets.Class)] public class ProviderInvariantNameAttribute : Attribute { public string Value { get; set; } diff --git a/DubUrl.Core/Locating/BaseLocatorFactory.cs b/DubUrl.Core/Locating/BaseLocatorFactory.cs index 85d9de9f..9f7da5ad 100644 --- a/DubUrl.Core/Locating/BaseLocatorFactory.cs +++ b/DubUrl.Core/Locating/BaseLocatorFactory.cs @@ -17,10 +17,10 @@ public abstract class BaseLocatorFactory public void AddAlias(string alias, string original) { if (Schemes.ContainsKey(alias)) - throw new ArgumentException(); + throw new ArgumentException($"There is already a scheme registered with the alias '{alias}'. You cannot add a second scheme with the same alias.", nameof(alias)); if (!Schemes.ContainsKey(original)) - throw new ArgumentException(); + throw new ArgumentException($"There is no scheme registered with the alias '{original}'. You cannot add an alias if the scheme is not already registered.", nameof(original)); Schemes.Add(alias, Schemes[original]); } @@ -28,7 +28,7 @@ public void AddAlias(string alias, string original) protected void AddElement(string alias, Type locator) { if (Schemes.ContainsKey(alias)) - throw new ArgumentException(); + throw new ArgumentException($"There is already a locator registered for the alias '{alias}'. You cannot register two locators with the same alias", nameof(alias)); Schemes.Add(alias, locator); } diff --git a/DubUrl.Core/Locating/OdbcDriver/BaseDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/BaseDriverLocator.cs index f120a722..0e1ba021 100644 --- a/DubUrl.Core/Locating/OdbcDriver/BaseDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/BaseDriverLocator.cs @@ -44,6 +44,6 @@ protected internal static int GetOptionPosition(Type optionType) => (typeof(T).GetCustomAttributes(typeof(LocatorAttribute), false).FirstOrDefault() as LocatorAttribute) ?.Options.ToList().IndexOf(optionType) - ?? throw new ArgumentOutOfRangeException(); + ?? throw new ArgumentOutOfRangeException(optionType.Name); } } diff --git a/DubUrl.Core/Locating/OdbcDriver/DriverLister.cs b/DubUrl.Core/Locating/OdbcDriver/DriverLister.cs index 2fc3f1dd..429d8e66 100644 --- a/DubUrl.Core/Locating/OdbcDriver/DriverLister.cs +++ b/DubUrl.Core/Locating/OdbcDriver/DriverLister.cs @@ -15,16 +15,14 @@ public virtual string[] List() if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var drivers = new List(); -#pragma warning disable CA1416 // Validate platform compatibility drivers.AddRange(ListFromRegistry(Registry.LocalMachine)); drivers.AddRange(ListFromRegistry(Registry.CurrentUser)); -#pragma warning restore CA1416 // Validate platform compatibility return drivers.ToArray(); } return Array.Empty(); } - private List ListFromRegistry(RegistryKey registryKey) + private static List ListFromRegistry(RegistryKey registryKey) { #pragma warning disable CA1416 // Validate platform compatibility var drivers = new List(); @@ -41,4 +39,4 @@ private List ListFromRegistry(RegistryKey registryKey) return drivers; } } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/DriverLocatorFactory.cs b/DubUrl.Core/Locating/OdbcDriver/DriverLocatorFactory.cs index 7da38c9a..e989da6a 100644 --- a/DubUrl.Core/Locating/OdbcDriver/DriverLocatorFactory.cs +++ b/DubUrl.Core/Locating/OdbcDriver/DriverLocatorFactory.cs @@ -33,7 +33,7 @@ public virtual IDriverLocator Instantiate(string scheme) public virtual IDriverLocator Instantiate(string scheme, IDictionary options) { if (!Schemes.ContainsKey(scheme)) - throw new ArgumentException(); + throw new ArgumentException($"There is no scheme registered with the alias '{scheme}'.", nameof(scheme)); var driverLocatorType = Schemes[scheme]; var ctors = driverLocatorType.GetConstructors(BindingFlags.Instance | BindingFlags.Public); @@ -50,4 +50,4 @@ public virtual IDriverLocator Instantiate(string scheme, IDictionary AddElement(alias, locator); } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/DrillDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/DrillDriverLocator.cs index e653c0be..3062ce2e 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/DrillDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/DrillDriverLocator.cs @@ -24,7 +24,7 @@ public DrillDriverRegex() { } } - private readonly List Candidates = new(); + private List Candidates { get; } = new(); internal EncodingOption Encoding { get; } public DrillDriverLocator() @@ -40,4 +40,4 @@ protected override List RankCandidates() } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/DuckdbDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/DuckdbDriverLocator.cs index 5504e570..0e0acfd0 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/DuckdbDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/DuckdbDriverLocator.cs @@ -25,7 +25,7 @@ public DuckdbDriverRegex() }) { } } - private readonly List Candidates = new(); + private List Candidates { get; } = new(); public DuckdbDriverLocator() : base(GetRegexPattern()) { } internal DuckdbDriverLocator(DriverLister driverLister) diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/MariaDbDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/MariaDbDriverLocator.cs index f4c39100..1956d0b3 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/MariaDbDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/MariaDbDriverLocator.cs @@ -28,7 +28,7 @@ public MariaDbDriverRegex() { } } - private readonly Dictionary Candidates = new(); + private Dictionary Candidates { get; } = new(); internal EncodingOption Encoding { get; } public MariaDbDriverLocator() @@ -52,4 +52,4 @@ protected override List RankCandidates() } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/MsExcelDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/MsExcelDriverLocator.cs index e6d8c9fa..afc92086 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/MsExcelDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/MsExcelDriverLocator.cs @@ -24,7 +24,7 @@ public MsExcelDriverRegex() }) { } } - private readonly List Candidates = new(); + private List Candidates { get; } = new(); public MsExcelDriverLocator() : base(GetRegexPattern()) { } @@ -38,4 +38,4 @@ protected override void AddCandidate(string driver, string[] matches) protected override List RankCandidates() => Candidates; } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/MssqlDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/MssqlDriverLocator.cs index 94b001c4..655e2d30 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/MssqlDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/MssqlDriverLocator.cs @@ -28,7 +28,7 @@ public MssqlDriverRegex() { } } - private readonly Dictionary Candidates = new(); + private Dictionary Candidates { get; } = new(); public MssqlDriverLocator() : base(GetRegexPattern()) { } internal MssqlDriverLocator(DriverLister driverLister) @@ -40,4 +40,4 @@ protected override void AddCandidate(string driver, string[] matches) protected override List RankCandidates() => Candidates.OrderByDescending(x => x.Value).Select(x => x.Key).ToList(); } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/MySqlConnectorDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/MySqlConnectorDriverLocator.cs index 0abd132c..a6ff2acb 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/MySqlConnectorDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/MySqlConnectorDriverLocator.cs @@ -30,7 +30,7 @@ public MySqlConnectorDriverRegex() { } } - private readonly Dictionary Candidates = new(); + private Dictionary Candidates { get; } = new(); internal EncodingOption Encoding { get; } public MySqlConnectorDriverLocator() @@ -63,4 +63,4 @@ protected override void AddCandidate(string driver, string[] matches) protected override List RankCandidates() => Candidates.OrderByDescending(x => x.Value).Select(x => x.Key).ToList(); } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/PostgresqlDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/PostgresqlDriverLocator.cs index 6a80085e..00fec638 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/PostgresqlDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/PostgresqlDriverLocator.cs @@ -29,7 +29,7 @@ public PostgresqlDriverRegex() private record struct CandidateInfo(string Driver, EncodingOption Encoding, ArchitectureOption Architecture); - private readonly List Candidates = new(); + private List Candidates { get; } = new(); internal EncodingOption Encoding { get; } internal ArchitectureOption Architecture { get; } diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/TextDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/TextDriverLocator.cs index 3f397c5a..525dde5c 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/TextDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/TextDriverLocator.cs @@ -24,7 +24,7 @@ public TextDriverRegex() }) { } } - private readonly List Candidates = new(); + private List Candidates { get; } = new(); public TextDriverLocator() : base(GetRegexPattern()) { } @@ -38,4 +38,4 @@ protected override void AddCandidate(string driver, string[] matches) protected override List RankCandidates() => Candidates; } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/OdbcDriver/Implementation/TrinoDriverLocator.cs b/DubUrl.Core/Locating/OdbcDriver/Implementation/TrinoDriverLocator.cs index cdbbd455..841dbb1a 100644 --- a/DubUrl.Core/Locating/OdbcDriver/Implementation/TrinoDriverLocator.cs +++ b/DubUrl.Core/Locating/OdbcDriver/Implementation/TrinoDriverLocator.cs @@ -26,7 +26,7 @@ public TrinoDriverRegex() { } } - private readonly List Candidates = new(); + private List Candidates { get; } = new(); public TrinoDriverLocator() : base(GetRegexPattern()) { } internal TrinoDriverLocator(DriverLister driverLister) @@ -38,4 +38,4 @@ protected override void AddCandidate(string driver, string[] matches) protected override List RankCandidates() => Candidates.OrderByDescending(x => x).ToList(); } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Locating/RegexUtils/StringBuilderExtensions.cs b/DubUrl.Core/Locating/RegexUtils/StringBuilderExtensions.cs index 52ad0142..1ec3c184 100644 --- a/DubUrl.Core/Locating/RegexUtils/StringBuilderExtensions.cs +++ b/DubUrl.Core/Locating/RegexUtils/StringBuilderExtensions.cs @@ -8,13 +8,13 @@ namespace DubUrl.Locating.RegexUtils { internal static class StringBuilderExtensions { - private static char[] EscapedChars = new[] { '[', ']', '(', ')', '{', '}', '*', '+', '?', '|', '^', '$', '.', '\\', '-' }; + private static readonly char[] escapedChars = new[] { '[', ']', '(', ')', '{', '}', '*', '+', '?', '|', '^', '$', '.', '\\', '-' }; public static StringBuilder AppendEscaped(this StringBuilder stringBuilder, string text) { foreach (var c in text.ToArray()) { - if (EscapedChars.Contains(c)) + if (escapedChars.Contains(c)) stringBuilder.Append('\\'); stringBuilder.Append(c); } diff --git a/DubUrl.Core/Mapping/AlternativeMapperAttribute.cs b/DubUrl.Core/Mapping/AlternativeMapperAttribute.cs index fab377d0..cee2ee7c 100644 --- a/DubUrl.Core/Mapping/AlternativeMapperAttribute.cs +++ b/DubUrl.Core/Mapping/AlternativeMapperAttribute.cs @@ -9,7 +9,7 @@ namespace DubUrl.Mapping { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - sealed public class AlternativeMapperAttribute : AlternativeMapperAttribute + public sealed class AlternativeMapperAttribute : AlternativeMapperAttribute where T : IDatabase where P : IParametrizer { diff --git a/DubUrl.Core/Mapping/BrandAttribute.cs b/DubUrl.Core/Mapping/BrandAttribute.cs index 01aff2f9..36f17376 100644 --- a/DubUrl.Core/Mapping/BrandAttribute.cs +++ b/DubUrl.Core/Mapping/BrandAttribute.cs @@ -7,6 +7,7 @@ namespace DubUrl.Mapping { + [AttributeUsage(AttributeTargets.Class)] public class BrandAttribute : Attribute { public const string DefaultMainColor = "#333333"; diff --git a/DubUrl.Core/Mapping/DatabaseAttribute.cs b/DubUrl.Core/Mapping/DatabaseAttribute.cs index ef49b7b4..29a851a7 100644 --- a/DubUrl.Core/Mapping/DatabaseAttribute.cs +++ b/DubUrl.Core/Mapping/DatabaseAttribute.cs @@ -24,7 +24,7 @@ public DatabaseAttribute(string databaseName, string[] aliases, Type dialectType } [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - sealed public class DatabaseAttribute : DatabaseAttribute where D : IDialect + public sealed class DatabaseAttribute : DatabaseAttribute where D : IDialect { public DatabaseAttribute(string databaseName, string[] aliases, DatabaseCategory listingPriority) : base( diff --git a/DubUrl.Core/Mapping/Implementation/OdbcDbqMapper.cs b/DubUrl.Core/Mapping/Implementation/OdbcDbqMapper.cs index bd54ffe4..e4e96909 100644 --- a/DubUrl.Core/Mapping/Implementation/OdbcDbqMapper.cs +++ b/DubUrl.Core/Mapping/Implementation/OdbcDbqMapper.cs @@ -19,9 +19,6 @@ namespace DubUrl.Mapping.Implementation internal class OdbcDbqMapper : BaseMapper, IOdbcMapper { public OdbcDbqMapper(DbConnectionStringBuilder csb, IDialect dialect, IParametrizer parametrizer) - : this(csb, dialect, parametrizer, new DriverLocatorFactory()) { } - - public OdbcDbqMapper(DbConnectionStringBuilder csb, IDialect dialect, IParametrizer parametrizer, DriverLocatorFactory driverLocatorFactory) : base(new OdbcDbqRewriter(csb), dialect, parametrizer diff --git a/DubUrl.Core/Mapping/MapperAttribute.cs b/DubUrl.Core/Mapping/MapperAttribute.cs index 4c739cf3..bab1ca47 100644 --- a/DubUrl.Core/Mapping/MapperAttribute.cs +++ b/DubUrl.Core/Mapping/MapperAttribute.cs @@ -10,7 +10,7 @@ namespace DubUrl.Mapping { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - sealed public class MapperAttribute : MapperAttribute where T : IDatabase where P : IParametrizer + public sealed class MapperAttribute : MapperAttribute where T : IDatabase where P : IParametrizer { public MapperAttribute(string providerInvariantName) : base( diff --git a/DubUrl.Core/Mapping/SchemeMapperBuilder.cs b/DubUrl.Core/Mapping/SchemeMapperBuilder.cs index a3688294..6c96cc55 100644 --- a/DubUrl.Core/Mapping/SchemeMapperBuilder.cs +++ b/DubUrl.Core/Mapping/SchemeMapperBuilder.cs @@ -18,12 +18,11 @@ public class SchemeMapperBuilder private readonly record struct ProviderInfo(string ProviderName, List Aliases, Type DialectType, DriverLocatorFactory? DriverLocatorFactory); private bool IsBuilt { get; set; } = false; - private readonly List MapperData = new(); + private List MapperData { get; } = new(); protected Dictionary Mappers { get; set; } = new(); private BaseMapperIntrospector[] MapperIntrospectors { get; } = new BaseMapperIntrospector[] { new NativeMapperIntrospector(), new WrapperMapperIntrospector() }; private DialectBuilder DialectBuilder { get; } = new(); - private ParametrizerFactory ParametrizerFactory { get; } = new(); public SchemeMapperBuilder() : this(new[] { typeof(SchemeMapperBuilder).Assembly }) { } diff --git a/DubUrl.Core/Mapping/WrapperConnectivityAttribute.cs b/DubUrl.Core/Mapping/WrapperConnectivityAttribute.cs index 3ca9056a..13ab79d7 100644 --- a/DubUrl.Core/Mapping/WrapperConnectivityAttribute.cs +++ b/DubUrl.Core/Mapping/WrapperConnectivityAttribute.cs @@ -7,6 +7,7 @@ namespace DubUrl.Mapping { + [AttributeUsage(AttributeTargets.Class)] public class WrapperConnectivityAttribute : Attribute { public virtual string ConnectivityName { get; protected set; } = string.Empty; diff --git a/DubUrl.Core/Mapping/WrapperMapperAttribute.cs b/DubUrl.Core/Mapping/WrapperMapperAttribute.cs index d7646ce9..c15af982 100644 --- a/DubUrl.Core/Mapping/WrapperMapperAttribute.cs +++ b/DubUrl.Core/Mapping/WrapperMapperAttribute.cs @@ -9,7 +9,7 @@ namespace DubUrl.Mapping { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - sealed public class WrapperMapperAttribute : WrapperMapperAttribute + public sealed class WrapperMapperAttribute : WrapperMapperAttribute where T : IWrapperConnectivity where P : IParametrizer { diff --git a/DubUrl.Core/Querying/Dialects/Casters/ReturnCasterAttribute.cs b/DubUrl.Core/Querying/Dialects/Casters/ReturnCasterAttribute.cs index d891d9b4..8fd92e40 100644 --- a/DubUrl.Core/Querying/Dialects/Casters/ReturnCasterAttribute.cs +++ b/DubUrl.Core/Querying/Dialects/Casters/ReturnCasterAttribute.cs @@ -7,6 +7,7 @@ namespace DubUrl.Querying.Dialects.Casters { + [AttributeUsage(AttributeTargets.Class)] public class ReturnCasterAttribute : Attribute { public virtual Type CasterType { get; protected set; } @@ -18,7 +19,7 @@ public ReturnCasterAttribute(Type casterType) } [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] - sealed public class ReturnCasterAttribute : ReturnCasterAttribute where R : ICaster + public sealed class ReturnCasterAttribute : ReturnCasterAttribute where R : ICaster { public ReturnCasterAttribute() : base(typeof(R)) diff --git a/DubUrl.Core/Querying/Dialects/DialectBuilder.cs b/DubUrl.Core/Querying/Dialects/DialectBuilder.cs index b8acdfa7..fb0d3950 100644 --- a/DubUrl.Core/Querying/Dialects/DialectBuilder.cs +++ b/DubUrl.Core/Querying/Dialects/DialectBuilder.cs @@ -24,8 +24,8 @@ public void AddAliases(Type dialectType, string[] aliases) if (DialectAliases.Values.Any(x => x.Any(d => aliases.Contains(d)))) return; - if (DialectAliases.ContainsKey(dialectType)) - DialectAliases[dialectType].AddRange(aliases); + if (DialectAliases.TryGetValue(dialectType, out var existingAliases)) + existingAliases.AddRange(aliases); else DialectAliases.Add(dialectType, aliases.ToList()); } @@ -35,10 +35,10 @@ public void AddAlias(string alias, string original) IsBuilt = false; if (DialectAliases.Values.Any(x => x.Contains(alias))) - throw new ArgumentException(); + throw new ArgumentOutOfRangeException(nameof(alias)); if (!DialectAliases.Values.Any(x => x.Contains(original))) - throw new ArgumentException(); + throw new ArgumentOutOfRangeException(nameof(original)); var dialect = DialectAliases.First(x => x.Value.Contains(original)); dialect.Value.Add(alias); diff --git a/DubUrl.Core/Querying/Dialects/Formatters/IntervalTrinoFormatter.cs b/DubUrl.Core/Querying/Dialects/Formatters/IntervalTrinoFormatter.cs index 2679a783..888c47f0 100644 --- a/DubUrl.Core/Querying/Dialects/Formatters/IntervalTrinoFormatter.cs +++ b/DubUrl.Core/Querying/Dialects/Formatters/IntervalTrinoFormatter.cs @@ -23,7 +23,7 @@ public string Format(TimeSpan value) sb.Append(" + INTERVAL \'", Convert.ToInt16(sb.Length == 0) * 3, 13 - Convert.ToInt16(sb.Length == 0) * 3).Append(value.Milliseconds).Append("\' MILLISECOND"); #if NET7_0_OR_GREATER if (value.Microseconds >= 1) - throw new ArgumentOutOfRangeException("Trino doesn't support microseconds."); + throw new ArgumentOutOfRangeException(nameof(value), "Trino doesn't support microseconds."); #endif return sb.ToString().TrimEnd(); } diff --git a/DubUrl.Core/Querying/Dialects/Formatters/ReservedKeywordsReader.cs b/DubUrl.Core/Querying/Dialects/Formatters/ReservedKeywordsReader.cs index 8d2662c1..2f32bed4 100644 --- a/DubUrl.Core/Querying/Dialects/Formatters/ReservedKeywordsReader.cs +++ b/DubUrl.Core/Querying/Dialects/Formatters/ReservedKeywordsReader.cs @@ -33,7 +33,7 @@ public virtual IEnumerable ReadAll() } } - protected internal IEnumerable ReadAll(Stream stream) + protected internal static IEnumerable ReadAll(Stream stream) { using var reader = new StreamReader(stream); while (reader.Peek() >= 0) diff --git a/DubUrl.Core/Querying/Dialects/Renderers/AnsiRenderer.cs b/DubUrl.Core/Querying/Dialects/Renderers/AnsiRenderer.cs index 9db0a978..41c908b4 100644 --- a/DubUrl.Core/Querying/Dialects/Renderers/AnsiRenderer.cs +++ b/DubUrl.Core/Querying/Dialects/Renderers/AnsiRenderer.cs @@ -26,7 +26,7 @@ public string Render(object? obj, string format) return obj?.ToString() ?? ""; if (format.ToLowerInvariant() == "identity") - return Identity.Format(obj ?? throw new ArgumentNullException()); + return Identity.Format(obj ?? throw new ArgumentNullException(nameof(obj))); if (format.ToLowerInvariant() == "value") { @@ -35,10 +35,10 @@ public string Render(object? obj, string format) if (Value.Values.TryGetValue(obj.GetType(), out var formatter)) return formatter.Format(obj); else - throw new ArgumentException(); + throw new ArgumentException($"No value formatter was found for the type '{obj.GetType().Name}'", nameof(format)); } else - throw new ArgumentException($"The format '{format}' is not a supported format. Only 'identifty' and 'value' are supported."); + throw new ArgumentException($"The format '{format}' is not a supported format. Only 'identifty' and 'value' are supported.", nameof(format)); } } } diff --git a/DubUrl.Core/Querying/Dialects/Renderers/RendererAttribute.cs b/DubUrl.Core/Querying/Dialects/Renderers/RendererAttribute.cs index 3d9efa8e..f1a16834 100644 --- a/DubUrl.Core/Querying/Dialects/Renderers/RendererAttribute.cs +++ b/DubUrl.Core/Querying/Dialects/Renderers/RendererAttribute.cs @@ -18,7 +18,7 @@ public RendererAttribute(Type rendererType) } [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - sealed public class RendererAttribute : RendererAttribute where R : IRenderer + public sealed class RendererAttribute : RendererAttribute where R : IRenderer { public RendererAttribute() : base(typeof(R)) diff --git a/DubUrl.Core/Querying/Parametrizing/DubUrlParameterFactory.cs b/DubUrl.Core/Querying/Parametrizing/DubUrlParameterFactory.cs index f05e57b5..1dd00715 100644 --- a/DubUrl.Core/Querying/Parametrizing/DubUrlParameterFactory.cs +++ b/DubUrl.Core/Querying/Parametrizing/DubUrlParameterFactory.cs @@ -3,10 +3,11 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using DubUrl.Extensions; namespace DubUrl.Querying.Parametrizing { - public class DubUrlParameterFactory + internal class DubUrlParameterFactory : IDubUrlParameterFactory { public enum Encoding { @@ -43,7 +44,7 @@ public DubUrlParameter Instantiate(string name, T? value) }; } - public DubUrlParameter Instantiate(string name, DateTime? value, bool isHighPrecision) + protected virtual DubUrlParameter Instantiate(string name, DateTime? value, bool isHighPrecision) { return isHighPrecision switch { @@ -52,13 +53,10 @@ public DubUrlParameter Instantiate(string name, DateTime? value, bool isHighPrec }; } - public DubUrlParameter Instantiate(string name, decimal? value, byte precision, byte scale) + protected virtual DubUrlParameter Instantiate(string name, decimal? value, byte precision, byte scale) => new DubUrlParameterDecimal(name, precision, scale, value); - public DubUrlParameter Instantiate(string name, string? value, Encoding encoding) - => Instantiate(name, value, encoding, null); - - public DubUrlParameter Instantiate(string name, string? value, Encoding encoding, int? fixedLength) + protected virtual DubUrlParameter Instantiate(string name, string? value, Encoding encoding, int? fixedLength) { return encoding switch { diff --git a/DubUrl.Core/Querying/Parametrizing/IDubUrlParameterFactory.cs b/DubUrl.Core/Querying/Parametrizing/IDubUrlParameterFactory.cs new file mode 100644 index 00000000..81b7a52c --- /dev/null +++ b/DubUrl.Core/Querying/Parametrizing/IDubUrlParameterFactory.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DubUrl.Querying.Parametrizing +{ + public interface IDubUrlParameterFactory + { + DubUrlParameter Instantiate(string name, T? value); + } +} diff --git a/DubUrl.Core/Querying/Parametrizing/ParametrizerFactory.cs b/DubUrl.Core/Querying/Parametrizing/ParametrizerFactory.cs index a7e17a77..bcc8be64 100644 --- a/DubUrl.Core/Querying/Parametrizing/ParametrizerFactory.cs +++ b/DubUrl.Core/Querying/Parametrizing/ParametrizerFactory.cs @@ -9,10 +9,10 @@ namespace DubUrl.Querying.Parametrizing { public class ParametrizerFactory { - public IParametrizer Instantiate(Type ParametrizerType) + public static IParametrizer Instantiate(Type ParametrizerType) => (IParametrizer)Activator.CreateInstance(ParametrizerType)!; - public IParametrizer Instantiate() where T : IParametrizer + public static IParametrizer Instantiate() where T : IParametrizer => Instantiate(typeof(T)); } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Querying/Parametrizing/TypeMappingAttribute.cs b/DubUrl.Core/Querying/Parametrizing/TypeMappingAttribute.cs index b32d7889..90c5e0cb 100644 --- a/DubUrl.Core/Querying/Parametrizing/TypeMappingAttribute.cs +++ b/DubUrl.Core/Querying/Parametrizing/TypeMappingAttribute.cs @@ -7,6 +7,7 @@ namespace DubUrl.Querying.Parametrizing { + [AttributeUsage(AttributeTargets.Class)] public class TypeMappingAttribute : Attribute { public DbType DbType { get; } diff --git a/DubUrl.Core/Querying/Reading/EmbeddedSqlFileResourceManager.cs b/DubUrl.Core/Querying/Reading/EmbeddedSqlFileResourceManager.cs index f36613ac..3f9be2a6 100644 --- a/DubUrl.Core/Querying/Reading/EmbeddedSqlFileResourceManager.cs +++ b/DubUrl.Core/Querying/Reading/EmbeddedSqlFileResourceManager.cs @@ -24,7 +24,7 @@ public string ReadResource(string resourceName) { using var stream = ResouceAssembly.GetManifestResourceStream(resourceName) - ?? throw new ArgumentException(); + ?? throw new FileNotFoundException(resourceName); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } @@ -48,4 +48,4 @@ protected virtual IEnumerable ListResourceMathing(string id, stri .Append(new ResourceMatch($"{id}.{extension}", 50)) .Where(x => ResourceNames.Any(y => x.Path.Equals(y, StringComparison.InvariantCultureIgnoreCase))); } -} \ No newline at end of file +} diff --git a/DubUrl.Core/Querying/Reading/InlineCommand.cs b/DubUrl.Core/Querying/Reading/InlineCommand.cs index 0491446c..5984011c 100644 --- a/DubUrl.Core/Querying/Reading/InlineCommand.cs +++ b/DubUrl.Core/Querying/Reading/InlineCommand.cs @@ -12,7 +12,7 @@ namespace DubUrl.Querying.Reading internal class InlineCommand : ICommandProvider { protected string Text { get; } - private readonly IQueryLogger QueryLogger; + private IQueryLogger QueryLogger { get; } public InlineCommand(string text, IQueryLogger queryLogger) => (Text, QueryLogger) = (text, queryLogger); diff --git a/DubUrl.Core/Querying/Templating/EmbeddedSqlTemplateResourceManager.cs b/DubUrl.Core/Querying/Templating/EmbeddedSqlTemplateResourceManager.cs index bc23c646..e9f64876 100644 --- a/DubUrl.Core/Querying/Templating/EmbeddedSqlTemplateResourceManager.cs +++ b/DubUrl.Core/Querying/Templating/EmbeddedSqlTemplateResourceManager.cs @@ -75,7 +75,8 @@ public IDictionary ListResources(string directory, string[] dial } protected virtual TextReader GetResourceReader(string resourceName) - => new StreamReader(ResouceAssembly.GetManifestResourceStream(resourceName) ?? throw new ArgumentException()); + => new StreamReader(ResouceAssembly.GetManifestResourceStream(resourceName) + ?? throw new FileNotFoundException(resourceName)); protected virtual (string?, object?) ParseDictionaryEntry(string? entry) { @@ -91,14 +92,14 @@ protected virtual (string?, object?) ParseDictionaryEntry(string? entry) var rawValue = entry[(separator+1)..].Trim(); if (rawValue[0] == '\"' && rawValue[^1] == '\"') return (key, rawValue.Trim('\"')); - else if (rawValue.All(c => char.IsDigit(c))) + else if (rawValue.All(char.IsDigit)) return (key, int.Parse(rawValue)); else if (rawValue.All(c => char.IsDigit(c) || c == '.')) return (key, decimal.Parse(rawValue)); else if (rawValue.Equals("true", StringComparison.InvariantCultureIgnoreCase) || rawValue.Equals("false", StringComparison.InvariantCultureIgnoreCase)) return (key, bool.Parse(rawValue)); else - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(entry)); } } } diff --git a/DubUrl.Core/Querying/Templating/IRenderingEngine.cs b/DubUrl.Core/Querying/Templating/IRenderingEngine.cs new file mode 100644 index 00000000..b41d74d6 --- /dev/null +++ b/DubUrl.Core/Querying/Templating/IRenderingEngine.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DubUrl.Querying.Dialects.Renderers; + +namespace DubUrl.Querying.Templating +{ + internal interface IRenderingEngine + { + string Render(string source, IDictionary subTemplates, IDictionary parameters, IRenderer? renderer); + string Render(string source, IDictionary subTemplates, IDictionary> @dictionaries, IDictionary parameters, IRenderer? renderer); + } +} diff --git a/DubUrl.Core/Querying/Templating/InlineTemplateCommand.cs b/DubUrl.Core/Querying/Templating/InlineTemplateCommand.cs index 7cf9c617..ad6f6da4 100644 --- a/DubUrl.Core/Querying/Templating/InlineTemplateCommand.cs +++ b/DubUrl.Core/Querying/Templating/InlineTemplateCommand.cs @@ -22,6 +22,6 @@ public InlineTemplateCommand(string sql, IDictionary parameters : base(sql, queryLogger) { Parameters = parameters; } protected override string Render(IDialect dialect, IConnectivity connectivity) - => new StringTemplateEngine().Render(Text, Parameters, dialect.Renderer); + => new StringTemplateEngine().Render(Text, new Dictionary(), Parameters, dialect.Renderer); } } diff --git a/DubUrl.Core/Querying/Templating/StringTemplateEngine.cs b/DubUrl.Core/Querying/Templating/StringTemplateEngine.cs index 265a63a8..f685a433 100644 --- a/DubUrl.Core/Querying/Templating/StringTemplateEngine.cs +++ b/DubUrl.Core/Querying/Templating/StringTemplateEngine.cs @@ -11,14 +11,8 @@ namespace DubUrl.Querying.Templating { - public class StringTemplateEngine + public class StringTemplateEngine : IRenderingEngine { - public string Render(string source, IDictionary parameters) - => Render(source, new Dictionary(), new Dictionary>(), parameters, null); - - public string Render(string source, IDictionary parameters, IRenderer? renderer) - => Render(source, new Dictionary(), new Dictionary>(), parameters, renderer); - public string Render(string source, IDictionary subTemplates, IDictionary parameters, IRenderer? renderer) => Render(source, subTemplates, new Dictionary>(), parameters, renderer); @@ -55,7 +49,7 @@ public string Render(string source, IDictionary subTemplates, ID return actual; } - private bool TryParseTemplate(string value, out string? name, out string[]? arguments, out string? template) + private static bool TryParseTemplate(string value, out string? name, out string[]? arguments, out string? template) { var end = value.IndexOf("::="); if (end < 0) diff --git a/DubUrl.Core/Registering/BinFolderDiscover.cs b/DubUrl.Core/Registering/BinFolderDiscover.cs index 7bb2d02c..2e02ea21 100644 --- a/DubUrl.Core/Registering/BinFolderDiscover.cs +++ b/DubUrl.Core/Registering/BinFolderDiscover.cs @@ -17,10 +17,10 @@ public class BinFolderDiscover : IProviderFactoriesDiscover private BaseMapperIntrospector[] MapperIntrospectors { get; } public BinFolderDiscover() - : this(new[] { Assembly.GetEntryAssembly() ?? throw new ArgumentNullException() }) { } + : this(new[] { Assembly.GetEntryAssembly() ?? throw new InvalidOperationException() }) { } internal BinFolderDiscover(BaseMapperIntrospector[] mapperIntrospectors) - : this(new[] { Assembly.GetEntryAssembly() ?? throw new ArgumentNullException() } , mapperIntrospectors) { } + : this(new[] { Assembly.GetEntryAssembly() ?? throw new InvalidOperationException() } , mapperIntrospectors) { } public BinFolderDiscover(Assembly[] assemblies) : this(assemblies, new BaseMapperIntrospector[] diff --git a/DubUrl.Core/Rewriting/Implementation/DuckdbRewriter.cs b/DubUrl.Core/Rewriting/Implementation/DuckdbRewriter.cs index 3082a8c1..b27e7c0a 100644 --- a/DubUrl.Core/Rewriting/Implementation/DuckdbRewriter.cs +++ b/DubUrl.Core/Rewriting/Implementation/DuckdbRewriter.cs @@ -49,9 +49,9 @@ public override void Execute(UrlInfo urlInfo) Specificator.Execute(DATABASE_KEYWORD, BuildPath(segments)); } - private string BuildPath(IEnumerable segments) + private static string BuildPath(IEnumerable segments) { - if (segments == null || segments.Count() == 0) + if (segments == null || !segments.Any()) throw new ArgumentException(); var path = new StringBuilder(); diff --git a/DubUrl.Core/Rewriting/Implementation/OdbcDbqRewriter.cs b/DubUrl.Core/Rewriting/Implementation/OdbcDbqRewriter.cs index 91b77730..c1ace960 100644 --- a/DubUrl.Core/Rewriting/Implementation/OdbcDbqRewriter.cs +++ b/DubUrl.Core/Rewriting/Implementation/OdbcDbqRewriter.cs @@ -48,7 +48,7 @@ public override void Execute(UrlInfo urlInfo) Specificator.Execute(SERVER_KEYWORD, BuildPath(segments)); } - private string BuildPath(IEnumerable segments) + private static string BuildPath(IEnumerable segments) { if (segments == null || !segments.Any()) throw new ArgumentException(); @@ -104,8 +104,7 @@ public override void Execute(UrlInfo urlInfo) } else { - if (AvailableOptions == null) - AvailableOptions = InitializeOptions(); + AvailableOptions ??= InitializeOptions(); var options = new Dictionary(); foreach (var scheme in remainingSchemes) { diff --git a/DubUrl.Core/Rewriting/Implementation/OdbcRewriter.cs b/DubUrl.Core/Rewriting/Implementation/OdbcRewriter.cs index 80978cda..ad4bd164 100644 --- a/DubUrl.Core/Rewriting/Implementation/OdbcRewriter.cs +++ b/DubUrl.Core/Rewriting/Implementation/OdbcRewriter.cs @@ -99,8 +99,7 @@ public override void Execute(UrlInfo urlInfo) } else { - if (AvailableOptions == null) - AvailableOptions = InitializeOptions(); + AvailableOptions ??= InitializeOptions(); var options = new Dictionary(); foreach (var scheme in remainingSchemes) { diff --git a/DubUrl.Core/Rewriting/Implementation/QuestDbRewriter.cs b/DubUrl.Core/Rewriting/Implementation/QuestDbRewriter.cs index bd059401..1ee377e3 100644 --- a/DubUrl.Core/Rewriting/Implementation/QuestDbRewriter.cs +++ b/DubUrl.Core/Rewriting/Implementation/QuestDbRewriter.cs @@ -78,9 +78,9 @@ public override void Execute(UrlInfo urlInfo) urlInfo.Options.Add(SERVER_COMPATIBILITY_MODE, NO_TYPE_LOADING); else if (urlInfo.Options[SERVER_COMPATIBILITY_MODE] != NO_TYPE_LOADING) throw new ArgumentOutOfRangeException($"QuestDb is accepting a single value '{NO_TYPE_LOADING}' for the option named '{SERVER_COMPATIBILITY_MODE}'. The value '{urlInfo.Options[SERVER_COMPATIBILITY_MODE]}' is not supported."); - if (urlInfo.Options.ContainsKey(STATEMENT_TIMEOUT)) + if (urlInfo.Options.TryGetValue(STATEMENT_TIMEOUT, out string? timeout)) { - urlInfo.Options.Add(COMMAND_TIMEOUT, urlInfo.Options[STATEMENT_TIMEOUT]); + urlInfo.Options.Add(COMMAND_TIMEOUT, timeout); urlInfo.Options.Remove(STATEMENT_TIMEOUT); } base.Execute(urlInfo); diff --git a/DubUrl.Core/Rewriting/Implementation/SqliteRewriter.cs b/DubUrl.Core/Rewriting/Implementation/SqliteRewriter.cs index ede73f77..28a399e4 100644 --- a/DubUrl.Core/Rewriting/Implementation/SqliteRewriter.cs +++ b/DubUrl.Core/Rewriting/Implementation/SqliteRewriter.cs @@ -39,9 +39,9 @@ public override void Execute(UrlInfo urlInfo) Specificator.Execute(DATABASE_KEYWORD, BuildPath(segments)); } - private string BuildPath(IEnumerable segments) + private static string BuildPath(IEnumerable segments) { - if (segments == null || segments.Count() == 0) + if (segments == null || !segments.Any()) throw new ArgumentException(); var path = new StringBuilder(); diff --git a/DubUrl.Core/Rewriting/Tokening/BaseTokenMapper.cs b/DubUrl.Core/Rewriting/Tokening/BaseTokenMapper.cs index 284b4a7e..0ef585c7 100644 --- a/DubUrl.Core/Rewriting/Tokening/BaseTokenMapper.cs +++ b/DubUrl.Core/Rewriting/Tokening/BaseTokenMapper.cs @@ -10,11 +10,11 @@ namespace DubUrl.Rewriting.Tokening { public abstract class BaseTokenMapper : ITokenMapper { - private ISpecificator? _specificator; + private ISpecificator? specificator; protected ISpecificator Specificator { - get { return _specificator ?? throw new ArgumentNullException(); } - set { _specificator = value; } + get { return specificator ?? throw new ArgumentNullException(); } + set { specificator = value; } } public BaseTokenMapper() { } diff --git a/DubUrl.QA/BaseAdoProvider.cs b/DubUrl.QA/BaseAdoProvider.cs index 59231978..d5a9c22d 100644 --- a/DubUrl.QA/BaseAdoProvider.cs +++ b/DubUrl.QA/BaseAdoProvider.cs @@ -275,10 +275,13 @@ protected void QueryCustomerWithDapper(string sql) using var conn = connectionUrl.Open(); var customers = conn.Query(sql).ToList(); Assert.That(customers, Has.Count.EqualTo(5)); - Assert.That(customers.Select(x => x.CustomerId).Distinct().ToList(), Has.Count.EqualTo(5)); - Assert.That(customers.Any(x => string.IsNullOrEmpty(x.FullName)), Is.False); - Assert.That(customers.Select(x => x.BirthDate).Distinct().ToList(), Has.Count.EqualTo(5)); - Assert.That(customers.Any(x => x.BirthDate == DateTime.MinValue), Is.False); + Assert.Multiple(() => + { + Assert.That(customers.Select(x => x.CustomerId).Distinct().ToList(), Has.Count.EqualTo(5)); + Assert.That(customers.Any(x => string.IsNullOrEmpty(x.FullName)), Is.False); + Assert.That(customers.Select(x => x.BirthDate).Distinct().ToList(), Has.Count.EqualTo(5)); + Assert.That(customers.Any(x => x.BirthDate == DateTime.MinValue), Is.False); + }); } [Test] @@ -298,10 +301,13 @@ public virtual void QueryCustomerWithDapperRepository() var repo = provider.GetRequiredService(); var customers = repo.GetAllAsync().Result; Assert.That(customers, Has.Count.EqualTo(5)); - Assert.That(customers.Select(x => x.CustomerId).Distinct().ToList(), Has.Count.EqualTo(5)); - Assert.That(customers.Any(x => string.IsNullOrEmpty(x.FullName)), Is.False); - Assert.That(customers.Select(x => x.BirthDate).Distinct().ToList(), Has.Count.EqualTo(5)); - Assert.That(customers.Any(x => x.BirthDate == DateTime.MinValue), Is.False); + Assert.Multiple(() => + { + Assert.That(customers.Select(x => x.CustomerId).Distinct().ToList(), Has.Count.EqualTo(5)); + Assert.That(customers.Any(x => string.IsNullOrEmpty(x.FullName)), Is.False); + Assert.That(customers.Select(x => x.BirthDate).Distinct().ToList(), Has.Count.EqualTo(5)); + Assert.That(customers.Any(x => x.BirthDate == DateTime.MinValue), Is.False); + }); } } -} \ No newline at end of file +} diff --git a/DubUrl.Testing/Querying/Templating/StringTemplateEngineTest.cs b/DubUrl.Testing/Querying/Templating/StringTemplateEngineTest.cs index dc1d4e6e..56ca4bef 100644 --- a/DubUrl.Testing/Querying/Templating/StringTemplateEngineTest.cs +++ b/DubUrl.Testing/Querying/Templating/StringTemplateEngineTest.cs @@ -15,7 +15,7 @@ public class StringTemplateEngineTest public void Render_WithoutSubTemplate_Correct() { var engine = new StringTemplateEngine(); - var response = engine.Render("Hello $name$!", new Dictionary() { { "name", "Cédric" } }); + var response = engine.Render("Hello $name$!", new Dictionary(), new Dictionary() { { "name", "Cédric" } }, null); Assert.That(response, Is.EqualTo("Hello Cédric!")); } diff --git a/Duburl.OleDb/ProviderAttribute.cs b/Duburl.OleDb/ProviderAttribute.cs index 9f43a999..fad9d40e 100644 --- a/Duburl.OleDb/ProviderAttribute.cs +++ b/Duburl.OleDb/ProviderAttribute.cs @@ -46,10 +46,10 @@ public ProviderSpecializationAttribute(Type P, string alias) public ProviderSpecializationAttribute(Type P, string[] aliases) : base( - P.GetCustomAttribute()?.RegexPattern ?? throw new ArgumentException() - , P.GetCustomAttribute()?.Options ?? throw new ArgumentException() - , P.GetCustomAttribute()?.Mapper ?? throw new ArgumentException() - , P.GetCustomAttribute()?.Database ?? throw new ArgumentException() + P.GetCustomAttribute()?.RegexPattern ?? throw new NullReferenceException($"Missing attribute 'Provider' for type '{P.Name}'.") + , P.GetCustomAttribute()?.Options ?? throw new NullReferenceException($"Missing attribute 'Provider' for type '{P.Name}'.") + , P.GetCustomAttribute()?.Mapper ?? throw new NullReferenceException($"Missing attribute 'Provider' for type '{P.Name}'.") + , P.GetCustomAttribute()?.Database ?? throw new NullReferenceException($"Missing attribute 'Provider' for type '{P.Name}'.") ) { Aliases = aliases; } } diff --git a/Duburl.OleDb/ProviderLocatorFactory.cs b/Duburl.OleDb/ProviderLocatorFactory.cs index 8450196c..7f69aec4 100644 --- a/Duburl.OleDb/ProviderLocatorFactory.cs +++ b/Duburl.OleDb/ProviderLocatorFactory.cs @@ -39,7 +39,7 @@ public virtual IProviderLocator Instantiate(string scheme) public virtual IProviderLocator Instantiate(string scheme, IDictionary options) { if (!Schemes.ContainsKey(scheme)) - throw new ArgumentException(); + throw new ArgumentException($"No ProviderLocator registered with the alias '{scheme}'.", nameof(scheme)); var providerLocatorType = Schemes[scheme]; var ctors = providerLocatorType.GetConstructors(BindingFlags.Instance | BindingFlags.Public); @@ -57,4 +57,4 @@ public virtual IProviderLocator Instantiate(string scheme, IDictionary AddElement(alias, locator); } -} \ No newline at end of file +} diff --git a/Duburl.OleDb/Providers/AceProviderLocator.cs b/Duburl.OleDb/Providers/AceProviderLocator.cs index 351003af..da9c223b 100644 --- a/Duburl.OleDb/Providers/AceProviderLocator.cs +++ b/Duburl.OleDb/Providers/AceProviderLocator.cs @@ -26,7 +26,7 @@ public AceProviderRegex() }) { } } - private readonly Dictionary Candidates = new(); + private Dictionary Candidates { get; } = new(); public AceProviderLocator() : base(GetRegexPattern()) { } diff --git a/Duburl.OleDb/Providers/MssqlNCliProviderLocator.cs b/Duburl.OleDb/Providers/MssqlNCliProviderLocator.cs index 79751532..161b8901 100644 --- a/Duburl.OleDb/Providers/MssqlNCliProviderLocator.cs +++ b/Duburl.OleDb/Providers/MssqlNCliProviderLocator.cs @@ -27,7 +27,7 @@ public MssqlNCliProviderRegex() { } } - private readonly Dictionary Candidates = new(); + private Dictionary Candidates { get; } = new(); public MssqlNCliProviderLocator() : base(GetRegexPattern(), new BaseTokenMapper[] @@ -41,15 +41,6 @@ public MssqlNCliProviderLocator() internal MssqlNCliProviderLocator(ProviderLister providerLister) : base(GetRegexPattern(), providerLister) { } - internal MssqlNCliProviderLocator(string value) - : base(GetRegexPattern(), new BaseTokenMapper[] - { new OptionsMapper() - , new OleDbRewriter.InitialCatalogMapper() - , new OleDbRewriter.ServerMapper() - } - ) - { } - protected override void AddCandidate(string provider, string[] matches) => Candidates.Add(provider, int.Parse(matches[0])); protected override List RankCandidates() diff --git a/Duburl.OleDb/Providers/MssqlOleDbProviderLocator.cs b/Duburl.OleDb/Providers/MssqlOleDbProviderLocator.cs index 1106ba25..17d8c88e 100644 --- a/Duburl.OleDb/Providers/MssqlOleDbProviderLocator.cs +++ b/Duburl.OleDb/Providers/MssqlOleDbProviderLocator.cs @@ -24,7 +24,7 @@ public MssqlOleDbProviderRegex() }) { } } - private readonly List Candidates = new(); + private List Candidates { get; } = new(); public MssqlOleDbProviderLocator() : base(GetRegexPattern(), new BaseTokenMapper[] @@ -38,14 +38,6 @@ public MssqlOleDbProviderLocator() internal MssqlOleDbProviderLocator(ProviderLister providerLister) : base(GetRegexPattern(), providerLister) { } - internal MssqlOleDbProviderLocator(string value) - : base(GetRegexPattern(), new BaseTokenMapper[] - { new OptionsMapper() - , new OleDbRewriter.InitialCatalogMapper() - , new OleDbRewriter.ServerMapper() - } - ) { } - protected override void AddCandidate(string provider, string[] matches) => Candidates.Add(provider); protected override List RankCandidates() diff --git a/Duburl.OleDb/Providers/MySqlProviderLocator.cs b/Duburl.OleDb/Providers/MySqlProviderLocator.cs index 2a069dbf..5fb25b59 100644 --- a/Duburl.OleDb/Providers/MySqlProviderLocator.cs +++ b/Duburl.OleDb/Providers/MySqlProviderLocator.cs @@ -23,7 +23,7 @@ public MySqlProviderRegex() }) { } } - private readonly List Candidates = new(); + private List Candidates { get; } = new(); public MySqlProviderLocator() : base(GetRegexPattern(), new BaseTokenMapper[] @@ -37,15 +37,6 @@ public MySqlProviderLocator() internal MySqlProviderLocator(ProviderLister providerLister) : base(GetRegexPattern(), providerLister) { } - internal MySqlProviderLocator(string value) - : base(GetRegexPattern(), new BaseTokenMapper[] - { new OptionsMapper() - , new OleDbRewriter.InitialCatalogMapper() - , new OleDbRewriter.ServerMapper() - } - ) - { } - protected override void AddCandidate(string provider, string[] matches) => Candidates.Add(provider); protected override List RankCandidates()