Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CA1802;CA1805;CA1823;CA1822;CA1845;CA1846;CA1852; #2138

Merged
merged 3 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<ThirdPartyAssemblySigningCertName>3PartySHA2</ThirdPartyAssemblySigningCertName>
<PackageSigningCertName>NuGet</PackageSigningCertName>
<!-- Disable the warnings for now, enable batch by batch later-->
<NoWarn>$(NoWarn);CA1802;CA1805;CA1823;CA1822;CA1845;CA1846;CA1852;CA2007;CA2008;CA2012;CA2016;CA1835;CA2208;IDE0161;IDE0130;IDE0290;IDE1006;IDE0090</NoWarn>
<NoWarn>$(NoWarn);CA2007;CA2008;CA2012;CA2016;CA1835;CA2208;IDE0161;IDE0130;IDE0290;IDE1006;IDE0090</NoWarn>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

namespace AspNet.ChatSample.CSharpClient;

class Program
sealed class Program
{
private static readonly Func<Task> ReconnectDelayTask = () => DelayRandom(200, 1000);
private static readonly SemaphoreSlim ReconnectLock = new SemaphoreSlim(1);
Expand Down
7 changes: 5 additions & 2 deletions samples/ChatSample/ChatSample.CSharpClient/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System;
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -8,7 +11,7 @@

namespace ChatSample.CSharpClient
{
class Program
sealed class Program
{
static async Task Main(string[] args)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// A simple library file to test cross project reference issue: https://github.com/Azure/azure-signalr/issues/1720
namespace ManagementPublisher
{
internal class MessagePublisher
internal sealed class MessagePublisher
{
private const string Target = "Target";
private const string HubName = "Chat";
Expand Down
2 changes: 1 addition & 1 deletion src/Common/TextMessageParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.Azure.SignalR
/// </summary>
internal static class TextMessageParser
{
public static readonly byte RecordSeparator = 0x1e;
public const byte RecordSeparator = 0x1e;

public static bool TryParseMessage(ref ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> payload)
{
Expand Down
4 changes: 1 addition & 3 deletions src/Microsoft.Azure.SignalR.Common/Auth/AuthUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ internal static class AuthUtility
{
private const int MaxTokenLength = 4096;

private static readonly SignalRJwtSecurityTokenHandler JwtTokenHandler = new();

public static string GenerateJwtToken(byte[] keyBytes,
string? kid = null,
string? issuer = null,
Expand All @@ -29,7 +27,7 @@ public static string GenerateJwtToken(byte[] keyBytes,
{
var subject = claims == null ? null : new ClaimsIdentity(claims);

var token = JwtTokenHandler.CreateJwtSecurityToken(
var token = SignalRJwtSecurityTokenHandler.CreateJwtSecurityToken(
expires: expires,
issuedAt: issuedAt,
issuer: issuer,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ internal class MicrosoftEntraAccessKey : IAccessKey

private readonly IHttpClientFactory _httpClientFactory;

private volatile bool _isAuthorized = false;
private volatile bool _isAuthorized;

private DateTime _updateAt = DateTime.MinValue;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ internal class SignalRJwtSecurityTokenHandler
// Simplified from following codes:
// method `CreateJwtSecurityToken` in [JwtSecruityTokenHandler.cs](https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/6.22.0/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs#L487)
// method `CreateJwtSecurityTokenPrivate` in [JwtSecurityTokenHandler.cs](https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/6.22.0/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs#L616)
public string CreateJwtSecurityToken(DateTime? notBefore = null,
DateTime? expires = null,
DateTime? issuedAt = null,
string issuer = null,
string audience = null,
ClaimsIdentity subject = null,
byte[] key = null,
string kid = null,
AccessTokenAlgorithm algorithm = AccessTokenAlgorithm.HS256)
public static string CreateJwtSecurityToken(DateTime? notBefore = null,
DateTime? expires = null,
DateTime? issuedAt = null,
string issuer = null,
string audience = null,
ClaimsIdentity subject = null,
byte[] key = null,
string kid = null,
AccessTokenAlgorithm algorithm = AccessTokenAlgorithm.HS256)
{
if (!expires.HasValue || !issuedAt.HasValue || !notBefore.HasValue)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Azure.SignalR.Common/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static class Keys

public const string AzureSignalREndpointsKey = $"{AzureSignalRSectionKey}:Endpoints";

public static readonly string ConnectionStringSecondaryKey =
public const string ConnectionStringSecondaryKey =
$"ConnectionStrings:{ConnectionStringDefaultKey}";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public Task DisposeAsync(ConnectionContext connection)
return ((WebSocketConnectionContext)connection).StopAsync();
}

private Uri GetServiceUrl(IServiceEndpointProvider provider, string hubName, string connectionId, string target)
private static Uri GetServiceUrl(IServiceEndpointProvider provider, string hubName, string connectionId, string target)
{
var baseUri = new UriBuilder(provider.GetServerEndpoint(hubName));
var query = "cid=" + connectionId;
Expand All @@ -82,7 +82,12 @@ private Uri GetServiceUrl(IServiceEndpointProvider provider, string hubName, str
}
if (baseUri.Query != null && baseUri.Query.Length > 1)
{
#if NET6_0_OR_GREATER
baseUri.Query = string.Concat(baseUri.Query.AsSpan(1), "&", query);
#else

baseUri.Query = baseUri.Query.Substring(1) + "&" + query;
#endif
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal class MultiEndpointServiceConnectionContainer : IServiceConnectionConta

private (bool needRouter, IReadOnlyList<HubServiceEndpoint> endpoints) _routerEndpoints;

private int _started = 0;
private int _started;

public ServiceConnectionStatus Status => throw new NotSupportedException();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ private Task OfflineAsync()

public abstract Task CloseClientConnections(CancellationToken token);

private async Task PauseClientConnectionAsync(IClientConnection clientConnection)
private static async Task PauseClientConnectionAsync(IClientConnection clientConnection)
{
await clientConnection.PauseAsync();
await clientConnection.PauseAckAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ internal abstract class ServiceConnectionContainerBase : IServiceConnectionConta

private static readonly TimeSpan CheckTimeSpan = TimeSpan.FromMinutes(10);

private static readonly int MaxReconnectBackOffInternalInMilliseconds = 1000;
private const int MaxReconnectBackOffInternalInMilliseconds = 1000;

private static readonly TimeSpan MessageWriteRetryDelay = TimeSpan.FromMilliseconds(200);

private static readonly int MessageWriteMaxRetry = 3;
private const int MessageWriteMaxRetry = 3;

// Give (interval * 3 + 1) delay when check value expire.
private static readonly long DefaultServersPingTimeoutTicks = Stopwatch.Frequency * ((long)Constants.Periods.DefaultServersPingInterval.TotalSeconds * 3 + 1);
Expand Down Expand Up @@ -62,7 +62,7 @@ internal abstract class ServiceConnectionContainerBase : IServiceConnectionConta

private volatile bool _hasClients;

private volatile bool _terminated = false;
private volatile bool _terminated;

public HubServiceEndpoint Endpoint { get; }

Expand Down Expand Up @@ -568,7 +568,7 @@ private IServiceConnection SelectConnection(ServiceMessage message)
return connection;
}

private bool IsActiveConnection(IServiceConnection connection)
private static bool IsActiveConnection(IServiceConnection connection)
{
return connection != null && connection.Status == ServiceConnectionStatus.Connected;
}
Expand Down Expand Up @@ -720,9 +720,9 @@ protected internal sealed class CustomizedPingTimer : IDisposable

// Considering parallel add endpoints to save time,
// Add a counter control multiple time call Start() and Stop() correctly.
private long _counter = 0;
private long _counter;

private long _lastSendTimestamp = 0;
private long _lastSendTimestamp;

private TimerAwaitable _timer;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ namespace Microsoft.Azure.SignalR;

internal class ServiceDiagnosticLogsContext
{
public bool EnableMessageLog { get; set; } = false;
public bool EnableMessageLog { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,12 @@ public static bool TryGetServersTag(this ServicePingMessage ping, out string ser
if (TryGetValue(ping, ServersKey, out var value) && !string.IsNullOrEmpty(value))
{
var indexPos = value.IndexOf(":");
#if NET6_0_OR_GREATER
if (long.TryParse(value.AsSpan(0, indexPos), out updatedTime))
#else

if (long.TryParse(value.Substring(0, indexPos), out updatedTime))
#endif
{
serversTag = value.Substring(indexPos + 1);
return true;
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.Azure.SignalR.Common/Utilities/BackOffPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ namespace Microsoft.Azure.SignalR.Common
{
internal class BackOffPolicy
{
private TaskCompletionSource<bool> _currentProbeTcs = null;
private int _currentRetryCount = 0;
private TaskCompletionSource<bool> _currentProbeTcs;
private int _currentRetryCount;

/// <summary>
/// Provides a synchronized mechanism of calling probing funcs by multiple concurrent callers.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,26 +50,26 @@ internal static class ConnectionStringParser

private const string VersionProperty = "version";

private static readonly string InvalidEndpointProperty = $"Invalid value for {EndpointProperty} property, it must be a valid URI.";
private const string InvalidEndpointProperty = $"Invalid value for {EndpointProperty} property, it must be a valid URI.";

private static readonly string InvalidClientEndpointProperty = $"Invalid value for {ClientEndpointProperty} property, it must be a valid URI.";
private const string InvalidClientEndpointProperty = $"Invalid value for {ClientEndpointProperty} property, it must be a valid URI.";

private static readonly string InvalidServerEndpointProperty = $"Invalid value for {ServerEndpointProperty} property, it must be a valid URI.";
private const string InvalidServerEndpointProperty = $"Invalid value for {ServerEndpointProperty} property, it must be a valid URI.";

private static readonly string InvalidPortValue = $"Invalid value for {PortProperty} property, it must be an positive integer between (0, 65536).";
private const string InvalidPortValue = $"Invalid value for {PortProperty} property, it must be an positive integer between (0, 65536).";

private static readonly char[] KeyValueSeparator = { '=' };

private static readonly string MissingClientIdProperty =
private const string MissingClientIdProperty =
$"Connection string missing required properties {ClientIdProperty}.";

private static readonly string MissingClientSecretProperty =
private const string MissingClientSecretProperty =
$"Connection string missing required properties {ClientSecretProperty} or {ClientCertProperty}.";

private static readonly string MissingEndpointProperty =
private const string MissingEndpointProperty =
$"Connection string missing required properties {EndpointProperty}.";

private static readonly string MissingTenantIdProperty =
private const string MissingTenantIdProperty =
$"Connection string missing required properties {TenantIdProperty}.";

private static readonly char[] PropertySeparator = { ';' };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ internal class PauseHandler
{
private readonly SemaphoreSlim _pauseSemaphore = new(1, 1);

private volatile int _paused = 0;
private volatile int _paused;

private volatile int _pauseAcked = 1;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace Microsoft.Azure.SignalR
{
internal class StaticRandom
internal sealed class StaticRandom
{
private static readonly object RandomLock = new object();
private static readonly Random RandomInterval = new Random((int)DateTime.UtcNow.Ticks);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ public override IActionResult GetHealthStatus()
return Ok();
}

private Task SendAsync(IClientProxy client, string method, object[] arguments, CancellationToken cancellationToken = default)
private static Task SendAsync(IClientProxy client, string method, object[] arguments, CancellationToken cancellationToken = default)
{
var argsLen = arguments?.Length ?? 0;

Expand Down Expand Up @@ -650,7 +650,7 @@ private string GetInternalHubName(string application, string hub)
return _hubs.GetOrAdd((hub, application), application.ToLower() + "_" + hub.ToLower());
}

private ValueTask SendCloseAsync(HubConnectionContext connection, string message)
private static ValueTask SendCloseAsync(HubConnectionContext connection, string message)
{
return connection.WriteAsync(new CloseMessage(message, true));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public async Task RemoveClientConnectionAsync(HubConnectionContext connectionCon
}
}

private IMemoryOwner<byte> BuildCloseConnectionPayload(string error)
private static IMemoryOwner<byte> BuildCloseConnectionPayload(string error)
{
var writer = MemoryBufferWriter.Get();
try
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ internal class HubProxyHandler<THub> : HubConnectionHandler<THub> where THub: Hu

private readonly string _hubName = typeof(THub).Name;

private readonly List<string> _defaultProtocols = new List<string>();

public HubProxyHandler(
IOptionsMonitor<UpstreamOptions> upstreamSettings,
HubLifetimeManager<THub> lifetimeManager,
Expand Down Expand Up @@ -158,32 +156,32 @@ private Task InvokeSendCloseAsync(HubConnectionContext connection, Exception exc
return task;
}

private bool GetAllowReconnect(HubConnectionContext connection)
private static bool GetAllowReconnect(HubConnectionContext connection)
{
return (bool)_hubConnectionContext_AllowReconnect.GetValue(connection);
}

private Task InvokeAbortAsync(HubConnectionContext connection)
private static Task InvokeAbortAsync(HubConnectionContext connection)
{
return (Task)_hubConnectionContext_AbortAsync.Invoke(connection, Array.Empty<object>());
}

private PipeReader GetInput(HubConnectionContext connection)
private static PipeReader GetInput(HubConnectionContext connection)
{
return (PipeReader)_hubConnectionContext_Input.GetValue(connection);
}

private void InvokeStopClientTimeout(HubConnectionContext connection)
private static void InvokeStopClientTimeout(HubConnectionContext connection)
{
_hubConnectionContext_StopClientTimeout.Invoke(connection, Array.Empty<object>());
}

private void InvokeBeginClientTimeout(HubConnectionContext connection)
private static void InvokeBeginClientTimeout(HubConnectionContext connection)
{
_hubConnectionContext_BeginClientTimeout.Invoke(connection, Array.Empty<object>());
}

private void InvokeCleanup(HubConnectionContext connection)
private static void InvokeCleanup(HubConnectionContext connection)
{
_hubConnectionContext_Cleanup.Invoke(connection, Array.Empty<object>());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public override string ToString()
return $"{UrlTemplate}(event:'{EventPattern}',hub:'{HubPattern}',category:'{CategoryPattern}')";
}

private void SetPattern(string pattern, ref string field, ref HashSet<string> store)
private static void SetPattern(string pattern, ref string field, ref HashSet<string> store)
{
if (field != pattern)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class ServiceManagerOptions
/// <summary>
/// Gets or sets a service endpoint of Azure SignalR Service instance by connection string.
/// </summary>
public string? ConnectionString { get; set; } = null;
public string? ConnectionString { get; set; }

/// <summary>
/// Gets or sets multiple service endpoints of Azure SignalR Service instances.
Expand Down Expand Up @@ -72,10 +72,10 @@ public void UseJsonObjectSerializer(ObjectSerializer objectSerializer)
}

/// <summary>
/// Gets or sets a value indicating whether message tracing ID is append to messages.
/// Gets or sets a value indicating whether message tracing ID is append to messages. By default it is false.
/// </summary>
// not ready
internal bool EnableMessageTracing { get; set; } = false;
internal bool EnableMessageTracing { get; set; }

internal string? ProductInfo { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ internal class HealthCheckOption
public TimeSpan CheckInterval { get; set; } = TimeSpan.FromMinutes(2);
public TimeSpan RetryInterval { get; set; } = TimeSpan.FromSeconds(3);
public TimeSpan HttpTimeout { get; set; } = TimeSpan.FromSeconds(2);
public bool EnabledForSingleEndpoint { get; set; } = false;
public bool EnabledForSingleEndpoint { get; set; }
}
Loading
Loading