Skip to content

Commit

Permalink
Fix/suppress new code style warnings.
Browse files Browse the repository at this point in the history
These were detected by either .NET 9 Preview 3 SDK or Visual Studio 2022 v17.10 Preview 3.
  • Loading branch information
bgrainger committed Apr 19, 2024
1 parent 033abea commit aee6fdf
Show file tree
Hide file tree
Showing 63 changed files with 446 additions and 430 deletions.
7 changes: 7 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@ indent_style = tab
indent_size = 4

# changes from VS2017 defaults
csharp_style_expression_bodied_local_functions = true:suggestion
csharp_style_expression_bodied_methods = true:suggestion
csharp_style_expression_bodied_constructors = true:suggestion
csharp_style_expression_bodied_operators = true:suggestion
csharp_style_namespace_declarations = file_scoped
csharp_prefer_braces = false:none
csharp_indent_switch_labels = true
csharp_space_after_cast = true
csharp_preserve_single_line_statements = false
dotnet_style_prefer_conditional_expression_over_return = false:suggestion

# use VS2017 defaults, but make them warnings (instead of none)
dotnet_style_qualification_for_field = false:warning
Expand Down Expand Up @@ -84,7 +87,11 @@ dotnet_diagnostic.CA2100.severity = none # Review SQL queries for security vulne
dotnet_diagnostic.CA2213.severity = silent # Disposable fields should be disposed.
dotnet_diagnostic.CA5398.severity = none # Avoid hardcoded SslProtocols values.
dotnet_diagnostic.IDE0044.severity = error # Make fields readonly.
dotnet_diagnostic.IDE0045.severity = suggestion # Use conditional expression for assignment.
dotnet_diagnostic.IDE0058.severity = none # Remove unnecessary expression value.
dotnet_diagnostic.IDE0059.severity = none # Remove unnecessary value assignment.
dotnet_diagnostic.IDE0065.severity = error # Using directives must be placed outside of a namespace declaration.
dotnet_diagnostic.IDE0072.severity = silent # Add missing cases to switch expression.
dotnet_diagnostic.SA1003.severity = none # Operator must not be followed by whitespace.
dotnet_diagnostic.SA1008.severity = none # Opening parenthesis must not be preceded by a space.
dotnet_diagnostic.SA1009.severity = none # Closing parenthesis must not be followed by a space.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public override object ReadValue(ReadOnlySpan<byte> data, ColumnDefinitionPayloa

try
{
return m_allowZeroDateTime ? (object) new MySqlDateTime(year, month, day, hour, minute, second, microseconds) :
return m_allowZeroDateTime ? new MySqlDateTime(year, month, day, hour, minute, second, microseconds) :
#if NET7_0_OR_GREATER
new DateTime(year, month, day, hour, minute, second, microseconds / 1000, microseconds % 1000, m_dateTimeKind);
#else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ public static Guid ReadGuid(ReadOnlySpan<byte> data) =>
#elif NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
new(stackalloc byte[16] { data[3], data[2], data[1], data[0], data[5], data[4], data[7], data[6], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15] });
#else
new(new[] { data[3], data[2], data[1], data[0], data[5], data[4], data[7], data[6], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15] });
new([data[3], data[2], data[1], data[0], data[5], data[4], data[7], data[6], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]]);
#endif
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ public static Guid ReadGuid(ReadOnlySpan<byte> data) =>
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
new(stackalloc byte[16] { data[7], data[6], data[5], data[4], data[3], data[2], data[1], data[0], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15] });
#else
new(new[] { data[7], data[6], data[5], data[4], data[3], data[2], data[1], data[0], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15] });
new([data[7], data[6], data[5], data[4], data[3], data[2], data[1], data[0], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]]);
#endif
}
12 changes: 6 additions & 6 deletions src/MySqlConnector/Core/CachedProcedure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ FROM information_schema.parameters
cmd.Parameters.AddWithValue("@component", component);

using var reader = await cmd.ExecuteReaderNoResetTimeoutAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false);
await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
_ = await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
routineCount = reader.GetInt32(0);
await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
_ = await reader.NextResultAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false))
{
Expand Down Expand Up @@ -168,17 +168,17 @@ internal static List<CachedParameter> ParseParameters(string parametersSql)
if (parameter.StartsWith("INOUT ", StringComparison.OrdinalIgnoreCase))
{
direction = "INOUT";
parameter = parameter.Substring(6);
parameter = parameter[6..];
}
else if (parameter.StartsWith("OUT ", StringComparison.OrdinalIgnoreCase))
{
direction = "OUT";
parameter = parameter.Substring(4);
parameter = parameter[4..];
}
else if (parameter.StartsWith("IN ", StringComparison.OrdinalIgnoreCase))
{
direction = "IN";
parameter = parameter.Substring(3);
parameter = parameter[3..];
}

var parts = s_parameterName.Match(parameter);
Expand Down Expand Up @@ -206,7 +206,7 @@ internal static string ParseDataType(string sql, out bool unsigned, out int leng
}

var list = sql.Trim().Split(' ');
var type = string.Empty;
string? type;

if (list.Length < 2 || !s_typeMapping.TryGetValue(list[0] + ' ' + list[1], out type))
{
Expand Down
22 changes: 10 additions & 12 deletions src/MySqlConnector/Core/ConnectionPool.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Net;
using System.Security.Authentication;
using Microsoft.Extensions.Logging;
using MySqlConnector.Logging;
using MySqlConnector.Protocol.Serialization;
Expand Down Expand Up @@ -140,7 +138,7 @@ public async ValueTask<ServerSession> GetSessionAsync(MySqlConnection connection
}
}

m_sessionSemaphore.Release();
_ = m_sessionSemaphore.Release();
throw;
}
}
Expand Down Expand Up @@ -172,14 +170,14 @@ public async ValueTask ReturnAsync(IOBehavior ioBehavior, ServerSession session)
try
{
lock (m_leasedSessions)
m_leasedSessions.Remove(session.Id);
_ = m_leasedSessions.Remove(session.Id);
MetricsReporter.RemoveUsed(this);
session.OwningConnection = null;
var sessionHealth = GetSessionHealth(session);
if (sessionHealth == 0)
{
lock (m_sessions)
m_sessions.AddFirst(session);
_ = m_sessions.AddFirst(session);
MetricsReporter.AddIdle(this);
}
else
Expand All @@ -194,15 +192,15 @@ public async ValueTask ReturnAsync(IOBehavior ioBehavior, ServerSession session)
}
finally
{
m_sessionSemaphore.Release();
_ = m_sessionSemaphore.Release();
}
}

public async Task ClearAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
// increment the generation of the connection pool
Log.ClearingConnectionPool(m_logger, Id);
Interlocked.Increment(ref m_generation);
_ = Interlocked.Increment(ref m_generation);
m_procedureCache = null;
await RecoverLeakedSessionsAsync(ioBehavior).ConfigureAwait(false);
await CleanPoolAsync(ioBehavior, session => session.PoolGeneration != m_generation, false, cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -406,13 +404,13 @@ private async Task CreateMinimumPooledSessions(MySqlConnection connection, IOBeh
var session = await ConnectSessionAsync(connection, s_createdToReachMinimumPoolSize, Stopwatch.GetTimestamp(), null, ioBehavior, cancellationToken).ConfigureAwait(false);
AdjustHostConnectionCount(session, 1);
lock (m_sessions)
m_sessions.AddFirst(session);
_ = m_sessions.AddFirst(session);
MetricsReporter.AddIdle(this);
}
finally
{
// connection is in pool; semaphore shouldn't be held any more
m_sessionSemaphore.Release();
_ = m_sessionSemaphore.Release();
}
}
}
Expand Down Expand Up @@ -452,7 +450,7 @@ private async ValueTask<ServerSession> ConnectSessionAsync(MySqlConnection conne
var redirectedSession = new ServerSession(m_connectionLogger, this, m_generation, Interlocked.Increment(ref m_lastSessionId));
try
{
await redirectedSession.ConnectAsync(redirectedSettings, connection, startingTimestamp, m_loadBalancer, activity, ioBehavior, cancellationToken).ConfigureAwait(false);
_ = await redirectedSession.ConnectAsync(redirectedSettings, connection, startingTimestamp, m_loadBalancer, activity, ioBehavior, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -614,7 +612,7 @@ private ConnectionPool(MySqlConnectorLoggingConfiguration loggingConfiguration,
cs.HostNames!.Count == 1 || cs.LoadBalance == MySqlLoadBalance.FailOver ? FailOverLoadBalancer.Instance :
cs.LoadBalance == MySqlLoadBalance.Random ? RandomLoadBalancer.Instance :
cs.LoadBalance == MySqlLoadBalance.LeastConnections ? new LeastConnectionsLoadBalancer(m_hostSessions!) :
(ILoadBalancer) new RoundRobinLoadBalancer();
new RoundRobinLoadBalancer();

// create tag lists for reporting pool metrics
var connectionString = cs.ConnectionStringBuilder.GetConnectionString(includePassword: false);
Expand Down Expand Up @@ -812,7 +810,7 @@ private static void OnAppDomainShutDown(object? sender, EventArgs e) =>
ClearPoolsAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();

private static readonly ConcurrentDictionary<string, ConnectionPool?> s_pools = new();
private static readonly List<ConnectionPool> s_allPools = new();
private static readonly List<ConnectionPool> s_allPools = [];
private static readonly Action<ILogger, int, string, Exception?> s_createdNewSession = LoggerMessage.Define<int, string>(
LogLevel.Debug, new EventId(EventIds.PoolCreatedNewSession, nameof(EventIds.PoolCreatedNewSession)),
"Pool {PoolId} has no pooled session available; created new session {SessionId}");
Expand Down
6 changes: 4 additions & 2 deletions src/MySqlConnector/Core/ConnectionSettings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#if NETCOREAPP3_0_OR_GREATER
using System.Net.Security;
#endif
using System.Security.Authentication;
using MySqlConnector.Utilities;

Expand Down Expand Up @@ -148,7 +150,7 @@ public ConnectionSettings(MySqlConnectionStringBuilder csb)
static int ToSigned(uint value) => value >= int.MaxValue ? int.MaxValue : (int) value;
}

public ConnectionSettings CloneWith(string host, int port, string userId) => new ConnectionSettings(this, host, port, userId);
public ConnectionSettings CloneWith(string host, int port, string userId) => new(this, host, port, userId);

private static MySqlGuidFormat GetEffectiveGuidFormat(MySqlGuidFormat guidFormat, bool oldGuids)
{
Expand Down Expand Up @@ -326,5 +328,5 @@ private ConnectionSettings(ConnectionSettings other, string host, int port, stri
UseXaTransactions = other.UseXaTransactions;
}

private static readonly string[] s_localhostPipeServer = { "." };
private static readonly string[] s_localhostPipeServer = ["."];
}
12 changes: 3 additions & 9 deletions src/MySqlConnector/Core/EnlistedTransactionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@

namespace MySqlConnector.Core;

internal abstract class EnlistedTransactionBase : IEnlistmentNotification
internal abstract class EnlistedTransactionBase(Transaction transaction, MySqlConnection connection) : IEnlistmentNotification
{
// A MySqlConnection that holds the ServerSession that was enrolled in the transaction
public MySqlConnection Connection { get; set; }
public MySqlConnection Connection { get; set; } = connection;

// Whether the connection is idle, i.e., a client has closed it and is no longer using it
public bool IsIdle { get; set; }

// Whether the distributed transaction was prepared successfully
public bool IsPrepared { get; private set; }

public Transaction Transaction { get; private set; }
public Transaction Transaction { get; private set; } = transaction;

public void Start()
{
Expand Down Expand Up @@ -51,12 +51,6 @@ void IEnlistmentNotification.Rollback(Enlistment enlistment)

public void InDoubt(Enlistment enlistment) => throw new NotImplementedException();

protected EnlistedTransactionBase(Transaction transaction, MySqlConnection connection)
{
Transaction = transaction;
Connection = connection;
}

protected abstract void OnStart();
protected abstract void OnPrepare(PreparingEnlistment enlistment);
protected abstract void OnCommit(Enlistment enlistment);
Expand Down
6 changes: 1 addition & 5 deletions src/MySqlConnector/Core/ILoadBalancer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,7 @@ public IReadOnlyList<string> LoadBalance(IReadOnlyList<string> hosts)
lock (m_random)
j = m_random.Next(i + 1);
if (i != j)
{
var temp = shuffled[i];
shuffled[i] = shuffled[j];
shuffled[j] = temp;
}
(shuffled[j], shuffled[i]) = (shuffled[i], shuffled[j]);
}
return shuffled;
}
Expand Down
6 changes: 3 additions & 3 deletions src/MySqlConnector/Core/MetricsReporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ public static void RemovePendingRequest(ConnectionPool? pool)

static MetricsReporter()
{
ActivitySourceHelper.Meter.CreateObservableUpDownCounter<int>("db.client.connections.idle.max",
_ = ActivitySourceHelper.Meter.CreateObservableUpDownCounter<int>("db.client.connections.idle.max",
observeValues: GetMaximumConnections, unit: "{connection}",
description: "The maximum number of idle open connections allowed; this corresponds to MaximumPoolSize in the connection string.");
ActivitySourceHelper.Meter.CreateObservableUpDownCounter<int>("db.client.connections.idle.min",
_ = ActivitySourceHelper.Meter.CreateObservableUpDownCounter<int>("db.client.connections.idle.min",
observeValues: GetMinimumConnections, unit: "{connection}",
description: "The minimum number of idle open connections allowed; this corresponds to MinimumPoolSize in the connection string.");
ActivitySourceHelper.Meter.CreateObservableUpDownCounter<int>("db.client.connections.max",
_ = ActivitySourceHelper.Meter.CreateObservableUpDownCounter<int>("db.client.connections.max",
observeValues: GetMaximumConnections, unit: "{connection}",
description: "The maximum number of open connections allowed; this corresponds to MaximumPoolSize in the connection string.");

Expand Down
16 changes: 7 additions & 9 deletions src/MySqlConnector/Core/NormalizedSchema.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@ internal sealed partial class NormalizedSchema
private static readonly Regex s_nameRegex = new(ReName, RegexOptions.Compiled);
#endif

public static NormalizedSchema MustNormalize(string name, string? defaultSchema = null)
{
var normalized = new NormalizedSchema(name, defaultSchema);
if (normalized.Component is null)
throw new ArgumentException("Could not determine function/procedure name", nameof(name));
if (normalized.Schema is null)
throw new ArgumentException("Could not determine schema", nameof(defaultSchema));
return normalized;
}
public static NormalizedSchema MustNormalize(string name, string? defaultSchema = null) =>
new NormalizedSchema(name, defaultSchema) switch
{
{ Component: null } => throw new ArgumentException("Could not determine function/procedure name", nameof(name)),
{ Schema: null } => throw new ArgumentException("Could not determine schema", nameof(defaultSchema)),
{ } normalized => normalized,
};

public NormalizedSchema(string name, string? defaultSchema = null)
{
Expand Down
11 changes: 4 additions & 7 deletions src/MySqlConnector/Core/ResultSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
if (!Session.SupportsDeprecateEof)
{
payload = await Session.ReceiveReplyAsync(ioBehavior, CancellationToken.None).ConfigureAwait(false);
EofPayload.Create(payload.Span);
_ = EofPayload.Create(payload.Span);
}

if (ColumnDefinitions.Length == (Command?.OutParameters?.Count + 1) && ColumnDefinitions[0].Name == SingleCommandPayloadCreator.OutParameterSentinelColumnName)
Expand All @@ -182,16 +182,13 @@ public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
}
}

private static bool IsHostVerified(MySqlConnection connection)
{
return connection.SslMode == MySqlSslMode.VerifyCA
|| connection.SslMode == MySqlSslMode.VerifyFull;
}
private static bool IsHostVerified(MySqlConnection connection) =>
connection.SslMode is MySqlSslMode.VerifyCA or MySqlSslMode.VerifyFull;

public async Task ReadEntireAsync(IOBehavior ioBehavior, CancellationToken cancellationToken)
{
while (State is ResultSetState.ReadingRows or ResultSetState.ReadResultSetHeader)
await ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
_ = await ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
}

public bool Read()
Expand Down
11 changes: 6 additions & 5 deletions src/MySqlConnector/Core/Row.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using MySqlConnector.ColumnReaders;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Serialization;
#if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER
using MySqlConnector.Utilities;
#endif

namespace MySqlConnector.Core;

Expand All @@ -30,7 +31,7 @@ public void SetData(ReadOnlyMemory<byte> data)
Array.Clear(m_dataOffsetLengths, 0, m_dataOffsetLengths.Length);
for (var column = 0; column < m_dataOffsetLengths.Length; column++)
{
if ((data.Span[(column + 2) / 8 + 1] & (1 << ((column + 2) % 8))) != 0)
if ((data.Span[((column + 2) / 8) + 1] & (1 << ((column + 2) % 8))) != 0)
{
// column is NULL
m_dataOffsetLengths[column] = (-1, 0);
Expand All @@ -40,7 +41,7 @@ public void SetData(ReadOnlyMemory<byte> data)
var reader = new ByteArrayReader(data.Span);

// skip packet header (1 byte) and NULL bitmap (formula for length at https://dev.mysql.com/doc/internals/en/null-bitmap.html)
reader.Offset += 1 + (m_dataOffsetLengths.Length + 7 + 2) / 8;
reader.Offset += 1 + ((m_dataOffsetLengths.Length + 7 + 2) / 8);
for (var column = 0; column < m_dataOffsetLengths.Length; column++)
{
if (m_dataOffsetLengths[column].Offset != -1)
Expand Down Expand Up @@ -341,7 +342,7 @@ public DateTime GetDateTime(int ordinal)
return (DateTime) value;
}

public DateTimeOffset GetDateTimeOffset(int ordinal) => new DateTimeOffset(DateTime.SpecifyKind(GetDateTime(ordinal), DateTimeKind.Utc));
public DateTimeOffset GetDateTimeOffset(int ordinal) => new(DateTime.SpecifyKind(GetDateTime(ordinal), DateTimeKind.Utc));

public Stream GetStream(int ordinal)
{
Expand Down Expand Up @@ -387,7 +388,7 @@ public float GetFloat(int ordinal)
{
float floatValue => floatValue,
double doubleValue when doubleValue is >= float.MinValue and <= float.MaxValue => (float) doubleValue,
double _ => throw new InvalidCastException("The value cannot be safely cast to Single."),
double => throw new InvalidCastException("The value cannot be safely cast to Single."),
decimal decimalValue => (float) decimalValue,
_ => (float) value,
};
Expand Down
5 changes: 3 additions & 2 deletions src/MySqlConnector/Core/SchemaProvider.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#if NET6_0_OR_GREATER
using System.Globalization;
using System.Text;
#endif
using MySqlConnector.Protocol.Serialization;

namespace MySqlConnector.Core;
Expand Down Expand Up @@ -431,7 +432,7 @@ private async Task FillDataTableAsync(IOBehavior ioBehavior, DataTable dataTable
while (await reader.ReadAsync(ioBehavior, cancellationToken).ConfigureAwait(false))
{
var rowValues = new object[dataTable.Columns.Count];
reader.GetValues(rowValues);
_ = reader.GetValues(rowValues);
dataTable.Rows.Add(rowValues);
}
}
Expand Down
Loading

0 comments on commit aee6fdf

Please sign in to comment.