Skip to content

Commit

Permalink
Remove FormatInvariant helper method. (#1253)
Browse files Browse the repository at this point in the history
  • Loading branch information
bgrainger authored Dec 18, 2022
1 parent ea3d329 commit 6bd719c
Show file tree
Hide file tree
Showing 35 changed files with 285 additions and 162 deletions.
10 changes: 5 additions & 5 deletions src/MySqlConnector/Core/BinaryRow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ protected override void GetDataOffsets(ReadOnlySpan<byte> data, int[] dataOffset
ColumnType.Short or ColumnType.Year => 2,
ColumnType.Tiny => 1,
ColumnType.Date or ColumnType.DateTime or ColumnType.NewDate or ColumnType.Timestamp or ColumnType.Time => reader.ReadByte(),
ColumnType.DateTime2 or ColumnType.Timestamp2 => throw new NotSupportedException("ColumnType {0} is not supported".FormatInvariant(columnDefinition.ColumnType)),
ColumnType.DateTime2 or ColumnType.Timestamp2 => throw new NotSupportedException($"ColumnType {columnDefinition.ColumnType} is not supported"),
_ => checked((int) reader.ReadLengthEncodedInteger()),
};

Expand Down Expand Up @@ -98,9 +98,9 @@ protected override object GetValueCore(ReadOnlySpan<byte> data, ColumnDefinition

case ColumnType.String:
if (Connection.GuidFormat == MySqlGuidFormat.Char36 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 36)
return Utf8Parser.TryParse(data, out Guid guid, out int guid36BytesConsumed, 'D') && guid36BytesConsumed == 36 ? guid : throw new FormatException("Could not parse CHAR(36) value as Guid: {0}".FormatInvariant(Encoding.UTF8.GetString(data)));
return Utf8Parser.TryParse(data, out Guid guid, out int guid36BytesConsumed, 'D') && guid36BytesConsumed == 36 ? guid : throw new FormatException($"Could not parse CHAR(36) value as Guid: {Encoding.UTF8.GetString(data)}");
if (Connection.GuidFormat == MySqlGuidFormat.Char32 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 32)
return Utf8Parser.TryParse(data, out Guid guid, out int guid32BytesConsumed, 'N') && guid32BytesConsumed == 32 ? guid : throw new FormatException("Could not parse CHAR(32) value as Guid: {0}".FormatInvariant(Encoding.UTF8.GetString(data)));
return Utf8Parser.TryParse(data, out Guid guid, out int guid32BytesConsumed, 'N') && guid32BytesConsumed == 32 ? guid : throw new FormatException($"Could not parse CHAR(32) value as Guid: {Encoding.UTF8.GetString(data)}");
goto case ColumnType.VarString;

case ColumnType.VarString:
Expand Down Expand Up @@ -153,7 +153,7 @@ protected override object GetValueCore(ReadOnlySpan<byte> data, ColumnDefinition
return data.ToArray();

default:
throw new NotImplementedException("Reading {0} not implemented".FormatInvariant(columnDefinition.ColumnType));
throw new NotImplementedException($"Reading {columnDefinition.ColumnType} not implemented");
}
}

Expand Down Expand Up @@ -199,7 +199,7 @@ private object ReadDateTime(ReadOnlySpan<byte> value)
}
catch (Exception ex)
{
throw new FormatException("Couldn't interpret value as a valid DateTime".FormatInvariant(Encoding.UTF8.GetString(value)), ex);
throw new FormatException($"Couldn't interpret value as a valid DateTime: {Encoding.UTF8.GetString(value)}", ex);
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/MySqlConnector/Core/CachedProcedure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using System.Text.RegularExpressions;
using MySqlConnector.Logging;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;

namespace MySqlConnector.Core;

Expand Down Expand Up @@ -226,7 +225,7 @@ private static CachedParameter CreateCachedParameter(int ordinal, string? direct
}
catch (NullReferenceException ex)
{
throw new MySqlException("Failed to parse stored procedure parameter '{0}'; extracted data type was {1}".FormatInvariant(originalSql, dataType), ex);
throw new MySqlException($"Failed to parse stored procedure parameter '{originalSql}'; extracted data type was {dataType}", ex);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/MySqlConnector/Core/CommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public static async Task<MySqlDataReader> ExecuteReaderAsync(IReadOnlyList<IMySq
// the default MySQL Server value for max_allowed_packet (in MySQL 5.7) is 4MiB: https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_max_allowed_packet
// use "decimal megabytes" (to round up) when creating the exception message
int megabytes = payload.Span.Length / 1_000_000;
throw new MySqlException("Error submitting {0}MB packet; ensure 'max_allowed_packet' is greater than {0}MB.".FormatInvariant(megabytes), ex);
throw new MySqlException($"Error submitting {megabytes}MB packet; ensure 'max_allowed_packet' is greater than {megabytes}MB.", ex);
}
}
catch (Exception ex) when (activity is { IsAllDataRequested: true })
Expand Down
3 changes: 2 additions & 1 deletion src/MySqlConnector/Core/ConnectionPool.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Security.Authentication;
using MySqlConnector.Logging;
Expand Down Expand Up @@ -569,7 +570,7 @@ private ConnectionPool(ConnectionSettings cs)
(ILoadBalancer) new RoundRobinLoadBalancer();

Id = Interlocked.Increment(ref s_poolId);
m_logArguments = new object[] { "{0}".FormatInvariant(Id) };
m_logArguments = new object[] { Id.ToString(CultureInfo.InvariantCulture) };
if (Log.IsInfoEnabled())
Log.Info("Pool{0} creating new connection pool for ConnectionString: {1}", m_logArguments[0], cs.ConnectionStringBuilder.GetConnectionString(includePassword: false));
}
Expand Down
6 changes: 3 additions & 3 deletions src/MySqlConnector/Core/ConnectionSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public ConnectionSettings(MySqlConnectionStringBuilder csb)
TlsVersions |= SslProtocols.Tls13;
#endif
else
throw new InvalidOperationException("Unexpected character '{0}' for TLS minor version.".FormatInvariant(minorVersion));
throw new InvalidOperationException($"Unexpected character '{minorVersion}' for TLS minor version.");
}
if (TlsVersions == default)
throw new NotSupportedException("All specified TLS versions are incompatible with this platform.");
Expand All @@ -95,10 +95,10 @@ public ConnectionSettings(MySqlConnectionStringBuilder csb)
tlsCipherSuites.Add(cipherSuite);
else if (int.TryParse(suiteName, out var value) && Enum.IsDefined(typeof(TlsCipherSuite), value))
tlsCipherSuites.Add((TlsCipherSuite) value);
else if (Enum.TryParse<TlsCipherSuite>("TLS_" + suiteName, ignoreCase: true, out cipherSuite))
else if (Enum.TryParse("TLS_" + suiteName, ignoreCase: true, out cipherSuite))
tlsCipherSuites.Add(cipherSuite);
else
throw new NotSupportedException("Unknown value '{0}' for TlsCipherSuites.".FormatInvariant(suiteName));
throw new NotSupportedException($"Unknown value '{suiteName}' for TlsCipherSuites.");
}
TlsCipherSuites = tlsCipherSuites;
#else
Expand Down
10 changes: 5 additions & 5 deletions src/MySqlConnector/Core/ResultSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public async Task ReadResultSetHeaderAsync(IOBehavior ioBehavior)
break;

default:
throw new InvalidOperationException("Unsupported Source type: {0}".FormatInvariant(source.GetType().Name));
throw new InvalidOperationException($"Unsupported Source type: {source.GetType().Name}");
}
}
catch (Exception ex)
Expand Down Expand Up @@ -293,7 +293,7 @@ public string GetName(int ordinal)
if (ColumnDefinitions is null)
throw new InvalidOperationException("There is no current result set.");
if (ordinal < 0 || ordinal >= ColumnDefinitions.Length)
throw new IndexOutOfRangeException("value must be between 0 and {0}".FormatInvariant(ColumnDefinitions.Length - 1));
throw new IndexOutOfRangeException($"value must be between 0 and {ColumnDefinitions.Length - 1}");
return ColumnDefinitions[ordinal].Name;
}

Expand All @@ -302,7 +302,7 @@ public string GetDataTypeName(int ordinal)
if (ColumnDefinitions is null)
throw new InvalidOperationException("There is no current result set.");
if (ordinal < 0 || ordinal >= ColumnDefinitions.Length)
throw new IndexOutOfRangeException("value must be between 0 and {0}.".FormatInvariant(ColumnDefinitions.Length));
throw new IndexOutOfRangeException($"value must be between 0 and {ColumnDefinitions.Length - 1}");

var mySqlDbType = ColumnTypes![ordinal];
if (mySqlDbType == MySqlDbType.String)
Expand All @@ -315,7 +315,7 @@ public Type GetFieldType(int ordinal)
if (ColumnDefinitions is null)
throw new InvalidOperationException("There is no current result set.");
if (ordinal < 0 || ordinal >= ColumnDefinitions.Length)
throw new IndexOutOfRangeException("value must be between 0 and {0}.".FormatInvariant(ColumnDefinitions.Length));
throw new IndexOutOfRangeException($"value must be between 0 and {ColumnDefinitions.Length - 1}");

var type = TypeMapper.Instance.GetColumnTypeMetadata(ColumnTypes![ordinal]).DbTypeMapping.ClrType;
if (Connection.AllowZeroDateTime && type == typeof(DateTime))
Expand Down Expand Up @@ -348,7 +348,7 @@ public int GetOrdinal(string name)
return column;
}

throw new IndexOutOfRangeException("The column name '{0}' does not exist in the result set.".FormatInvariant(name));
throw new IndexOutOfRangeException($"The column name '{name}' does not exist in the result set.");
}

public Row GetCurrentRow()
Expand Down
14 changes: 7 additions & 7 deletions src/MySqlConnector/Core/Row.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public Row Clone()
public object GetValue(int ordinal)
{
if (ordinal < 0 || ordinal >= ResultSet.ColumnDefinitions!.Length)
throw new ArgumentOutOfRangeException(nameof(ordinal), "value must be between 0 and {0}.".FormatInvariant(ResultSet.ColumnDefinitions!.Length - 1));
throw new ArgumentOutOfRangeException(nameof(ordinal), $"value must be between 0 and {ResultSet.ColumnDefinitions!.Length - 1}");

if (m_dataOffsets[ordinal] == -1)
return DBNull.Value;
Expand Down Expand Up @@ -216,7 +216,7 @@ public int GetInt32(int ordinal)
and not ColumnType.Int24 and not ColumnType.Long and not ColumnType.Longlong
and not ColumnType.Bit and not ColumnType.Year)
{
throw new InvalidCastException("Can't convert {0} to Int32".FormatInvariant(ResultSet.ColumnTypes![ordinal]));
throw new InvalidCastException($"Can't convert {ResultSet.ColumnTypes![ordinal]} to Int32");
}

var data = m_data.Slice(m_dataOffsets[ordinal], m_dataLengths[ordinal]).Span;
Expand Down Expand Up @@ -357,7 +357,7 @@ public DateTime GetDateTime(int ordinal)
if (dateString.Length is >= 10 and <= 26)
value = ParseDateTime(Encoding.UTF8.GetBytes(dateString));
else
throw new FormatException("Couldn't interpret '{0}' as a valid DateTime".FormatInvariant(value));
throw new FormatException($"Couldn't interpret value as a valid DateTime: {value}");
}

if (value is MySqlDateTime mySqlDateTime)
Expand Down Expand Up @@ -436,7 +436,7 @@ public MySqlGeometry GetMySqlGeometry(int ordinal)
var value = GetValue(ordinal);
if (value is byte[] bytes && ResultSet.ColumnDefinitions![ordinal].ColumnType == ColumnType.Geometry)
return new MySqlGeometry(bytes);
throw new InvalidCastException("Can't convert {0} to MySqlGeometry.".FormatInvariant(ResultSet.ColumnDefinitions![ordinal].ColumnType));
throw new InvalidCastException($"Can't convert {ResultSet.ColumnDefinitions![ordinal].ColumnType} to MySqlGeometry.");
}

public MySqlDecimal GetMySqlDecimal(int ordinal)
Expand All @@ -447,7 +447,7 @@ public MySqlDecimal GetMySqlDecimal(int ordinal)
var columnType = ResultSet.ColumnDefinitions![ordinal].ColumnType;
if (columnType is ColumnType.NewDecimal or ColumnType.Decimal)
return new MySqlDecimal(Encoding.UTF8.GetString(data));
throw new InvalidCastException("Can't convert {0} to MySqlDecimal.".FormatInvariant(ResultSet.ColumnDefinitions![ordinal].ColumnType));
throw new InvalidCastException($"Can't convert {ResultSet.ColumnDefinitions![ordinal].ColumnType} to MySqlDecimal.");
}

public int GetValues(object[] values)
Expand Down Expand Up @@ -557,7 +557,7 @@ protected object ParseDateTime(ReadOnlySpan<byte> value)
}

InvalidDateTime:
throw new FormatException("Couldn't interpret '{0}' as a valid DateTime".FormatInvariant(Encoding.UTF8.GetString(value)), exception);
throw new FormatException($"Couldn't interpret value as a valid DateTime: {Encoding.UTF8.GetString(value)}", exception);
}

#if NET5_0_OR_GREATER
Expand Down Expand Up @@ -615,7 +615,7 @@ private void CheckBinaryColumn(int ordinal)
columnType != ColumnType.Blob && columnType != ColumnType.MediumBlob && columnType != ColumnType.LongBlob &&
columnType != ColumnType.Geometry))
{
throw new InvalidCastException("Can't convert {0} to bytes.".FormatInvariant(columnType));
throw new InvalidCastException($"Can't convert {columnType} to bytes.");
}
}

Expand Down
9 changes: 7 additions & 2 deletions src/MySqlConnector/Core/SchemaProvider.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System.Globalization;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;

namespace MySqlConnector.Core;

Expand Down Expand Up @@ -36,7 +36,12 @@ private void DoFillDataSourceInformation(DataTable dataTable)
SupportedJoinOperators.RightOuter;
dataTable.Rows.Add(row);

static string GetVersion(Version v) => "{0:00}.{1:00}.{2:0000}".FormatInvariant(v.Major, v.Minor, v.Build);
static string GetVersion(Version v) =>
#if NET6_0_OR_GREATER
string.Create(CultureInfo.InvariantCulture, stackalloc char[10], $"{v.Major:00}.{v.Minor:00}.{v.Build:0000}");
#else
FormattableString.Invariant($"{v.Major:00}.{v.Minor:00}.{v.Build:0000}");
#endif
}

private static void DoFillDataTypes(DataTable dataTable)
Expand Down
20 changes: 10 additions & 10 deletions src/MySqlConnector/Core/ServerSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public ServerSession(ConnectionPool? pool, int poolGeneration, int id)
Pool = pool;
PoolGeneration = poolGeneration;
HostName = "";
m_logArguments = new object?[] { "{0}".FormatInvariant(Id), null };
m_logArguments = new object?[] { Id.ToString(CultureInfo.InvariantCulture), null };
m_activityTags = new ActivityTagsCollection();
Log.Trace("Session{0} created new session", m_logArguments);
}
Expand Down Expand Up @@ -149,7 +149,7 @@ public async Task PrepareAsync(IMySqlCommand command, IOBehavior ioBehavior, Can
if (cachedProcedure is null)
{
var name = NormalizedSchema.MustNormalize(command.CommandText!, command.Connection.Database);
throw new MySqlException("Procedure or function '{0}' cannot be found in database '{1}'.".FormatInvariant(name.Component, name.Schema));
throw new MySqlException($"Procedure or function '{name.Component}' cannot be found in database '{name.Schema}'.");
}

var parameterCount = cachedProcedure.Parameters.Count;
Expand Down Expand Up @@ -467,7 +467,7 @@ public async Task DisposeAsync(IOBehavior ioBehavior, CancellationToken cancella
if (authPluginName != "mysql_native_password" && authPluginName != "sha256_password" && authPluginName != "caching_sha2_password")
{
Log.Error("Session{0} unsupported authentication method AuthPluginName={1}", m_logArguments);
throw new NotSupportedException("Authentication method '{0}' is not supported.".FormatInvariant(initialHandshake.AuthPluginName));
throw new NotSupportedException($"Authentication method '{initialHandshake.AuthPluginName}' is not supported.");
}

ServerVersion = new(initialHandshake.ServerVersion);
Expand Down Expand Up @@ -714,7 +714,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,
if (!m_isSecureConnection)
{
Log.Error("Session{0} needs a secure connection to use AuthenticationMethod '{1}'", m_logArguments);
throw new MySqlException(MySqlErrorCode.UnableToConnectToHost, "Authentication method '{0}' requires a secure connection.".FormatInvariant(switchRequest.Name));
throw new MySqlException(MySqlErrorCode.UnableToConnectToHost, $"Authentication method '{switchRequest.Name}' requires a secure connection.");
}

// send the password as a NULL-terminated UTF-8 string
Expand Down Expand Up @@ -767,7 +767,7 @@ private async Task<PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs,

default:
Log.Error("Session{0} is requesting AuthenticationMethod '{1}' which is not supported", m_logArguments);
throw new NotSupportedException("Authentication method '{0}' is not supported.".FormatInvariant(switchRequest.Name));
throw new NotSupportedException($"Authentication method '{switchRequest.Name}' is not supported.");
}
}

Expand Down Expand Up @@ -846,7 +846,7 @@ private async Task<string> GetRsaPublicKeyAsync(string switchRequestName, Connec
{
m_logArguments[1] = cs.ServerRsaPublicKeyFile;
Log.Error(ex, "Session{0} couldn't load server's RSA public key from PublicKeyFile '{1}'", m_logArguments);
throw new MySqlException("Couldn't load server's RSA public key from '{0}'".FormatInvariant(cs.ServerRsaPublicKeyFile), ex);
throw new MySqlException($"Couldn't load server's RSA public key from '{cs.ServerRsaPublicKeyFile}'", ex);
}
}

Expand All @@ -862,7 +862,7 @@ private async Task<string> GetRsaPublicKeyAsync(string switchRequestName, Connec

m_logArguments[1] = switchRequestName;
Log.Error("Session{0} couldn't use AuthenticationMethod '{1}' because RSA key wasn't specified or couldn't be retrieved", m_logArguments);
throw new MySqlException(MySqlErrorCode.UnableToConnectToHost, "Authentication method '{0}' failed. Either use a secure connection, specify the server's RSA public key with ServerRSAPublicKeyFile, or set AllowPublicKeyRetrieval=True.".FormatInvariant(switchRequestName));
throw new MySqlException(MySqlErrorCode.UnableToConnectToHost, $"Authentication method '{switchRequestName}' failed. Either use a secure connection, specify the server's RSA public key with ServerRSAPublicKeyFile, or set AllowPublicKeyRetrieval=True.");
}

public async ValueTask<bool> TryPingAsync(bool logInfo, IOBehavior ioBehavior, CancellationToken cancellationToken)
Expand Down Expand Up @@ -1329,7 +1329,7 @@ private async Task InitSslAsync(ProtocolCapabilities serverCapabilities, Connect
{
m_logArguments[1] = cs.CertificateThumbprint;
Log.Error("Session{0} certificate with Thumbprint={1} not found in store", m_logArguments);
throw new MySqlException("Certificate with Thumbprint {0} not found".FormatInvariant(cs.CertificateThumbprint));
throw new MySqlException($"Certificate with Thumbprint {cs.CertificateThumbprint} not found");
}

clientCertificates = new(foundCertificates);
Expand Down Expand Up @@ -1793,7 +1793,7 @@ private void VerifyState(State state)
if (m_state != state)
{
Log.Error("Session{0} should have SessionStateExpected {1} but was SessionState {2}", m_logArguments[0], state, m_state);
throw new InvalidOperationException("Expected state to be {0} but was {1}.".FormatInvariant(state, m_state));
throw new InvalidOperationException($"Expected state to be {state} but was {m_state}.");
}
}

Expand All @@ -1803,7 +1803,7 @@ private void VerifyState(State state1, State state2, State state3, State state4,
{
Log.Error("Session{0} should have SessionStateExpected {1} or SessionStateExpected2 {2} or SessionStateExpected3 {3} or SessionStateExpected4 {4} or SessionStateExpected5 {5} or SessionStateExpected6 {6} but was SessionState {7}",
m_logArguments[0], state1, state2, state3, state4, state5, state6, m_state);
throw new InvalidOperationException("Expected state to be ({0}|{1}|{2}|{3}|{4}|{5}) but was {6}.".FormatInvariant(state1, state2, state3, state4, state5, state6, m_state));
throw new InvalidOperationException($"Expected state to be ({state1}|{state2}|{state3}|{state4}|{state5}|{state6}) but was {m_state}.");
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/MySqlConnector/Core/SingleCommandPayloadCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@ private static void WritePreparedStatement(IMySqlCommand command, PreparedStatem
var parameterName = preparedStatement.Statement.NormalizedParameterNames![i];
var parameterIndex = parameterName is not null ? (parameterCollection?.UnsafeIndexOf(parameterName) ?? -1) : preparedStatement.Statement.ParameterIndexes[i];
if (parameterIndex == -1 && parameterName is not null)
throw new MySqlException("Parameter '{0}' must be defined.".FormatInvariant(preparedStatement.Statement.ParameterNames![i]));
throw new MySqlException($"Parameter '{preparedStatement.Statement.ParameterNames![i]}' must be defined.");
else if (parameterIndex < 0 || parameterIndex >= (parameterCollection?.Count ?? 0))
throw new MySqlException("Parameter index {0} is invalid when only {1} parameter{2} defined.".FormatInvariant(parameterIndex, parameterCollection?.Count ?? 0, parameterCollection?.Count == 1 ? " is" : "s are"));
throw new MySqlException($"Parameter index {parameterIndex} is invalid when only {parameterCollection?.Count ?? 0} parameter{(parameterCollection?.Count == 1 ? " is" : "s are")} defined.");
parameters[i] = parameterCollection![parameterIndex];
}
for (var i = 0; i < attributeCount; i++)
Expand Down
Loading

0 comments on commit 6bd719c

Please sign in to comment.