Skip to content

Commit

Permalink
style: fix many style issues (#647)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Seddryck authored Nov 6, 2023
1 parent 614e8d5 commit 1f8cdb0
Show file tree
Hide file tree
Showing 60 changed files with 152 additions and 160 deletions.
10 changes: 3 additions & 7 deletions DubUrl.Adomd/Discovery/NativeMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,15 @@ 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,
StringBuilder? lParam,
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,
Expand All @@ -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);
}
}
10 changes: 6 additions & 4 deletions DubUrl.Adomd/Discovery/TcpDiscoverer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -58,12 +59,13 @@ public static Dictionary<int, TcpRow> 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)
{
Expand Down
8 changes: 2 additions & 6 deletions DubUrl.Adomd/Discovery/WindowTitle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
}
}
}
6 changes: 3 additions & 3 deletions DubUrl.Adomd/Querying/DaxRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public string Render(object? obj, string format)
return obj?.ToString() ?? "<empty>";

if (format.ToLowerInvariant() == "identity")
return Identity.Format(obj ?? throw new ArgumentNullException());
return Identity.Format(obj ?? throw new ArgumentNullException(nameof(obj)));

if (format.ToLowerInvariant() == "value")
{
Expand All @@ -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));
}
}
}
6 changes: 3 additions & 3 deletions DubUrl.Adomd/Rewriting/PowerBiDesktopRewriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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))
Expand All @@ -67,4 +67,4 @@ public int GetPortFromSegments(string[] segments)
}
}
}
}
}
4 changes: 2 additions & 2 deletions DubUrl.Core/ConnectionUrl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
1 change: 1 addition & 0 deletions DubUrl.Core/Extensions/ProviderInvariantNameAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

namespace DubUrl.Extensions
{
[AttributeUsage(AttributeTargets.Class)]
public class ProviderInvariantNameAttribute : Attribute
{
public string Value { get; set; }
Expand Down
6 changes: 3 additions & 3 deletions DubUrl.Core/Locating/BaseLocatorFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@ 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]);
}

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);
}
Expand Down
2 changes: 1 addition & 1 deletion DubUrl.Core/Locating/OdbcDriver/BaseDriverLocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ protected internal static int GetOptionPosition<T>(Type optionType)
=>
(typeof(T).GetCustomAttributes(typeof(LocatorAttribute), false).FirstOrDefault() as LocatorAttribute)
?.Options.ToList().IndexOf(optionType)
?? throw new ArgumentOutOfRangeException();
?? throw new ArgumentOutOfRangeException(optionType.Name);
}
}
6 changes: 2 additions & 4 deletions DubUrl.Core/Locating/OdbcDriver/DriverLister.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,14 @@ public virtual string[] List()
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var drivers = new List<string>();
#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<string>();
}

private List<string> ListFromRegistry(RegistryKey registryKey)
private static List<string> ListFromRegistry(RegistryKey registryKey)
{
#pragma warning disable CA1416 // Validate platform compatibility
var drivers = new List<string>();
Expand All @@ -41,4 +39,4 @@ private List<string> ListFromRegistry(RegistryKey registryKey)
return drivers;
}
}
}
}
4 changes: 2 additions & 2 deletions DubUrl.Core/Locating/OdbcDriver/DriverLocatorFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public virtual IDriverLocator Instantiate(string scheme)
public virtual IDriverLocator Instantiate(string scheme, IDictionary<Type, object> 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);
Expand All @@ -50,4 +50,4 @@ public virtual IDriverLocator Instantiate(string scheme, IDictionary<Type, objec

public void AddDriver(string alias, Type locator) => AddElement(alias, locator);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public DrillDriverRegex()
{ }
}

private readonly List<string> Candidates = new();
private List<string> Candidates { get; } = new();
internal EncodingOption Encoding { get; }

public DrillDriverLocator()
Expand All @@ -40,4 +40,4 @@ protected override List<string> RankCandidates()


}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public DuckdbDriverRegex()
})
{ }
}
private readonly List<string> Candidates = new();
private List<string> Candidates { get; } = new();
public DuckdbDriverLocator()
: base(GetRegexPattern<DuckdbDriverLocator>()) { }
internal DuckdbDriverLocator(DriverLister driverLister)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public MariaDbDriverRegex()
{ }
}

private readonly Dictionary<string, decimal> Candidates = new();
private Dictionary<string, decimal> Candidates { get; } = new();
internal EncodingOption Encoding { get; }

public MariaDbDriverLocator()
Expand All @@ -52,4 +52,4 @@ protected override List<string> RankCandidates()


}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public MsExcelDriverRegex()
})
{ }
}
private readonly List<string> Candidates = new();
private List<string> Candidates { get; } = new();

public MsExcelDriverLocator()
: base(GetRegexPattern<MsExcelDriverLocator>()) { }
Expand All @@ -38,4 +38,4 @@ protected override void AddCandidate(string driver, string[] matches)
protected override List<string> RankCandidates()
=> Candidates;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public MssqlDriverRegex()
{ }
}

private readonly Dictionary<string, int> Candidates = new();
private Dictionary<string, int> Candidates { get; } = new();
public MssqlDriverLocator()
: base(GetRegexPattern<MssqlDriverLocator>()) { }
internal MssqlDriverLocator(DriverLister driverLister)
Expand All @@ -40,4 +40,4 @@ protected override void AddCandidate(string driver, string[] matches)
protected override List<string> RankCandidates()
=> Candidates.OrderByDescending(x => x.Value).Select(x => x.Key).ToList();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public MySqlConnectorDriverRegex()
{ }
}

private readonly Dictionary<string, decimal> Candidates = new();
private Dictionary<string, decimal> Candidates { get; } = new();
internal EncodingOption Encoding { get; }

public MySqlConnectorDriverLocator()
Expand Down Expand Up @@ -63,4 +63,4 @@ protected override void AddCandidate(string driver, string[] matches)
protected override List<string> RankCandidates()
=> Candidates.OrderByDescending(x => x.Value).Select(x => x.Key).ToList();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public PostgresqlDriverRegex()

private record struct CandidateInfo(string Driver, EncodingOption Encoding, ArchitectureOption Architecture);

private readonly List<CandidateInfo> Candidates = new();
private List<CandidateInfo> Candidates { get; } = new();
internal EncodingOption Encoding { get; }
internal ArchitectureOption Architecture { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public TextDriverRegex()
})
{ }
}
private readonly List<string> Candidates = new();
private List<string> Candidates { get; } = new();

public TextDriverLocator()
: base(GetRegexPattern<TextDriverLocator>()) { }
Expand All @@ -38,4 +38,4 @@ protected override void AddCandidate(string driver, string[] matches)
protected override List<string> RankCandidates()
=> Candidates;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public TrinoDriverRegex()
{ }
}

private readonly List<string> Candidates = new();
private List<string> Candidates { get; } = new();
public TrinoDriverLocator()
: base(GetRegexPattern<TrinoDriverLocator>()) { }
internal TrinoDriverLocator(DriverLister driverLister)
Expand All @@ -38,4 +38,4 @@ protected override void AddCandidate(string driver, string[] matches)
protected override List<string> RankCandidates()
=> Candidates.OrderByDescending(x => x).ToList();
}
}
}
4 changes: 2 additions & 2 deletions DubUrl.Core/Locating/RegexUtils/StringBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion DubUrl.Core/Mapping/AlternativeMapperAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
namespace DubUrl.Mapping
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
sealed public class AlternativeMapperAttribute<T, P> : AlternativeMapperAttribute
public sealed class AlternativeMapperAttribute<T, P> : AlternativeMapperAttribute
where T : IDatabase
where P : IParametrizer
{
Expand Down
1 change: 1 addition & 0 deletions DubUrl.Core/Mapping/BrandAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

namespace DubUrl.Mapping
{
[AttributeUsage(AttributeTargets.Class)]
public class BrandAttribute : Attribute
{
public const string DefaultMainColor = "#333333";
Expand Down
Loading

0 comments on commit 1f8cdb0

Please sign in to comment.