diff --git a/.editorconfig b/.editorconfig index 53c54022e..045844b02 100644 --- a/.editorconfig +++ b/.editorconfig @@ -192,7 +192,34 @@ dotnet_naming_symbols.everything_else.applicable_accessibilities = * dotnet_diagnostic.CA1812.severity = none dotnet_diagnostic.CA1724.severity = none dotnet_diagnostic.CA1515.severity = none +dotnet_diagnostic.CA2007.severity = none +dotnet_diagnostic.CA1707.severity = none +dotnet_diagnostic.CA1062.severity = none +dotnet_diagnostic.CA1816.severity = none +dotnet_diagnostic.CA1303.severity = none +dotnet_diagnostic.CA1002.severity = none +dotnet_diagnostic.CA1032.severity = none +dotnet_diagnostic.CA1034.severity = none +dotnet_diagnostic.CA1019.severity = none +dotnet_diagnostic.CA1308.severity = none dotnet_diagnostic.IDE0058.severity = none # Disable temporarily dotnet_diagnostic.xUnit1051.severity = none + +# Rider +resharper_inconsistent_naming_highlighting = hint +resharper_static_member_in_generic_type_highlighting = hint +resharper_check_namespace_highlighting = hint +resharper_variable_hides_outer_variable_highlighting = hint +resharper_parameter_hides_member_highlighting = hint +resharper_not_null_or_required_member_is_not_initialized_highlighting = hint + +resharper_convert_type_check_pattern_to_null_check_highlighting = none +resharper_convert_type_check_to_null_check_highlighting = none +resharper_redundant_record_class_keyword_highlighting = none + +[test/**] +resharper_equal_expression_comparison_highlighting = none +resharper_entity_framework_model_validation_unlimited_string_length_highlighting = none +resharper_unused_auto_property_accessor_local_highlighting = none diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/CQRSEndpointRouteBuilderExtensions.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/CQRSEndpointRouteBuilderExtensions.cs index 0d5d44cd7..6e9d57a2b 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/CQRSEndpointRouteBuilderExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/CQRSEndpointRouteBuilderExtensions.cs @@ -40,9 +40,9 @@ public class CQRSPipelineBuilder { public Func ObjectsFilter { get; set; } = _ => true; - public Action Commands { get; set; } = app => { }; - public Action Queries { get; set; } = app => { }; - public Action Operations { get; set; } = app => { }; + public Action Commands { get; set; } = _ => { }; + public Action Queries { get; set; } = _ => { }; + public Action Operations { get; set; } = _ => { }; private readonly IEndpointRouteBuilder routeBuilder; diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/LocalCallContext.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/LocalCallContext.cs index 1c054208e..470c732ae 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/LocalCallContext.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/LocalCallContext.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Security.Claims; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; @@ -49,6 +50,7 @@ public override ISession Session set { } } + [SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] public LocalCallContext( IServiceProvider requestServices, ClaimsPrincipal user, diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Middleware/CQRSMiddleware.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Middleware/CQRSMiddleware.cs index ef097e199..a69813b21 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Middleware/CQRSMiddleware.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Middleware/CQRSMiddleware.cs @@ -1,5 +1,4 @@ using System.Diagnostics.CodeAnalysis; -using System.Diagnostics.Metrics; using LeanCode.CQRS.AspNetCore.Serialization; using LeanCode.CQRS.Execution; using Microsoft.AspNetCore.Http; diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs index 23dcfb27b..a30b00852 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs @@ -1,8 +1,8 @@ using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Text; using LeanCode.Contracts; using LeanCode.CQRS.Execution; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.ModelBinding; @@ -213,6 +213,7 @@ private static void AddCommonResponses(ApiDescription apiDescription) private static CQRSBodyModelMetadata CreateModelMetadata(Type type) => new(ModelMetadataIdentity.ForType(type)); } +[SuppressMessage("ReSharper", "UnassignedGetOnlyAutoProperty")] internal sealed class CQRSBodyModelMetadata : ModelMetadata { public CQRSBodyModelMetadata(ModelMetadataIdentity identity) @@ -222,7 +223,7 @@ public CQRSBodyModelMetadata(ModelMetadataIdentity identity) ImmutableDictionary.Empty; public override string? BinderModelName { get; } public override Type? BinderType { get; } - public override BindingSource? BindingSource => BindingSource.Body; + public override BindingSource BindingSource => BindingSource.Body; public override bool ConvertEmptyStringToNull { get; } public override string? DataTypeName { get; } public override string? Description { get; } diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs index d9f1fc5c3..798801619 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs @@ -1,4 +1,5 @@ using System.Collections.Frozen; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using LeanCode.Components; using LeanCode.Contracts; @@ -26,6 +27,7 @@ public CQRSObjectsRegistrationSource(IServiceCollection services, IObjectExecuto public CQRSObjectMetadata MetadataFor(Type type) => cachedMetadata.Value[type]; + [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public void AddCQRSObjects(TypesCatalog contractsCatalog, TypesCatalog handlersCatalog) { var contracts = contractsCatalog diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/ServiceCollectionRegistrationExtensions.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/ServiceCollectionRegistrationExtensions.cs index 3cbec42dc..8051d9b27 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/ServiceCollectionRegistrationExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/ServiceCollectionRegistrationExtensions.cs @@ -25,7 +25,7 @@ public static void AddCQRSHandler(this IServiceCollection serviceCollection, CQR new(MakeHandlerInterfaceType(obj), sp => sp.GetRequiredService(obj.HandlerType), ServiceLifetime.Scoped) ); - Type MakeHandlerInterfaceType(CQRSObjectMetadata obj) + static Type MakeHandlerInterfaceType(CQRSObjectMetadata obj) { return obj.ObjectKind switch { diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Serialization/ISerializer.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Serialization/ISerializer.cs index bc99e3c3f..1b30bd3df 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Serialization/ISerializer.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Serialization/ISerializer.cs @@ -1,5 +1,4 @@ using System.Text.Json; -using LeanCode.Serialization; using Microsoft.AspNetCore.Http.Json; using Microsoft.Extensions.Options; diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs index 387ac1549..e3297aa2a 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs @@ -11,7 +11,6 @@ using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Options; namespace LeanCode.CQRS.AspNetCore; diff --git a/src/CQRS/LeanCode.CQRS.Execution/CommandHandlerNotFoundException.cs b/src/CQRS/LeanCode.CQRS.Execution/CommandHandlerNotFoundException.cs index 21ca947c6..e663f3110 100644 --- a/src/CQRS/LeanCode.CQRS.Execution/CommandHandlerNotFoundException.cs +++ b/src/CQRS/LeanCode.CQRS.Execution/CommandHandlerNotFoundException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.CQRS.Execution; public class CommandHandlerNotFoundException : Exception diff --git a/src/CQRS/LeanCode.CQRS.Execution/ICommandHandler.cs b/src/CQRS/LeanCode.CQRS.Execution/ICommandHandler.cs index d67839574..c70a3e6bb 100644 --- a/src/CQRS/LeanCode.CQRS.Execution/ICommandHandler.cs +++ b/src/CQRS/LeanCode.CQRS.Execution/ICommandHandler.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using LeanCode.Contracts; using Microsoft.AspNetCore.Http; diff --git a/src/CQRS/LeanCode.CQRS.Execution/IOperationHandler.cs b/src/CQRS/LeanCode.CQRS.Execution/IOperationHandler.cs index 4a5302f16..3965f533e 100644 --- a/src/CQRS/LeanCode.CQRS.Execution/IOperationHandler.cs +++ b/src/CQRS/LeanCode.CQRS.Execution/IOperationHandler.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using LeanCode.Contracts; using Microsoft.AspNetCore.Http; @@ -7,5 +6,5 @@ namespace LeanCode.CQRS.Execution; public interface IOperationHandler where TOperation : IOperation { - public Task ExecuteAsync(HttpContext context, TOperation operation); + Task ExecuteAsync(HttpContext context, TOperation operation); } diff --git a/src/CQRS/LeanCode.CQRS.Execution/IQueryHandler.cs b/src/CQRS/LeanCode.CQRS.Execution/IQueryHandler.cs index dd9db4125..031da8a0b 100644 --- a/src/CQRS/LeanCode.CQRS.Execution/IQueryHandler.cs +++ b/src/CQRS/LeanCode.CQRS.Execution/IQueryHandler.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using LeanCode.Contracts; using Microsoft.AspNetCore.Http; diff --git a/src/CQRS/LeanCode.CQRS.Execution/OperationHandlerNotFoundException.cs b/src/CQRS/LeanCode.CQRS.Execution/OperationHandlerNotFoundException.cs index e2082c54b..6e7d9fac6 100644 --- a/src/CQRS/LeanCode.CQRS.Execution/OperationHandlerNotFoundException.cs +++ b/src/CQRS/LeanCode.CQRS.Execution/OperationHandlerNotFoundException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.CQRS.Execution; public class OperationHandlerNotFoundException : Exception diff --git a/src/CQRS/LeanCode.CQRS.Execution/QueryHandlerNotFoundException.cs b/src/CQRS/LeanCode.CQRS.Execution/QueryHandlerNotFoundException.cs index 4140c58db..fffac2ea5 100644 --- a/src/CQRS/LeanCode.CQRS.Execution/QueryHandlerNotFoundException.cs +++ b/src/CQRS/LeanCode.CQRS.Execution/QueryHandlerNotFoundException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.CQRS.Execution; public class QueryHandlerNotFoundException : Exception diff --git a/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRegistrationConfigurationExtensions.cs b/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRegistrationConfigurationExtensions.cs index ca824a12a..b63fae20c 100644 --- a/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRegistrationConfigurationExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRegistrationConfigurationExtensions.cs @@ -31,7 +31,7 @@ Type defaultDefinition ) { var outer = types.Where(RegistrationMetadata.IsConsumer); - var inner = types.Where((Type x) => x.HasInterface(typeof(IConsumerDefinition<>))); + var inner = types.Where(x => x.HasInterface(typeof(IConsumerDefinition<>))); var enumerable = from c in outer join d in inner on c equals d.GetClosingArgument(typeof(IConsumerDefinition<>)) into dc diff --git a/src/CQRS/LeanCode.CQRS.MassTransitRelay/Testing/ResettableBusActivityMonitor.cs b/src/CQRS/LeanCode.CQRS.MassTransitRelay/Testing/ResettableBusActivityMonitor.cs index 3b9149fe0..5f038f252 100644 --- a/src/CQRS/LeanCode.CQRS.MassTransitRelay/Testing/ResettableBusActivityMonitor.cs +++ b/src/CQRS/LeanCode.CQRS.MassTransitRelay/Testing/ResettableBusActivityMonitor.cs @@ -13,9 +13,9 @@ public sealed class ResettableBusActivityMonitor IPublishObserver, IDisposable { - private readonly object mutex = new object(); + private readonly Lock mutex = new(); private readonly AsyncManualResetEvent inactive = new(true); - private readonly RollingTimer timer; + private readonly RollingTimer rollingTimer; private volatile int consumersInFlight; private volatile int receiversInFlight; @@ -27,7 +27,7 @@ public sealed class ResettableBusActivityMonitor public ResettableBusActivityMonitor(TimeSpan inactivityWaitTime) { - timer = new RollingTimer(OnTimer, inactivityWaitTime); + rollingTimer = new RollingTimer(OnTimer, inactivityWaitTime); } public static ResettableBusActivityMonitor CreateFor(IBusControl bus, TimeSpan inactivityWaitTime) @@ -83,7 +83,7 @@ Task IPublishObserver.PublishFault(PublishContext context, Exception excep Decrement(ref publishInFlight); [System.Diagnostics.CodeAnalysis.SuppressMessage("?", "CA1063", Justification = "We want clean API.")] - void IDisposable.Dispose() => timer.Dispose(); + void IDisposable.Dispose() => rollingTimer.Dispose(); private Task Increment(ref int counter) { @@ -91,7 +91,7 @@ private Task Increment(ref int counter) { Interlocked.Increment(ref counter); inactive.Reset(); - timer.Stop(); + rollingTimer.Stop(); } return Task.CompletedTask; @@ -105,7 +105,7 @@ private Task Decrement(ref int counter) if (HasStabilized) { - timer.Restart(); + rollingTimer.Restart(); } } diff --git a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/Exceptions.cs b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/Exceptions.cs index 2ccc3d47e..60bedc2c2 100644 --- a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/Exceptions.cs +++ b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/Exceptions.cs @@ -1,4 +1,3 @@ -using System; using System.Net; namespace LeanCode.CQRS.RemoteHttp.Client; diff --git a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpCommandsExecutor.cs b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpCommandsExecutor.cs index b550b8a40..355bda68f 100644 --- a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpCommandsExecutor.cs +++ b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpCommandsExecutor.cs @@ -1,12 +1,7 @@ -using System; using System.Collections.Immutable; -using System.IO; -using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; using LeanCode.Contracts; using LeanCode.Contracts.Validation; @@ -30,7 +25,7 @@ public virtual async Task RunAsync(ICommand command, Cancellation { using var content = JsonContent.Create(command, command.GetType(), options: serializerOptions); using var response = await client.PostAsync( - "command/" + command.GetType().FullName, + new Uri("command/" + command.GetType().FullName, UriKind.Relative), content, cancellationToken ); diff --git a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpOperationsExecutor.cs b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpOperationsExecutor.cs index 71dcda7bb..2ced4266f 100644 --- a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpOperationsExecutor.cs +++ b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpOperationsExecutor.cs @@ -25,7 +25,7 @@ public virtual async Task GetAsync( { using var content = JsonContent.Create(operation, operation.GetType(), options: serializerOptions); using var response = await client.PostAsync( - "operation/" + operation.GetType().FullName, + new Uri("operation/" + operation.GetType().FullName, UriKind.Relative), content, cancellationToken ); diff --git a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpQueriesExecutor.cs b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpQueriesExecutor.cs index be164db7f..2d1c7e17e 100644 --- a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpQueriesExecutor.cs +++ b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpQueriesExecutor.cs @@ -1,8 +1,5 @@ -using System; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; using LeanCode.Contracts; namespace LeanCode.CQRS.RemoteHttp.Client; @@ -27,7 +24,11 @@ public virtual async Task GetAsync( ) { using var content = JsonContent.Create(query, query.GetType(), options: serializerOptions); - using var response = await client.PostAsync("query/" + query.GetType().FullName, content, cancellationToken); + using var response = await client.PostAsync( + new Uri("query/" + query.GetType().FullName, UriKind.Relative), + content, + cancellationToken + ); response.HandleCommonCQRSErrors(); diff --git a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpResponseMessageExtensions.cs b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpResponseMessageExtensions.cs index 5562ee562..d7abf7432 100644 --- a/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpResponseMessageExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.RemoteHttp.Client/HttpResponseMessageExtensions.cs @@ -1,5 +1,3 @@ -using System; -using System.Net.Http; using static System.Net.HttpStatusCode; namespace LeanCode.CQRS.RemoteHttp.Client; diff --git a/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs b/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs index ff4d8cbf7..da7252707 100644 --- a/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs @@ -1,4 +1,3 @@ -using System.Linq; using System.Security.Claims; namespace LeanCode.CQRS.Security; diff --git a/src/CQRS/LeanCode.CQRS.Security/CustomAuthorizerNotFoundException.cs b/src/CQRS/LeanCode.CQRS.Security/CustomAuthorizerNotFoundException.cs index 22ea974f7..b6e25cdd2 100644 --- a/src/CQRS/LeanCode.CQRS.Security/CustomAuthorizerNotFoundException.cs +++ b/src/CQRS/LeanCode.CQRS.Security/CustomAuthorizerNotFoundException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.CQRS.Security; public class CustomAuthorizerNotFoundException : Exception diff --git a/src/CQRS/LeanCode.CQRS.Security/DefaultPermissionAuthorizer.cs b/src/CQRS/LeanCode.CQRS.Security/DefaultPermissionAuthorizer.cs index d837e9a68..110c09a5a 100644 --- a/src/CQRS/LeanCode.CQRS.Security/DefaultPermissionAuthorizer.cs +++ b/src/CQRS/LeanCode.CQRS.Security/DefaultPermissionAuthorizer.cs @@ -1,7 +1,5 @@ using System.Security.Claims; -using System.Threading.Tasks; using LeanCode.Contracts.Security; -using Microsoft.AspNetCore.Http; namespace LeanCode.CQRS.Security; diff --git a/src/CQRS/LeanCode.CQRS.Security/Exceptions/InsufficientPermissionException.cs b/src/CQRS/LeanCode.CQRS.Security/Exceptions/InsufficientPermissionException.cs index 5f6190467..f4cb64c1e 100644 --- a/src/CQRS/LeanCode.CQRS.Security/Exceptions/InsufficientPermissionException.cs +++ b/src/CQRS/LeanCode.CQRS.Security/Exceptions/InsufficientPermissionException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.CQRS.Security.Exceptions; public class InsufficientPermissionException : Exception diff --git a/src/CQRS/LeanCode.CQRS.Security/Exceptions/UnauthenticatedException.cs b/src/CQRS/LeanCode.CQRS.Security/Exceptions/UnauthenticatedException.cs index 3b4f49aaf..cb66a8d14 100644 --- a/src/CQRS/LeanCode.CQRS.Security/Exceptions/UnauthenticatedException.cs +++ b/src/CQRS/LeanCode.CQRS.Security/Exceptions/UnauthenticatedException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.CQRS.Security.Exceptions; public class UnauthenticatedException : Exception diff --git a/src/CQRS/LeanCode.CQRS.Security/IAuthorizerResolver.cs b/src/CQRS/LeanCode.CQRS.Security/IAuthorizerResolver.cs index 0aaf4a8a3..5d61d2717 100644 --- a/src/CQRS/LeanCode.CQRS.Security/IAuthorizerResolver.cs +++ b/src/CQRS/LeanCode.CQRS.Security/IAuthorizerResolver.cs @@ -1,6 +1,6 @@ namespace LeanCode.CQRS.Security; -public interface IAuthorizerResolver +public interface IAuthorizerResolver { ICustomAuthorizerWrapper? FindAuthorizer(Type authorizerType, Type objectType); } diff --git a/src/CQRS/LeanCode.CQRS.Security/IRoleRegistration.cs b/src/CQRS/LeanCode.CQRS.Security/IRoleRegistration.cs index 6da223dfb..cee5561aa 100644 --- a/src/CQRS/LeanCode.CQRS.Security/IRoleRegistration.cs +++ b/src/CQRS/LeanCode.CQRS.Security/IRoleRegistration.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace LeanCode.CQRS.Security; public interface IRoleRegistration diff --git a/src/CQRS/LeanCode.CQRS.Security/Role.cs b/src/CQRS/LeanCode.CQRS.Security/Role.cs index 30ae2b130..04b7ada4a 100644 --- a/src/CQRS/LeanCode.CQRS.Security/Role.cs +++ b/src/CQRS/LeanCode.CQRS.Security/Role.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using System.Collections.Immutable; namespace LeanCode.CQRS.Security; diff --git a/src/CQRS/LeanCode.CQRS.Security/RoleRegistry.cs b/src/CQRS/LeanCode.CQRS.Security/RoleRegistry.cs index a1346f7c1..73a833a0f 100644 --- a/src/CQRS/LeanCode.CQRS.Security/RoleRegistry.cs +++ b/src/CQRS/LeanCode.CQRS.Security/RoleRegistry.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; namespace LeanCode.CQRS.Security; diff --git a/src/CQRS/LeanCode.CQRS.Validation/ICommandValidator.cs b/src/CQRS/LeanCode.CQRS.Validation/ICommandValidator.cs index 2a999c2e9..41da62a15 100644 --- a/src/CQRS/LeanCode.CQRS.Validation/ICommandValidator.cs +++ b/src/CQRS/LeanCode.CQRS.Validation/ICommandValidator.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using LeanCode.Contracts; using LeanCode.Contracts.Validation; using Microsoft.AspNetCore.Http; diff --git a/src/Core/LeanCode.Components/TypesCatalog.cs b/src/Core/LeanCode.Components/TypesCatalog.cs index c8afda9c6..e237778c1 100644 --- a/src/Core/LeanCode.Components/TypesCatalog.cs +++ b/src/Core/LeanCode.Components/TypesCatalog.cs @@ -1,6 +1,4 @@ -using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Reflection; namespace LeanCode.Components; diff --git a/src/Core/LeanCode.Startup.Autofac/LeanProgram.cs b/src/Core/LeanCode.Startup.Autofac/LeanProgram.cs index 945fcdff1..6f74fa489 100644 --- a/src/Core/LeanCode.Startup.Autofac/LeanProgram.cs +++ b/src/Core/LeanCode.Startup.Autofac/LeanProgram.cs @@ -1,4 +1,3 @@ -using System.IO; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; @@ -16,7 +15,7 @@ public static IHostBuilder BuildMinimalHost() return new HostBuilder() .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureAppConfiguration( - (hostingContext, config) => + (_, config) => { config.AddEnvironmentVariables(); } diff --git a/src/Core/LeanCode.Startup.MicrosoftDI/LeanProgram.cs b/src/Core/LeanCode.Startup.MicrosoftDI/LeanProgram.cs index 7d31812cf..6fcc26555 100644 --- a/src/Core/LeanCode.Startup.MicrosoftDI/LeanProgram.cs +++ b/src/Core/LeanCode.Startup.MicrosoftDI/LeanProgram.cs @@ -13,7 +13,7 @@ public static IHostBuilder BuildMinimalHost() { return new HostBuilder() .ConfigureAppConfiguration( - (hostingContext, config) => + (_, config) => { config.AddEnvironmentVariables(); } diff --git a/src/Domain/LeanCode.DomainModels.EF/CachingEFRepository.cs b/src/Domain/LeanCode.DomainModels.EF/CachingEFRepository.cs index 660582b63..9b6aaef94 100644 --- a/src/Domain/LeanCode.DomainModels.EF/CachingEFRepository.cs +++ b/src/Domain/LeanCode.DomainModels.EF/CachingEFRepository.cs @@ -35,7 +35,7 @@ protected CachingEFRepository(TContext dbContext) { // Safety: aggregates are bound to have Id as a primary key by design. var primaryKey = DbContext.Model.FindEntityType(typeof(TEntity))!.FindPrimaryKey()!; - return ((IDbContextDependencies)DbContext).StateManager!.TryGetEntryTyped(primaryKey, id)?.Entity as TEntity; + return ((IDbContextDependencies)DbContext).StateManager.TryGetEntryTyped(primaryKey, id)?.Entity as TEntity; } [SuppressMessage( @@ -47,7 +47,7 @@ protected CachingEFRepository(TContext dbContext) { // Safety: aggregates are bound to have Id as a primary key by design. var primaryKey = DbContext.Model.FindEntityType(typeof(TEntity))!.FindPrimaryKey()!; - return ((IDbContextDependencies)DbContext).StateManager!.TryGetEntryTyped(primaryKey, id)?.Entity as TEntity; + return ((IDbContextDependencies)DbContext).StateManager.TryGetEntryTyped(primaryKey, id)?.Entity as TEntity; } protected ValueTask FindTrackedOrLoadNewAsync(TIdentity id, Func, Task> query) diff --git a/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs b/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs index 16e1beebe..68c6b7dd0 100644 --- a/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs +++ b/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs @@ -1,4 +1,3 @@ -using System.Linq; using LeanCode.DomainModels.Model; using Microsoft.EntityFrameworkCore; diff --git a/src/Domain/LeanCode.DomainModels.EF/EFRepository.cs b/src/Domain/LeanCode.DomainModels.EF/EFRepository.cs index 6314d2c1b..0dc125094 100644 --- a/src/Domain/LeanCode.DomainModels.EF/EFRepository.cs +++ b/src/Domain/LeanCode.DomainModels.EF/EFRepository.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using LeanCode.DomainModels.DataAccess; using LeanCode.DomainModels.Model; using LeanCode.TimeProvider; @@ -39,6 +40,7 @@ public virtual void Delete(TEntity entity) DbSet.Remove(entity); } + [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public virtual void DeleteRange(IEnumerable entities) { foreach (var oc in entities.OfType()) diff --git a/src/Domain/LeanCode.DomainModels.EF/ModelBuilderExtensions.cs b/src/Domain/LeanCode.DomainModels.EF/ModelBuilderExtensions.cs index a58d9084b..e5e28e85d 100644 --- a/src/Domain/LeanCode.DomainModels.EF/ModelBuilderExtensions.cs +++ b/src/Domain/LeanCode.DomainModels.EF/ModelBuilderExtensions.cs @@ -1,5 +1,3 @@ -using System; -using System.Linq.Expressions; using System.Reflection; using LeanCode.DomainModels.Model; using Microsoft.EntityFrameworkCore; @@ -73,7 +71,7 @@ public static void EnableOptimisticConcurrency( ) where TEntity : class, IOptimisticConcurrency { - builder.Entity().IsOptimisticConcurrent(useExplicitBackingFields, addRowVersion); + builder.Entity().IsOptimisticConcurrent(useExplicitBackingFields, addRowVersion); } private static string GetBackingFieldFor(string fieldName) diff --git a/src/Domain/LeanCode.DomainModels.EF/SimpleEFRepository.cs b/src/Domain/LeanCode.DomainModels.EF/SimpleEFRepository.cs index 0e08af68c..6989aecb1 100644 --- a/src/Domain/LeanCode.DomainModels.EF/SimpleEFRepository.cs +++ b/src/Domain/LeanCode.DomainModels.EF/SimpleEFRepository.cs @@ -5,8 +5,8 @@ namespace LeanCode.DomainModels.EF; public sealed class SimpleEFRepository : EFRepository where TEntity : class, IAggregateRoot - where TIdentity : notnull, IEquatable - where TContext : notnull, DbContext + where TIdentity : IEquatable + where TContext : DbContext { public SimpleEFRepository(TContext dbContext) : base(dbContext) { } diff --git a/src/Domain/LeanCode.DomainModels.Generators/TypedIdFormat.cs b/src/Domain/LeanCode.DomainModels.Generators/TypedIdFormat.cs index cb7d94489..ad04b0218 100644 --- a/src/Domain/LeanCode.DomainModels.Generators/TypedIdFormat.cs +++ b/src/Domain/LeanCode.DomainModels.Generators/TypedIdFormat.cs @@ -1,6 +1,6 @@ namespace LeanCode.DomainModels.Generators; -public enum TypedIdFormat : int +public enum TypedIdFormat { RawInt = 0, RawLong = 1, diff --git a/src/Domain/LeanCode.DomainModels/DataAccess/IRepository.cs b/src/Domain/LeanCode.DomainModels/DataAccess/IRepository.cs index 171128567..3bb51f27b 100644 --- a/src/Domain/LeanCode.DomainModels/DataAccess/IRepository.cs +++ b/src/Domain/LeanCode.DomainModels/DataAccess/IRepository.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using LeanCode.DomainModels.Model; namespace LeanCode.DomainModels.DataAccess; diff --git a/src/Domain/LeanCode.DomainModels/Ids/ITypedId.cs b/src/Domain/LeanCode.DomainModels/Ids/ITypedId.cs index 129b64886..c01ee4caf 100644 --- a/src/Domain/LeanCode.DomainModels/Ids/ITypedId.cs +++ b/src/Domain/LeanCode.DomainModels/Ids/ITypedId.cs @@ -16,15 +16,15 @@ public interface IPrefixedTypedId where TSelf : struct, IPrefixedTypedId { string Value { get; } - public static abstract int RawLength { get; } - public static abstract TSelf Parse(string v); - public static abstract bool IsValid(string? v); + static abstract int RawLength { get; } + static abstract TSelf Parse(string v); + static abstract bool IsValid(string? v); [EditorBrowsable(EditorBrowsableState.Never)] - public static abstract Expression> FromDatabase { get; } + static abstract Expression> FromDatabase { get; } [EditorBrowsable(EditorBrowsableState.Never)] - public static abstract Expression> DatabaseEquals { get; } + static abstract Expression> DatabaseEquals { get; } } [SuppressMessage("?", "CA1000", Justification = "Roslyn bug.")] @@ -39,11 +39,11 @@ public interface IRawTypedId where TSelf : struct, IRawTypedId { TBacking Value { get; } - public static abstract TSelf Parse(TBacking v); + static abstract TSelf Parse(TBacking v); [EditorBrowsable(EditorBrowsableState.Never)] - public static abstract Expression> FromDatabase { get; } + static abstract Expression> FromDatabase { get; } [EditorBrowsable(EditorBrowsableState.Never)] - public static abstract Expression> DatabaseEquals { get; } + static abstract Expression> DatabaseEquals { get; } } diff --git a/src/Domain/LeanCode.DomainModels/Ids/TypedIdAttribute.cs b/src/Domain/LeanCode.DomainModels/Ids/TypedIdAttribute.cs index bc153e46b..bc3f05ef1 100644 --- a/src/Domain/LeanCode.DomainModels/Ids/TypedIdAttribute.cs +++ b/src/Domain/LeanCode.DomainModels/Ids/TypedIdAttribute.cs @@ -6,7 +6,7 @@ namespace LeanCode.DomainModels.Ids; /// /// See documentation for more details. /// -public enum TypedIdFormat : int +public enum TypedIdFormat { /// /// Raw , without prefix. It's backing type is . diff --git a/src/Domain/LeanCode.DomainModels/Ids/TypedIdConverter.cs b/src/Domain/LeanCode.DomainModels/Ids/TypedIdConverter.cs index d02f2efe9..44e802339 100644 --- a/src/Domain/LeanCode.DomainModels/Ids/TypedIdConverter.cs +++ b/src/Domain/LeanCode.DomainModels/Ids/TypedIdConverter.cs @@ -122,6 +122,7 @@ public override void WriteAsPropertyName(Utf8JsonWriter writer, TId value, JsonS private bool TryGetGuidCore(ref Utf8JsonReader reader, out Guid value) { + // ReSharper disable once RedundantAssignment ReadOnlySpan span = stackalloc byte[0]; if (reader.HasValueSequence) diff --git a/src/Domain/LeanCode.DomainModels/Model/DomainEvents.cs b/src/Domain/LeanCode.DomainModels/Model/DomainEvents.cs index d8c06508e..f2c6bd6d8 100644 --- a/src/Domain/LeanCode.DomainModels/Model/DomainEvents.cs +++ b/src/Domain/LeanCode.DomainModels/Model/DomainEvents.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace LeanCode.DomainModels.Model; public static class DomainEvents @@ -9,6 +11,7 @@ public static void SetInterceptor(IDomainEventInterceptor interceptor) EventInterceptor = interceptor; } + [SuppressMessage("?", "CA1030", Justification = "Convention for `DomainEvents`.")] public static void Raise(TEvent domainEvent) where TEvent : class, IDomainEvent { diff --git a/src/Domain/LeanCode.DomainModels/Model/IDomainEvent.cs b/src/Domain/LeanCode.DomainModels/Model/IDomainEvent.cs index 66c926ca0..45a3bdd31 100644 --- a/src/Domain/LeanCode.DomainModels/Model/IDomainEvent.cs +++ b/src/Domain/LeanCode.DomainModels/Model/IDomainEvent.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.DomainModels.Model; public interface IDomainEvent diff --git a/src/Domain/LeanCode.DomainModels/Model/IOptimisticConcurrency.cs b/src/Domain/LeanCode.DomainModels/Model/IOptimisticConcurrency.cs index 92ee461c9..3c4bfc74b 100644 --- a/src/Domain/LeanCode.DomainModels/Model/IOptimisticConcurrency.cs +++ b/src/Domain/LeanCode.DomainModels/Model/IOptimisticConcurrency.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.DomainModels.Model; public interface IOptimisticConcurrency diff --git a/src/Domain/LeanCode.DomainModels/Model/Id.cs b/src/Domain/LeanCode.DomainModels/Model/Id.cs index 3744cc251..4ff3a5816 100644 --- a/src/Domain/LeanCode.DomainModels/Model/Id.cs +++ b/src/Domain/LeanCode.DomainModels/Model/Id.cs @@ -14,6 +14,7 @@ namespace LeanCode.DomainModels.Model; public readonly struct Id : IEquatable>, IComparable> where TEntity : class, IEntity> { + // ReSharper disable once UnassignedReadonlyField public static readonly Id Empty; public Guid Value { get; } @@ -63,6 +64,7 @@ public Id(Guid value) public readonly struct IId : IEquatable>, IComparable> where TEntity : class, IEntity> { + // ReSharper disable once UnassignedReadonlyField public static readonly IId Empty; public int Value { get; } diff --git a/src/Domain/LeanCode.DomainModels/Model/SId.cs b/src/Domain/LeanCode.DomainModels/Model/SId.cs index 5ba5fdf79..81be35b56 100644 --- a/src/Domain/LeanCode.DomainModels/Model/SId.cs +++ b/src/Domain/LeanCode.DomainModels/Model/SId.cs @@ -38,7 +38,7 @@ public SId(Guid v) public static SId New() => new(Guid.NewGuid()); [return: NotNullIfNotNull("id")] - public static SId? FromNullable(string? id) => id is string v ? From(v) : (SId?)null; + public static SId? FromNullable(string? id) => id is string v ? From(v) : null; public static bool TryParse(string? v, out SId id) { @@ -88,7 +88,7 @@ public static bool TryParseFromGuidOrSId([NotNullWhen(true)] string? v, out SId< { if (IsValid(v)) { - id = new SId(v!); + id = new SId(v); return true; } else if (Guid.TryParse(v, out var guid)) diff --git a/src/Domain/LeanCode.DomainModels/Model/TypedIdConverterAttribute.cs b/src/Domain/LeanCode.DomainModels/Model/TypedIdConverterAttribute.cs index 4ce30bb96..230e66112 100644 --- a/src/Domain/LeanCode.DomainModels/Model/TypedIdConverterAttribute.cs +++ b/src/Domain/LeanCode.DomainModels/Model/TypedIdConverterAttribute.cs @@ -77,6 +77,7 @@ public override void WriteAsPropertyName(Utf8JsonWriter writer, Id value, Jso private bool TryGetGuidCore(ref Utf8JsonReader reader, out Guid value) { + // ReSharper disable once RedundantAssignment ReadOnlySpan span = stackalloc byte[0]; if (reader.HasValueSequence) diff --git a/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs b/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs index 1ebbb8e49..3e5145963 100644 --- a/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs +++ b/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs @@ -41,12 +41,7 @@ namespace LeanCode.DomainModels.Ulids; [DebuggerDisplay("{ToString(),nq}")] [System.Text.Json.Serialization.JsonConverter(typeof(UlidJsonConverter))] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] -public readonly record struct Ulid - : IEquatable, - IComparable, - ISpanFormattable, - ISpanParsable, - IUtf8SpanFormattable +public readonly record struct Ulid : IComparable, ISpanFormattable, ISpanParsable, IUtf8SpanFormattable { public const int LengthInTextElements = 26; @@ -193,6 +188,7 @@ public readonly record struct Ulid new byte[] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 } ); + // ReSharper disable once UnassignedReadonlyField public static readonly Ulid Empty; // Core @@ -250,8 +246,7 @@ public readonly record struct Ulid [IgnoreDataMember] [SuppressMessage("?", "CA1819", Justification = "Fresh array is allocated per call")] public byte[] Random => - new byte[] - { + [ randomness0, randomness1, randomness2, @@ -262,7 +257,7 @@ public readonly record struct Ulid randomness7, randomness8, randomness9, - }; + ]; [IgnoreDataMember] public DateTimeOffset Time @@ -355,6 +350,7 @@ internal Ulid(ReadOnlySpan base32) // HACK: We assume the layout of a Guid is the following: // Int32, Int16, Int16, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8 // source: https://github.com/dotnet/runtime/blob/4f9ae42d861fcb4be2fcd5d3d55d5f227d30e723/src/libraries/System.Private.CoreLib/src/System/Guid.cs + [SuppressMessage("?", "CA1720", Justification = "Vendored code.")] public Ulid(Guid guid) { Span buf = stackalloc byte[16]; diff --git a/src/Domain/LeanCode.DomainModels/Ulids/UlidJsonConverter.cs b/src/Domain/LeanCode.DomainModels/Ulids/UlidJsonConverter.cs index 75a2a0580..dedba8c4c 100644 --- a/src/Domain/LeanCode.DomainModels/Ulids/UlidJsonConverter.cs +++ b/src/Domain/LeanCode.DomainModels/Ulids/UlidJsonConverter.cs @@ -26,65 +26,64 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE using System.Text.Json; using System.Text.Json.Serialization; -namespace LeanCode.DomainModels.Ulids +namespace LeanCode.DomainModels.Ulids; + +[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] +public class UlidJsonConverter : JsonConverter { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - public class UlidJsonConverter : JsonConverter + /// + /// Read a Ulid value represented by a string from JSON. + /// + public override Ulid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - /// - /// Read a Ulid value represented by a string from JSON. - /// - public override Ulid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + try { - try + if (reader.TokenType != JsonTokenType.String) { - if (reader.TokenType != JsonTokenType.String) - { - throw new JsonException("Expected string"); - } + throw new JsonException("Expected string"); + } - if (reader.HasValueSequence) + if (reader.HasValueSequence) + { + // Parse using ValueSequence + var seq = reader.ValueSequence; + if (seq.Length != 26) { - // Parse using ValueSequence - var seq = reader.ValueSequence; - if (seq.Length != 26) - { - throw new JsonException("Ulid invalid: length must be 26"); - } - - Span buf = stackalloc byte[26]; - seq.CopyTo(buf); - _ = Ulid.TryParse(buf, out var ulid); - return ulid; + throw new JsonException("Ulid invalid: length must be 26"); } - else - { - // Parse usign ValueSpan - var buf = reader.ValueSpan; - if (buf.Length != 26) - { - throw new JsonException("Ulid invalid: length must be 26"); - } - _ = Ulid.TryParse(buf, out var ulid); - return ulid; - } - } - catch (IndexOutOfRangeException e) - { - throw new JsonException("Ulid invalid: length must be 26", e); + Span buf = stackalloc byte[26]; + seq.CopyTo(buf); + _ = Ulid.TryParse(buf, out var ulid); + return ulid; } - catch (OverflowException e) + else { - throw new JsonException("Ulid invalid: invalid character", e); + // Parse usign ValueSpan + var buf = reader.ValueSpan; + if (buf.Length != 26) + { + throw new JsonException("Ulid invalid: length must be 26"); + } + + _ = Ulid.TryParse(buf, out var ulid); + return ulid; } } - - public override void Write(Utf8JsonWriter writer, Ulid value, JsonSerializerOptions options) + catch (IndexOutOfRangeException e) { - Span buf = stackalloc byte[Ulid.LengthInTextElements]; - value.TryFormat(buf, out _, "", null); - writer.WriteStringValue(buf); + throw new JsonException("Ulid invalid: length must be 26", e); } + catch (OverflowException e) + { + throw new JsonException("Ulid invalid: invalid character", e); + } + } + + public override void Write(Utf8JsonWriter writer, Ulid value, JsonSerializerOptions options) + { + Span buf = stackalloc byte[Ulid.LengthInTextElements]; + value.TryFormat(buf, out _, "", null); + writer.WriteStringValue(buf); } } diff --git a/src/Helpers/LeanCode.UserIdExtractors/IUserIdExtractor.cs b/src/Helpers/LeanCode.UserIdExtractors/IUserIdExtractor.cs index 398b403bb..074cd4214 100644 --- a/src/Helpers/LeanCode.UserIdExtractors/IUserIdExtractor.cs +++ b/src/Helpers/LeanCode.UserIdExtractors/IUserIdExtractor.cs @@ -3,7 +3,7 @@ namespace LeanCode.UserIdExtractors; public interface IUserIdExtractor : IUserIdExtractor - where TUserId : notnull, IEquatable + where TUserId : IEquatable { new TUserId Extract(ClaimsPrincipal user); string IUserIdExtractor.Extract(ClaimsPrincipal user) => Extract(user).ToString()!; diff --git a/src/Infrastructure/LeanCode.AuditLogs/AuditLogsMiddleware.cs b/src/Infrastructure/LeanCode.AuditLogs/AuditLogsMiddleware.cs index c618c8ec0..90bae630f 100644 --- a/src/Infrastructure/LeanCode.AuditLogs/AuditLogsMiddleware.cs +++ b/src/Infrastructure/LeanCode.AuditLogs/AuditLogsMiddleware.cs @@ -25,7 +25,7 @@ AuditLogsPublisher auditLogsPublisher await auditLogsPublisher.ExtractAndPublishAsync( dbContext, bus, - httpContext.Request.Path.ToString()!, + httpContext.Request.Path.ToString(), httpContext.RequestAborted ); } diff --git a/src/Infrastructure/LeanCode.AuditLogs/IAuditLogStorage.cs b/src/Infrastructure/LeanCode.AuditLogs/IAuditLogStorage.cs index 0c212748d..7cd43ddca 100644 --- a/src/Infrastructure/LeanCode.AuditLogs/IAuditLogStorage.cs +++ b/src/Infrastructure/LeanCode.AuditLogs/IAuditLogStorage.cs @@ -2,7 +2,7 @@ namespace LeanCode.AuditLogs; public interface IAuditLogStorage { - public Task StoreEventAsync(AuditLogMessage auditLogMessage, CancellationToken cancellationToken); + Task StoreEventAsync(AuditLogMessage auditLogMessage, CancellationToken cancellationToken); } public record AuditLogMessage( diff --git a/src/Infrastructure/LeanCode.AzureIdentity/IHostBuilderExtensions.cs b/src/Infrastructure/LeanCode.AzureIdentity/IHostBuilderExtensions.cs index 78a8fdbb0..6195edd5f 100644 --- a/src/Infrastructure/LeanCode.AzureIdentity/IHostBuilderExtensions.cs +++ b/src/Infrastructure/LeanCode.AzureIdentity/IHostBuilderExtensions.cs @@ -17,7 +17,7 @@ public static IHostBuilder AddAppConfigurationFromAzureKeyVault( ) { return builder.ConfigureAppConfiguration( - (context, builder) => + (_, builder) => { ConfigureAzureKeyVault(builder, credential, keyVaultKeyOverride, manager); } diff --git a/src/Infrastructure/LeanCode.ClientCredentialsHandler/ClientCredentialsHandler.cs b/src/Infrastructure/LeanCode.ClientCredentialsHandler/ClientCredentialsHandler.cs index 8ca43fd1b..d739d6570 100644 --- a/src/Infrastructure/LeanCode.ClientCredentialsHandler/ClientCredentialsHandler.cs +++ b/src/Infrastructure/LeanCode.ClientCredentialsHandler/ClientCredentialsHandler.cs @@ -1,9 +1,5 @@ -using System; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; -using System.Threading; -using System.Threading.Tasks; using IdentityModel.Client; namespace LeanCode.ClientCredentialsHandler; diff --git a/src/Infrastructure/LeanCode.ConfigCat/ConfigCatInitializer.cs b/src/Infrastructure/LeanCode.ConfigCat/ConfigCatInitializer.cs index 5fd6716bc..288afd3cd 100644 --- a/src/Infrastructure/LeanCode.ConfigCat/ConfigCatInitializer.cs +++ b/src/Infrastructure/LeanCode.ConfigCat/ConfigCatInitializer.cs @@ -12,17 +12,8 @@ public ConfigCatInitializer(IConfigCatClient configCatClient) this.configCatClient = configCatClient; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( - "?", - "CA1031:DoNotCatchGeneralExceptionTypes", - Justification = "We don't want any exceptions to be propagated." - )] protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - try - { - await configCatClient.GetAllKeysAsync(stoppingToken); - } - catch { } + await configCatClient.GetAllKeysAsync(stoppingToken); } } diff --git a/src/Infrastructure/LeanCode.ConfigCat/ConfigCatToMSLoggerAdapter.cs b/src/Infrastructure/LeanCode.ConfigCat/ConfigCatToMSLoggerAdapter.cs index b68fca496..17b45b498 100644 --- a/src/Infrastructure/LeanCode.ConfigCat/ConfigCatToMSLoggerAdapter.cs +++ b/src/Infrastructure/LeanCode.ConfigCat/ConfigCatToMSLoggerAdapter.cs @@ -78,7 +78,7 @@ public LogValues(ref FormattableLogMessage message) } } - public int Count => (Message.ArgNames?.Length ?? 0) + 1; + public int Count => Message.ArgNames.Length + 1; public IEnumerator> GetEnumerator() { diff --git a/src/Infrastructure/LeanCode.Dapper/DbContextExtensions.cs b/src/Infrastructure/LeanCode.Dapper/DbContextExtensions.cs index b135fe95e..0382a2e02 100644 --- a/src/Infrastructure/LeanCode.Dapper/DbContextExtensions.cs +++ b/src/Infrastructure/LeanCode.Dapper/DbContextExtensions.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; using System.Data; using System.Data.Common; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; using Dapper; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -13,11 +8,6 @@ namespace LeanCode.Dapper; -[SuppressMessage( - "StyleCop.CSharp.LayoutRules", - "SA1507:CodeMustNotContainMultipleBlankLinesInARow", - Justification = "Grouping of the methods improves readability." -)] public static class DbContextDapperExtensions { public static async Task WithConnectionAsync( diff --git a/src/Infrastructure/LeanCode.Dapper/RawQueryValidator.cs b/src/Infrastructure/LeanCode.Dapper/RawQueryValidator.cs index b4f02e35c..e8b646e6c 100644 --- a/src/Infrastructure/LeanCode.Dapper/RawQueryValidator.cs +++ b/src/Infrastructure/LeanCode.Dapper/RawQueryValidator.cs @@ -1,8 +1,5 @@ -using System; -using System.Linq; using System.Reflection; using System.Text.RegularExpressions; -using System.Threading.Tasks; using Microsoft.Data.SqlClient; namespace LeanCode.Dapper; diff --git a/src/Infrastructure/LeanCode.Dapper/RawSqlQueryAttribute.cs b/src/Infrastructure/LeanCode.Dapper/RawSqlQueryAttribute.cs index 49070d3d3..4a12b7c85 100644 --- a/src/Infrastructure/LeanCode.Dapper/RawSqlQueryAttribute.cs +++ b/src/Infrastructure/LeanCode.Dapper/RawSqlQueryAttribute.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.Dapper; [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)] diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs b/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs index 6918e8cff..ce6a6cfd3 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Globalization; using FirebaseAdmin.Messaging; using LeanCode.Localization.StringLocalizers; @@ -5,7 +6,7 @@ namespace LeanCode.Firebase.FCM; public class FCMClient - where TUserId : notnull, IEquatable + where TUserId : IEquatable { private readonly Serilog.ILogger logger = Serilog.Log.ForContext>(); @@ -103,6 +104,7 @@ public virtual async Task SendToUsersAsync( } } + [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public virtual async Task SendAllAsync( IEnumerable messages, bool dryRun, diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/FCMSendException.cs b/src/Infrastructure/LeanCode.Firebase.FCM/FCMSendException.cs index 1513e1111..1b643bdbc 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/FCMSendException.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/FCMSendException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.Firebase.FCM; public class FCMSendException : Exception diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/FCMServiceCollectionExtensions.cs b/src/Infrastructure/LeanCode.Firebase.FCM/FCMServiceCollectionExtensions.cs index a737532cd..925325641 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/FCMServiceCollectionExtensions.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/FCMServiceCollectionExtensions.cs @@ -12,7 +12,7 @@ public static IServiceCollection AddFCM( this IServiceCollection services, Action> config ) - where TUserId : notnull, IEquatable + where TUserId : IEquatable { services.TryAddSingleton(s => FirebaseMessaging.GetMessaging(s.GetRequiredService())); services.TryAddTransient>(); @@ -23,7 +23,7 @@ Action> config } public class FCMBuilder - where TUserId : notnull, IEquatable + where TUserId : IEquatable { public IServiceCollection Services { get; } diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/IPushNotificationTokenStore.cs b/src/Infrastructure/LeanCode.Firebase.FCM/IPushNotificationTokenStore.cs index 6ae664e0e..c5a749f03 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/IPushNotificationTokenStore.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/IPushNotificationTokenStore.cs @@ -1,9 +1,9 @@ namespace LeanCode.Firebase.FCM; public interface IPushNotificationTokenStore - where TUserId : notnull, IEquatable + where TUserId : IEquatable { - public const int MaxTokenBatchSize = 100; + const int MaxTokenBatchSize = 100; Task> GetTokensAsync(TUserId userId, CancellationToken cancellationToken = default); diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/ModelBuilderExtensions.cs b/src/Infrastructure/LeanCode.Firebase.FCM/ModelBuilderExtensions.cs index 128304cca..d1094c1b3 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/ModelBuilderExtensions.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/ModelBuilderExtensions.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace LeanCode.Firebase.FCM; @@ -9,12 +8,12 @@ public static void ConfigurePushNotificationTokenEntity( this ModelBuilder builder, bool setTokenColumnMaxLength ) - where TUserId : notnull, IEquatable + where TUserId : IEquatable { builder.Entity>(c => { c.HasKey(e => new { e.UserId, e.Token }); - c.HasIndex(e => e.Token).IsUnique(true); + c.HasIndex(e => e.Token).IsUnique(); c.Property(e => e.UserId).ValueGeneratedNever(); diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenEntity.cs b/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenEntity.cs index 1a9063257..d80a7f435 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenEntity.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenEntity.cs @@ -1,6 +1,4 @@ -using LeanCode.TimeProvider; - namespace LeanCode.Firebase.FCM; public sealed record class PushNotificationTokenEntity(TUserId UserId, string Token, DateTime DateCreated) - where TUserId : notnull, IEquatable; + where TUserId : IEquatable; diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs b/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs index d889c1b38..0cac76ebb 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs @@ -8,7 +8,7 @@ namespace LeanCode.Firebase.FCM; public sealed class PushNotificationTokenStore : IPushNotificationTokenStore where TDbContext : DbContext - where TUserId : notnull, IEquatable + where TUserId : IEquatable { private const int MaxTokenBatchSize = IPushNotificationTokenStore.MaxTokenBatchSize; private readonly Serilog.ILogger logger = Serilog.Log.ForContext>(); diff --git a/src/Infrastructure/LeanCode.Firebase.Firestore/FirestoreDatabase.cs b/src/Infrastructure/LeanCode.Firebase.Firestore/FirestoreDatabase.cs index b705a0e0e..259bcc275 100644 --- a/src/Infrastructure/LeanCode.Firebase.Firestore/FirestoreDatabase.cs +++ b/src/Infrastructure/LeanCode.Firebase.Firestore/FirestoreDatabase.cs @@ -1,6 +1,3 @@ -using System; -using System.Threading; -using System.Threading.Tasks; using FirebaseAdmin; using Google.Api.Gax; using Google.Cloud.Firestore; diff --git a/src/Infrastructure/LeanCode.ForceUpdate/LeanCode.ForceUpdate.Services/CQRS/VersionSupportQH.cs b/src/Infrastructure/LeanCode.ForceUpdate/LeanCode.ForceUpdate.Services/CQRS/VersionSupportQH.cs index f654e31f0..93e9fc890 100644 --- a/src/Infrastructure/LeanCode.ForceUpdate/LeanCode.ForceUpdate.Services/CQRS/VersionSupportQH.cs +++ b/src/Infrastructure/LeanCode.ForceUpdate/LeanCode.ForceUpdate.Services/CQRS/VersionSupportQH.cs @@ -26,7 +26,7 @@ VersionHandler versionHandler public async Task ExecuteAsync(HttpContext context, VersionSupport query) { - if (!Version.TryParse(query.Version, out var version) || !Enum.IsDefined(query.Platform)) + if (!Version.TryParse(query.Version, out var version) || !Enum.IsDefined(query.Platform)) { logger.Warning("Invalid input: {Version}, {Platform}", query.Version, query.Platform); return null; diff --git a/src/Infrastructure/LeanCode.Kratos/KratosWebHookHandlerBase.cs b/src/Infrastructure/LeanCode.Kratos/KratosWebHookHandlerBase.cs index 94ad73c72..9bedc468c 100644 --- a/src/Infrastructure/LeanCode.Kratos/KratosWebHookHandlerBase.cs +++ b/src/Infrastructure/LeanCode.Kratos/KratosWebHookHandlerBase.cs @@ -10,7 +10,7 @@ namespace LeanCode.Kratos; public sealed record class KratosWebHookHandlerConfig(string ApiKey); -public abstract partial class KratosWebHookHandlerBase +public abstract class KratosWebHookHandlerBase { private readonly Serilog.ILogger logger = Serilog.Log.ForContext(); diff --git a/src/Infrastructure/LeanCode.Localization/LocalizationConfiguration.cs b/src/Infrastructure/LeanCode.Localization/LocalizationConfiguration.cs index 36d52ab06..5bd5c8d57 100644 --- a/src/Infrastructure/LeanCode.Localization/LocalizationConfiguration.cs +++ b/src/Infrastructure/LeanCode.Localization/LocalizationConfiguration.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.Localization; public sealed class LocalizationConfiguration diff --git a/src/Infrastructure/LeanCode.Localization/StringLocalizers/ResourceManagerStringLocalizer.cs b/src/Infrastructure/LeanCode.Localization/StringLocalizers/ResourceManagerStringLocalizer.cs index fb4c92f4f..d7b78c4f8 100644 --- a/src/Infrastructure/LeanCode.Localization/StringLocalizers/ResourceManagerStringLocalizer.cs +++ b/src/Infrastructure/LeanCode.Localization/StringLocalizers/ResourceManagerStringLocalizer.cs @@ -1,4 +1,3 @@ -using System; using System.Globalization; using System.Resources; using static System.Globalization.CultureInfo; diff --git a/src/Infrastructure/LeanCode.Logging/BaseSanitizer.cs b/src/Infrastructure/LeanCode.Logging/BaseSanitizer.cs index 0c7ca8f57..bf42ebf8e 100644 --- a/src/Infrastructure/LeanCode.Logging/BaseSanitizer.cs +++ b/src/Infrastructure/LeanCode.Logging/BaseSanitizer.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics.CodeAnalysis; using Serilog.Core; using Serilog.Events; diff --git a/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs b/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs index 6bc4e0131..07c221357 100644 --- a/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs +++ b/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs @@ -69,7 +69,7 @@ public static IHostBuilder ConfigureDefaultLogging( if (configuration.GetValue(SeqEndpointKey) is string seqEndpoint) { - loggerConfiguration.WriteTo.Seq(seqEndpoint); + loggerConfiguration.WriteTo.Seq(seqEndpoint, formatProvider: CultureInfo.InvariantCulture); } if (context.HostingEnvironment.IsDevelopment()) diff --git a/src/Infrastructure/LeanCode.Logging/SerilogExtensions.cs b/src/Infrastructure/LeanCode.Logging/SerilogExtensions.cs index dbdbb2fb3..40f6686a6 100644 --- a/src/Infrastructure/LeanCode.Logging/SerilogExtensions.cs +++ b/src/Infrastructure/LeanCode.Logging/SerilogExtensions.cs @@ -29,6 +29,6 @@ private static List SelectTypes(IEnumerable searchAssemb .Where(t => typeof(TType).IsAssignableFrom(t) && t.IsPublic && t.GetConstructor(Type.EmptyTypes) != null) .Select(Activator.CreateInstance) .Cast() - .ToList()!; + .ToList(); } } diff --git a/src/Infrastructure/LeanCode.Logging/UserIdLogsCorrelationMiddleware.cs b/src/Infrastructure/LeanCode.Logging/UserIdLogsCorrelationMiddleware.cs index a924b26bd..4cb3fb869 100644 --- a/src/Infrastructure/LeanCode.Logging/UserIdLogsCorrelationMiddleware.cs +++ b/src/Infrastructure/LeanCode.Logging/UserIdLogsCorrelationMiddleware.cs @@ -1,4 +1,3 @@ -using System; using System.Security.Claims; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -25,7 +24,7 @@ public static IApplicationBuilder UseUserIdLogsCorrelation( private static IDisposable? UserId(HttpContext httpCtx, string? userIdClaim) { - if (httpCtx?.User.Identity?.IsAuthenticated ?? false) + if (httpCtx.User.Identity?.IsAuthenticated ?? false) { var userId = httpCtx.User.FindFirstValue(userIdClaim ?? "sub"); diff --git a/src/Infrastructure/LeanCode.Mixpanel/IMixpanelEvent.cs b/src/Infrastructure/LeanCode.Mixpanel/IMixpanelEvent.cs index 985115466..998411b81 100644 --- a/src/Infrastructure/LeanCode.Mixpanel/IMixpanelEvent.cs +++ b/src/Infrastructure/LeanCode.Mixpanel/IMixpanelEvent.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace LeanCode.Mixpanel; public interface IMixpanelEvent diff --git a/src/Infrastructure/LeanCode.Mixpanel/MixpanelAnalytics.cs b/src/Infrastructure/LeanCode.Mixpanel/MixpanelAnalytics.cs index 5c6abd860..97298a4ca 100644 --- a/src/Infrastructure/LeanCode.Mixpanel/MixpanelAnalytics.cs +++ b/src/Infrastructure/LeanCode.Mixpanel/MixpanelAnalytics.cs @@ -1,19 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; namespace LeanCode.Mixpanel; -[SuppressMessage( - "StyleCop.CSharp.LayoutRules", - "SA1507:CodeMustNotContainMultipleBlankLinesInARow", - Justification = "Reviewed." -)] public class MixpanelAnalytics { private readonly Serilog.ILogger logger = Serilog.Log.ForContext(); @@ -180,7 +169,7 @@ CancellationToken cancellationToken var url = $"{uri}/?data={dataString}&verbose={(configuration.VerboseErrors ? "1" : "0")}&api_key={configuration.ApiKey}"; - using var rawResponse = await client.GetAsync(url, cancellationToken); + using var rawResponse = await client.GetAsync(new Uri(url), cancellationToken); var content = await rawResponse.Content.ReadAsStringAsync(cancellationToken); if (content == "1") { @@ -213,7 +202,8 @@ CancellationToken cancellationToken "Error sending mixpanel request {RequestName} for user {UserId} with data: {@EventData}. Mixpanel returned an error {Error}", requestName, userId, - data + data, + response?.Error ); } } diff --git a/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs b/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs index da8417b7f..4f1213747 100644 --- a/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs +++ b/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics; using LeanCode.OpenTelemetry.Datadog; using Serilog; diff --git a/src/Infrastructure/LeanCode.OpenTelemetry/IdentityTraceAttributesMiddleware.cs b/src/Infrastructure/LeanCode.OpenTelemetry/IdentityTraceAttributesMiddleware.cs index 2f550af93..cca92da3f 100644 --- a/src/Infrastructure/LeanCode.OpenTelemetry/IdentityTraceAttributesMiddleware.cs +++ b/src/Infrastructure/LeanCode.OpenTelemetry/IdentityTraceAttributesMiddleware.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Security.Claims; using Microsoft.AspNetCore.Builder; @@ -6,6 +7,7 @@ namespace LeanCode.OpenTelemetry; public static class IdentityTraceAttributesMiddleware { + [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public static IApplicationBuilder UseIdentityTraceAttributes( this IApplicationBuilder builder, string userIdClaim = "sub", diff --git a/src/Infrastructure/LeanCode.OpenTelemetry/LeanCodeMetrics.cs b/src/Infrastructure/LeanCode.OpenTelemetry/LeanCodeMetrics.cs index 13b0dc8dd..1ead28b4e 100644 --- a/src/Infrastructure/LeanCode.OpenTelemetry/LeanCodeMetrics.cs +++ b/src/Infrastructure/LeanCode.OpenTelemetry/LeanCodeMetrics.cs @@ -1,5 +1,3 @@ -using System.Diagnostics.Metrics; - namespace LeanCode.OpenTelemetry; public static class LeanCodeMetrics diff --git a/src/Infrastructure/LeanCode.PeriodicService/IPeriodicAction.cs b/src/Infrastructure/LeanCode.PeriodicService/IPeriodicAction.cs index 03f327ec7..43bbf57e0 100644 --- a/src/Infrastructure/LeanCode.PeriodicService/IPeriodicAction.cs +++ b/src/Infrastructure/LeanCode.PeriodicService/IPeriodicAction.cs @@ -1,18 +1,14 @@ -using System.Threading; -using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; using Cronos; namespace LeanCode.PeriodicService; public interface IPeriodicAction { + [SuppressMessage("?", "CA1716", Justification = "Convention for `PeriodicAction`.")] CronExpression When { get; } bool SkipFirstExecution { get; } - [System.Diagnostics.CodeAnalysis.SuppressMessage( - "?", - "LNCD0006", - Justification = "Convention for `PeriodicAction`." - )] + [SuppressMessage("?", "LNCD0006", Justification = "Convention for `PeriodicAction`.")] Task ExecuteAsync(CancellationToken stoppingToken); } diff --git a/src/Infrastructure/LeanCode.PeriodicService/PeriodicHostedService.cs b/src/Infrastructure/LeanCode.PeriodicService/PeriodicHostedService.cs index 5a15e2333..a191bc608 100644 --- a/src/Infrastructure/LeanCode.PeriodicService/PeriodicHostedService.cs +++ b/src/Infrastructure/LeanCode.PeriodicService/PeriodicHostedService.cs @@ -62,7 +62,7 @@ private static TimeSpan CalculateDelay(IPeriodicAction action) { var now = TimeProvider.Time.UtcNow; var next = - action.When.GetNextOccurrence(now, false) + action.When.GetNextOccurrence(now) ?? throw new InvalidOperationException("Cannot get next occurrence of the task."); return next - now; } diff --git a/src/Infrastructure/LeanCode.SendGrid/EnumerableAsyncExtensions.cs b/src/Infrastructure/LeanCode.SendGrid/EnumerableAsyncExtensions.cs index 77c494889..9ce71ce92 100644 --- a/src/Infrastructure/LeanCode.SendGrid/EnumerableAsyncExtensions.cs +++ b/src/Infrastructure/LeanCode.SendGrid/EnumerableAsyncExtensions.cs @@ -1,6 +1,3 @@ -using System.Collections.Generic; -using System.Threading.Tasks; - namespace System.Linq; internal static class EnumerableAsyncExtensions diff --git a/src/Infrastructure/LeanCode.SendGrid/SendGridException.cs b/src/Infrastructure/LeanCode.SendGrid/SendGridException.cs index 50ff14eac..a36a20cf3 100644 --- a/src/Infrastructure/LeanCode.SendGrid/SendGridException.cs +++ b/src/Infrastructure/LeanCode.SendGrid/SendGridException.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; using System.Net; namespace LeanCode.SendGrid; diff --git a/src/Infrastructure/LeanCode.SendGrid/SendGridLocalizedRazorMessage.cs b/src/Infrastructure/LeanCode.SendGrid/SendGridLocalizedRazorMessage.cs index dafdf803d..ecc930273 100644 --- a/src/Infrastructure/LeanCode.SendGrid/SendGridLocalizedRazorMessage.cs +++ b/src/Infrastructure/LeanCode.SendGrid/SendGridLocalizedRazorMessage.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; @@ -36,7 +35,7 @@ public void SetGlobalSubject(string subjectKey, object[]? subjectFormatArgs) internal override IEnumerable GetTemplateNames(string templateBaseName) { - for (var c = Culture; c != CultureInfo.InvariantCulture; c = c.Parent) + for (var c = Culture; !Equals(c, CultureInfo.InvariantCulture); c = c.Parent) { yield return $"{templateBaseName}.{c.Name}"; } diff --git a/src/Infrastructure/LeanCode.SendGrid/SendGridRazorClient.cs b/src/Infrastructure/LeanCode.SendGrid/SendGridRazorClient.cs index 2d1f4d252..696221c7d 100644 --- a/src/Infrastructure/LeanCode.SendGrid/SendGridRazorClient.cs +++ b/src/Infrastructure/LeanCode.SendGrid/SendGridRazorClient.cs @@ -1,9 +1,6 @@ using System.Globalization; -using System.Linq; using System.Net; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; using LeanCode.Localization.StringLocalizers; using LeanCode.ViewRenderer; using SendGrid; diff --git a/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessage.cs b/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessage.cs index 52324626a..7062303eb 100644 --- a/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessage.cs +++ b/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessage.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Text.Json.Serialization; using SendGrid.Helpers.Mail; diff --git a/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessageExtensions.cs b/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessageExtensions.cs index 45bf80c43..622af6c1c 100644 --- a/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessageExtensions.cs +++ b/src/Infrastructure/LeanCode.SendGrid/SendGridRazorMessageExtensions.cs @@ -1,7 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; using SendGrid.Helpers.Mail; namespace LeanCode.SendGrid; @@ -24,7 +20,7 @@ public static SendGridRazorMessage WithSender(this SendGridRazorMessage message, public static SendGridRazorMessage WithSender(this SendGridRazorMessage message, string email) { - message.SetFrom(email, null); + message.SetFrom(email); return message; } @@ -45,7 +41,7 @@ public static SendGridRazorMessage WithRecipient(this SendGridRazorMessage messa public static SendGridRazorMessage WithRecipient(this SendGridRazorMessage message, string email) { - message.AddTo(email, null); + message.AddTo(email); return message; } @@ -83,7 +79,7 @@ public static SendGridRazorMessage WithCarbonCopyRecipient( public static SendGridRazorMessage WithCarbonCopyRecipient(this SendGridRazorMessage message, string email) { - message.AddCc(email, null); + message.AddCc(email); return message; } @@ -121,7 +117,7 @@ public static SendGridRazorMessage WithBlindCarbonCopyRecipient( public static SendGridRazorMessage WithBlindCarbonCopyRecipient(this SendGridRazorMessage message, string email) { - message.AddBcc(email, null); + message.AddBcc(email); return message; } diff --git a/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateOnlyConverter.cs b/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateOnlyConverter.cs index ee63accc3..496c45dc5 100644 --- a/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateOnlyConverter.cs +++ b/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateOnlyConverter.cs @@ -43,7 +43,7 @@ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, Jso public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) { Span buffer = stackalloc char[MaxDateOnlyBufferSize]; - var success = value.TryFormat(buffer, out var written, "o", CultureInfo.InvariantCulture); + value.TryFormat(buffer, out var written, "o", CultureInfo.InvariantCulture); writer.WriteStringValue(JsonEncodedText.Encode(buffer[..written], JavaScriptEncoder.UnsafeRelaxedJsonEscaping)); } } diff --git a/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateTimeOffsetConverter.cs b/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateTimeOffsetConverter.cs index 1e91da8bd..03f96ffa2 100644 --- a/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateTimeOffsetConverter.cs +++ b/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxDateTimeOffsetConverter.cs @@ -44,7 +44,7 @@ public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConver public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) { Span buffer = stackalloc char[MaxDateTimeOffsetBufferSize]; - var success = value.TryFormat(buffer, out var written, format, CultureInfo.InvariantCulture); + value.TryFormat(buffer, out var written, format, CultureInfo.InvariantCulture); writer.WriteStringValue(JsonEncodedText.Encode(buffer[..written], JavaScriptEncoder.UnsafeRelaxedJsonEscaping)); } } diff --git a/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxTimeOnlyConverter.cs b/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxTimeOnlyConverter.cs index 791606bcb..8b936a419 100644 --- a/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxTimeOnlyConverter.cs +++ b/src/Infrastructure/LeanCode.Serialization/JsonConverters/JsonLaxTimeOnlyConverter.cs @@ -44,7 +44,7 @@ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, Jso public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) { Span buffer = stackalloc char[MaxTimeOnlyBufferSize]; - var success = value.TryFormat(buffer, out var written, format, CultureInfo.InvariantCulture); + value.TryFormat(buffer, out var written, format, CultureInfo.InvariantCulture); writer.WriteStringValue(JsonEncodedText.Encode(buffer[..written], JavaScriptEncoder.UnsafeRelaxedJsonEscaping)); } } diff --git a/src/Infrastructure/LeanCode.SmsSender/Exceptions/Exceptions.cs b/src/Infrastructure/LeanCode.SmsSender/Exceptions/Exceptions.cs index e641d3314..25a205b25 100644 --- a/src/Infrastructure/LeanCode.SmsSender/Exceptions/Exceptions.cs +++ b/src/Infrastructure/LeanCode.SmsSender/Exceptions/Exceptions.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.SmsSender.Exceptions; public abstract class ResponseException : Exception diff --git a/src/Infrastructure/LeanCode.SmsSender/ISmsSender.cs b/src/Infrastructure/LeanCode.SmsSender/ISmsSender.cs index 1b0d6a533..36ec59abe 100644 --- a/src/Infrastructure/LeanCode.SmsSender/ISmsSender.cs +++ b/src/Infrastructure/LeanCode.SmsSender/ISmsSender.cs @@ -1,6 +1,3 @@ -using System.Threading; -using System.Threading.Tasks; - namespace LeanCode.SmsSender; public interface ISmsSender diff --git a/src/Infrastructure/LeanCode.SmsSender/SmsApiClient.cs b/src/Infrastructure/LeanCode.SmsSender/SmsApiClient.cs index 617a58610..e35dc60b0 100644 --- a/src/Infrastructure/LeanCode.SmsSender/SmsApiClient.cs +++ b/src/Infrastructure/LeanCode.SmsSender/SmsApiClient.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; using System.Collections.Immutable; -using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.Serialization; using System.Text; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; using LeanCode.SmsSender.Exceptions; namespace LeanCode.SmsSender; @@ -89,7 +84,7 @@ public async Task SendAsync(string message, string phoneNumber, CancellationToke parameters["fast"] = "1"; } - using var requestContent = new FormUrlEncodedContent(parameters!); + using var requestContent = new FormUrlEncodedContent(parameters); using var response = await client.PostAsync("sms.do", requestContent, cancellationToken); await using var responseContent = await response.Content.ReadAsStreamAsync(cancellationToken); diff --git a/src/Infrastructure/LeanCode.SmsSender/SmsApiConfiguration.cs b/src/Infrastructure/LeanCode.SmsSender/SmsApiConfiguration.cs index c0e8e5535..771a817ac 100644 --- a/src/Infrastructure/LeanCode.SmsSender/SmsApiConfiguration.cs +++ b/src/Infrastructure/LeanCode.SmsSender/SmsApiConfiguration.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.SmsSender; /// diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/CompiledViewsCache.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/CompiledViewsCache.cs index 17b348b43..fab500049 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/CompiledViewsCache.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/CompiledViewsCache.cs @@ -1,6 +1,4 @@ -using System; using System.Collections.Concurrent; -using System.Threading.Tasks; namespace LeanCode.ViewRenderer.Razor; diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutDirectivePass.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutDirectivePass.cs index 8cb96b58d..6240b50d4 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutDirectivePass.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutDirectivePass.cs @@ -1,4 +1,3 @@ -using System.Linq; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Intermediate; diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs index 95dcc7877..24cd823af 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.AspNetCore.Razor.Language.CodeGeneration; using Microsoft.AspNetCore.Razor.Language.Intermediate; diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRenderer.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRenderer.cs index 63b1d7c1a..c7ffe1005 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRenderer.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRenderer.cs @@ -1,8 +1,4 @@ -using System; -using System.IO; using System.Text; -using System.Threading; -using System.Threading.Tasks; using LeanCode.ViewRenderer.Razor.ViewBase; namespace LeanCode.ViewRenderer.Razor; @@ -27,7 +23,7 @@ public async Task RenderToStreamAsync( { logger.Debug("Rendering view {ViewName}", viewName); - await RenderAsync(outputStream, viewName, model, null, 0); + await RenderAsync(outputStream, viewName, model, null); logger.Information("View {ViewName} rendered", viewName); } @@ -46,13 +42,7 @@ public async Task RenderToStringAsync( } } - private async Task RenderAsync( - Stream outputStream, - string viewName, - object model, - BaseView? childView, - int childSize - ) + private async Task RenderAsync(Stream outputStream, string viewName, object model, BaseView? childView) { var compiledView = await cache.GetOrCompileAsync(viewName); @@ -72,7 +62,7 @@ int childSize { logger.Debug("View {ViewName} has a layout {Layout}, delegating work", viewName, compiledView.Layout); - await RenderAsync(outputStream, compiledView.Layout, model, view, childSize + compiledView.ProjectedSize); + await RenderAsync(outputStream, compiledView.Layout, model, view); } } } diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRendererOptions.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRendererOptions.cs index a75a93928..8f49795d2 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRendererOptions.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/RazorViewRendererOptions.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace LeanCode.ViewRenderer.Razor; public class RazorViewRendererOptions diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/AttributeValue.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/AttributeValue.cs index 66e8dbf03..4fc186c96 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/AttributeValue.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/AttributeValue.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.ViewRenderer.Razor.ViewBase; public class AttributeValue diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/BaseView.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/BaseView.cs index 4dbc1945b..580d420b5 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/BaseView.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/BaseView.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.IO; -using System.Runtime.CompilerServices; using System.Text; using System.Text.Encodings.Web; -using System.Threading.Tasks; namespace LeanCode.ViewRenderer.Razor.ViewBase; @@ -86,16 +81,14 @@ protected void WriteTo(TextWriter writer, string value) => protected void WriteTo(TextWriter writer, object value) { - if (value != null) + if (value is HelperResult helperResult) { - if (value is HelperResult helperResult) - { - helperResult.WriteTo(writer); - } - else - { - WriteTo(writer, Stringify(value)); - } + helperResult.WriteTo(writer); + } + // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract + else if (value is not null) + { + WriteTo(writer, Stringify(value)); } } @@ -110,7 +103,7 @@ protected void WriteLiteralTo(TextWriter writer, string? value) { if (!string.IsNullOrEmpty(value)) { - writer?.Write(value); + writer.Write(value); } } diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/HelperResult.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/HelperResult.cs index fe95a1792..7d86b2262 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/HelperResult.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewBase/HelperResult.cs @@ -1,6 +1,3 @@ -using System; -using System.IO; - namespace LeanCode.ViewRenderer.Razor.ViewBase; public class HelperResult diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs index a8b3488a8..9041e61dc 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Text.Encodings.Web; -using System.Threading.Tasks; using LeanCode.ViewRenderer.Razor.ViewBase; using Microsoft.AspNetCore.Razor.Hosting; using Microsoft.AspNetCore.Razor.Language; @@ -194,7 +189,7 @@ private static RazorProjectEngine PrepareEngine(ViewLocator locator) { builder.SetBaseType(typeof(BaseView).FullName); builder.ConfigureClass( - (doc, @class) => + (_, @class) => { @class.ClassName = "View_" + Guid.NewGuid().ToString("N"); @class.Modifiers.Clear(); diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewLocator.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewLocator.cs index 26a0dae58..a9da0789f 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewLocator.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewLocator.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; using Microsoft.AspNetCore.Razor.Language; namespace LeanCode.ViewRenderer.Razor; diff --git a/src/Infrastructure/LeanCode.ViewRenderer/CompilationFailedException.cs b/src/Infrastructure/LeanCode.ViewRenderer/CompilationFailedException.cs index c77b77d52..9082551e2 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer/CompilationFailedException.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer/CompilationFailedException.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using System.Collections.Immutable; namespace LeanCode.ViewRenderer; diff --git a/src/Infrastructure/LeanCode.ViewRenderer/IViewRenderer.cs b/src/Infrastructure/LeanCode.ViewRenderer/IViewRenderer.cs index 9ef0f2950..a7e235677 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer/IViewRenderer.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer/IViewRenderer.cs @@ -1,7 +1,3 @@ -using System.IO; -using System.Threading; -using System.Threading.Tasks; - namespace LeanCode.ViewRenderer; public interface IViewRenderer diff --git a/src/Infrastructure/LeanCode.ViewRenderer/ViewNotFoundException.cs b/src/Infrastructure/LeanCode.ViewRenderer/ViewNotFoundException.cs index 8e80b3881..4080d31b3 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer/ViewNotFoundException.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer/ViewNotFoundException.cs @@ -1,5 +1,3 @@ -using System; - namespace LeanCode.ViewRenderer; public class ViewNotFoundException : Exception diff --git a/src/Testing/LeanCode.DomainModels.EventsExecution.TestHelpers/EventsInterceptor.cs b/src/Testing/LeanCode.DomainModels.EventsExecution.TestHelpers/EventsInterceptor.cs index c5aa197e3..6ffd16a34 100644 --- a/src/Testing/LeanCode.DomainModels.EventsExecution.TestHelpers/EventsInterceptor.cs +++ b/src/Testing/LeanCode.DomainModels.EventsExecution.TestHelpers/EventsInterceptor.cs @@ -1,7 +1,5 @@ -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; +using System.Diagnostics.CodeAnalysis; using LeanCode.DomainModels.Model; namespace LeanCode.UnitTests.TestHelpers; @@ -26,6 +24,7 @@ public static void Configure() } } + [SuppressMessage("?", "CA1720", Justification = "Convention for EventsInterceptor.")] public static SingleStorage Single() where TEvent : class, IDomainEvent { diff --git a/src/Testing/LeanCode.IntegrationTestHelpers/DbContextInitializer.cs b/src/Testing/LeanCode.IntegrationTestHelpers/DbContextInitializer.cs index ba859328b..b6a7f5952 100644 --- a/src/Testing/LeanCode.IntegrationTestHelpers/DbContextInitializer.cs +++ b/src/Testing/LeanCode.IntegrationTestHelpers/DbContextInitializer.cs @@ -37,12 +37,12 @@ await CreatePolicy.ExecuteAsync( if (connection.State == System.Data.ConnectionState.Closed) { await connection.OpenAsync(token); - await connection.ReloadTypesAsync(); + await connection.ReloadTypesAsync(token); await connection.CloseAsync(); } else { - await connection.ReloadTypesAsync(); + await connection.ReloadTypesAsync(token); } } }, diff --git a/src/Testing/LeanCode.IntegrationTestHelpers/TestConnectionString.cs b/src/Testing/LeanCode.IntegrationTestHelpers/TestConnectionString.cs index f058391c3..c77a4becc 100644 --- a/src/Testing/LeanCode.IntegrationTestHelpers/TestConnectionString.cs +++ b/src/Testing/LeanCode.IntegrationTestHelpers/TestConnectionString.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Configuration; -using Serilog.Events; namespace LeanCode.IntegrationTestHelpers; diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandsQueriesAndOperationsHaveAuthorizers.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandsQueriesAndOperationsHaveAuthorizers.cs index a4ff4f667..a1ab1c353 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandsQueriesAndOperationsHaveAuthorizers.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandsQueriesAndOperationsHaveAuthorizers.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs index 734f551e1..1058f7f07 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs @@ -1,4 +1,3 @@ -using System.Linq; using Microsoft.CodeAnalysis; namespace LeanCode.CodeAnalysis.Analyzers; diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs index 6c05bc279..4d78359a9 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs @@ -1,6 +1,5 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; -using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddAuthorizationAttributeCodeAction.cs b/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddAuthorizationAttributeCodeAction.cs index 34c17d261..19af1d041 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddAuthorizationAttributeCodeAction.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddAuthorizationAttributeCodeAction.cs @@ -1,9 +1,5 @@ -using System; -using System.Threading; -using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Text; diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs b/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs index a3a2719d1..a0e919ae6 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs @@ -1,14 +1,9 @@ -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using LeanCode.CodeAnalysis.Analyzers; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; -using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCQRSHandlerNamespaceCodeAction.cs b/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCQRSHandlerNamespaceCodeAction.cs index 4cf6f8024..fc8825048 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCQRSHandlerNamespaceCodeAction.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCQRSHandlerNamespaceCodeAction.cs @@ -82,46 +82,49 @@ private static async Task MoveDocumentToContractMatchingFolderIfNecessaryAsync( CancellationToken cancellationToken ) { - if (document != null && document.FilePath != null) + if (document is not null && document.FilePath is not null) { var projectName = document.Project.AssemblyName; var fileName = Path.GetFileName(document.FilePath); var currentDirectory = Path.GetDirectoryName(document.FilePath); - var currDirectoryIdx = currentDirectory.LastIndexOf(projectName, StringComparison.InvariantCulture); - var expectedNamespaceIdx = expectedNamespace.StartsWith(projectName, StringComparison.InvariantCulture) - ? 0 - : -1; - - if (currDirectoryIdx != -1 && expectedNamespaceIdx != -1) + if (currentDirectory is not null) { - currDirectoryIdx = currDirectoryIdx + projectName.Length; - expectedNamespaceIdx = expectedNamespaceIdx + projectName.Length; + var currDirectoryIdx = currentDirectory.LastIndexOf(projectName, StringComparison.InvariantCulture); + var expectedNamespaceIdx = expectedNamespace.StartsWith(projectName, StringComparison.InvariantCulture) + ? 0 + : -1; - // Path prefix with project name. - var pathPrefix = currentDirectory[..currDirectoryIdx]; - // Namespace without project name prefix. - var namespaceSuffix = expectedNamespace[expectedNamespaceIdx..]; + if (currDirectoryIdx != -1 && expectedNamespaceIdx != -1) + { + currDirectoryIdx += projectName.Length; + expectedNamespaceIdx += projectName.Length; - // `Path.Combine` will return the second argument if it begins with a separation character. - var pathSuffix = namespaceSuffix - .Replace('.', Path.DirectorySeparatorChar) - .Trim(Path.DirectorySeparatorChar); + // Path prefix with project name. + var pathPrefix = currentDirectory[..currDirectoryIdx]; + // Namespace without project name prefix. + var namespaceSuffix = expectedNamespace[expectedNamespaceIdx..]; - var newPath = Path.Combine(pathPrefix, pathSuffix, fileName); + // `Path.Combine` will return the second argument if it begins with a separation character. + var pathSuffix = namespaceSuffix + .Replace('.', Path.DirectorySeparatorChar) + .Trim(Path.DirectorySeparatorChar); - if (newPath != document.FilePath) - { - var directoryPath = Path.GetDirectoryName(newPath); + var newPath = Path.Combine(pathPrefix, pathSuffix, fileName); - if (!Directory.Exists(directoryPath)) + if (newPath != document.FilePath) { - Directory.CreateDirectory(directoryPath); - } + var directoryPath = Path.GetDirectoryName(newPath); + + if (directoryPath is not null) + { + Directory.CreateDirectory(directoryPath); + } - var updatedText = (await document.GetTextAsync(cancellationToken)).ToString(); - await File.WriteAllTextAsync(newPath, updatedText, cancellationToken); - File.Delete(document.FilePath); + var updatedText = (await document.GetTextAsync(cancellationToken)).ToString(); + await File.WriteAllTextAsync(newPath, updatedText, cancellationToken); + File.Delete(document.FilePath); + } } } } diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs b/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs index f4273332e..570ac74da 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs @@ -56,7 +56,7 @@ token.Parent is ParameterSyntax parameter // the old nodes are still available, we need to replace them all at once. var newRoot = root.ReplaceNodes( references, - (oldNode, newNode) => + (oldNode, _) => { return oldNode switch { diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeActions/Helpers.cs b/src/Tools/LeanCode.CodeAnalysis/CodeActions/Helpers.cs index b48423127..64e29e3ce 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeActions/Helpers.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeActions/Helpers.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; @@ -22,7 +20,8 @@ public static void InsertNamespaceDirective(DocumentEditor editor, SyntaxNode ro var stmt = BuildUsing(namespaceName); var namespaces = root.DescendantNodes() .OfType() - .OrderBy(n => n.Name.ToString(), NamespaceComparer) + .Where(n => n.Name != null) // Skip usings without names for comparison e.g. using x = (X.Y.Z, A.B.C) + .OrderBy(n => n.Name!.ToString(), NamespaceComparer) .ToArray(); if (namespaces.Length == 0) @@ -32,7 +31,7 @@ public static void InsertNamespaceDirective(DocumentEditor editor, SyntaxNode ro } var toInsert = namespaces - .SkipWhile(ns => NamespaceComparer.Compare(ns.Name.ToString(), namespaceName) < 0) + .SkipWhile(ns => NamespaceComparer.Compare(ns.Name!.ToString(), namespaceName) < 0) .FirstOrDefault(); if (toInsert != null) diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddAuthorizationAttributeCodeFixProvider.cs b/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddAuthorizationAttributeCodeFixProvider.cs index ce429e0fc..3a42e2f46 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddAuthorizationAttributeCodeFixProvider.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddAuthorizationAttributeCodeFixProvider.cs @@ -1,9 +1,5 @@ -using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; -using System.Linq; -using System.Threading.Tasks; -using LeanCode.CodeAnalysis.Analyzers; using LeanCode.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddCommandValidatorCodeFixProvider.cs b/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddCommandValidatorCodeFixProvider.cs index 074921f88..1eddd45a3 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddCommandValidatorCodeFixProvider.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeFixProviders/AddCommandValidatorCodeFixProvider.cs @@ -1,6 +1,5 @@ using System.Collections.Immutable; using System.Composition; -using System.Threading.Tasks; using LeanCode.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; diff --git a/src/Tools/LeanCode.CodeAnalysis/LeanCode.CodeAnalysis.csproj b/src/Tools/LeanCode.CodeAnalysis/LeanCode.CodeAnalysis.csproj index 3f4012e2b..1cbaa6ce9 100644 --- a/src/Tools/LeanCode.CodeAnalysis/LeanCode.CodeAnalysis.csproj +++ b/src/Tools/LeanCode.CodeAnalysis/LeanCode.CodeAnalysis.csproj @@ -1,7 +1,6 @@ - 1 false true true diff --git a/test-bed/Api/TestCommand.cs b/test-bed/Api/TestCommand.cs index 9da145e91..90c79c955 100644 --- a/test-bed/Api/TestCommand.cs +++ b/test-bed/Api/TestCommand.cs @@ -1,4 +1,3 @@ -using System.ComponentModel; using FluentValidation; using LeanCode.Contracts; using LeanCode.Contracts.Security; diff --git a/test-bed/Api/TestQuery.cs b/test-bed/Api/TestQuery.cs index 70ae91534..590fa7492 100644 --- a/test-bed/Api/TestQuery.cs +++ b/test-bed/Api/TestQuery.cs @@ -3,16 +3,17 @@ namespace LeanCode.TestBed.Api; -[Obsolete] +[Obsolete("For tests.")] public class TestQuery : IQuery { } public class TestQueryResult { public Guid Id { get; set; } - public string Property1 { get; set; } + public string Property1 { get; set; } = default!; public TestQueryResult? Inner { get; set; } } +[Obsolete("For tests.")] public class TestQueryQH : IQueryHandler { public Task ExecuteAsync(HttpContext context, TestQuery query) diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/CustomAuthorizer.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/CustomAuthorizer.cs index 880f2f312..3973dcae5 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/CustomAuthorizer.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/CustomAuthorizer.cs @@ -7,7 +7,7 @@ namespace LeanCode.CQRS.AspNetCore.Tests.Integration; public interface ICustomAuthorizerParams { - public bool FailAuthorization { get; set; } + bool FailAuthorization { get; set; } } [SuppressMessage("?", "CA1040", Justification = "Marker interface")] diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/HttpContextCustomAuthorizer.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/HttpContextCustomAuthorizer.cs index dcd0efafb..01a07c760 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/HttpContextCustomAuthorizer.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/HttpContextCustomAuthorizer.cs @@ -7,7 +7,7 @@ namespace LeanCode.CQRS.AspNetCore.Tests.Integration; public interface IHttpContextCustomAuthorizerParams { - public bool FailAuthorization { get; set; } + bool FailAuthorization { get; set; } } [SuppressMessage("?", "CA1040", Justification = "Marker interface")] diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSCommandsTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSCommandsTests.cs index 3a0b9e198..0d75f0df7 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSCommandsTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSCommandsTests.cs @@ -46,7 +46,7 @@ public async Task Returns_OK_with_successful_command_result_on_success() Assert.Equal(HttpStatusCode.OK, statusCode); var result = JsonSerializer.Deserialize(body); Assert.NotNull(result); - Assert.True(result!.WasSuccessful); + Assert.True(result.WasSuccessful); } [Fact] @@ -62,7 +62,7 @@ public async Task Returns_UnprocessableEntity_with_errors_when_validation_fails( Assert.Equal(HttpStatusCode.UnprocessableEntity, statusCode); Assert.NotNull(commandResult); - Assert.False(commandResult!.WasSuccessful); + Assert.False(commandResult.WasSuccessful); var error = Assert.Single(commandResult.ValidationErrors); Assert.Equal(nameof(TestCommand.FailValidation), error.PropertyName); Assert.Equal("Test command should pass validation", error.ErrorMessage); diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSQueriesTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSQueriesTests.cs index a1e81209e..a6086bda9 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSQueriesTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests.Integration/RemoteCQRSQueriesTests.cs @@ -1,6 +1,5 @@ using System.Net; using System.Text.Json; -using LeanCode.Contracts; using Xunit; namespace LeanCode.CQRS.AspNetCore.Tests.Integration; diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs index ab4bd8943..71c348952 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs @@ -11,7 +11,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Xunit; -using Xunit.Internal; namespace LeanCode.CQRS.AspNetCore.Tests { @@ -150,42 +149,42 @@ private static CQRSEndpointsDataSource PrepareEndpointsSource() typeof(Command), typeof(CommandResult), typeof(IgnoreHandler), - (_, __) => Task.FromResult(null) + (_, _) => Task.FromResult(null) ), new( CQRSObjectKind.Command, typeof(AliasedCommand), typeof(CommandResult), typeof(IgnoreHandler), - (_, __) => Task.FromResult(null) + (_, _) => Task.FromResult(null) ), new( CQRSObjectKind.Query, typeof(Query), typeof(Result), typeof(IgnoreHandler), - (_, __) => Task.FromResult(null) + (_, _) => Task.FromResult(null) ), new( CQRSObjectKind.Query, typeof(AliasedQuery), typeof(Result), typeof(IgnoreHandler), - (_, __) => Task.FromResult(null) + (_, _) => Task.FromResult(null) ), new( CQRSObjectKind.Operation, typeof(Operation), typeof(Result), typeof(IgnoreHandler), - (_, __) => Task.FromResult(null) + (_, _) => Task.FromResult(null) ), new( CQRSObjectKind.Operation, typeof(AliasedOperation), typeof(Result), typeof(IgnoreHandler), - (_, __) => Task.FromResult(null) + (_, _) => Task.FromResult(null) ), ], pipeline, @@ -205,12 +204,6 @@ public void Dispose() public async ValueTask DisposeAsync() => await host.StopAsync(); - private sealed class MockExecutorFactory : IObjectExecutorFactory - { - public ObjectExecutor CreateExecutorFor(CQRSObjectKind kind, Type objectType, Type handlerType) => - (_, __) => Task.FromResult(null); - } - private sealed class IgnoreHandler { } } } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSObjectsRegistrationSourceTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSObjectsRegistrationSourceTests.cs index 3b69a32bf..51ed4d3b3 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSObjectsRegistrationSourceTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSObjectsRegistrationSourceTests.cs @@ -57,7 +57,6 @@ public void Duplicate_objects_cannot_be_registered() TypesCatalog.Of(), TypesCatalog.Of() ); - var firstCount = registrationSource.Objects.Count; var act = () => registrationSource.AddCQRSObjects( diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs index ea351c09a..6bdf86433 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs @@ -11,13 +11,12 @@ namespace LeanCode.CQRS.AspNetCore.Tests; public class CQRSServicesBuilderTests { - private readonly ServiceCollection services; private readonly CQRSObjectsRegistrationSource registrationSource; private readonly CQRSServicesBuilder builder; public CQRSServicesBuilderTests() { - services = new(); + var services = new ServiceCollection(); registrationSource = new CQRSObjectsRegistrationSource(services, new ObjectExecutorFactory()); registrationSource.AddCQRSObjects( TypesCatalog.Of(), diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CommandValidatorResolverTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CommandValidatorResolverTests.cs index 17aa4fb4e..cfe3232a6 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CommandValidatorResolverTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CommandValidatorResolverTests.cs @@ -12,13 +12,12 @@ namespace LeanCode.CQRS.AspNetCore.Tests; public class CommandValidatorResolverTests { private readonly ICommandValidator validator; - private readonly IServiceProvider serviceProvider; private readonly CommandValidatorResolver resolver; public CommandValidatorResolverTests() { + var serviceProvider = Substitute.For(); validator = Substitute.For>(); - serviceProvider = Substitute.For(); resolver = new CommandValidatorResolver(serviceProvider); serviceProvider.GetService(typeof(ICommandValidator)).Returns(validator); diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/LocalHttpRequestTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/LocalHttpRequestTests.cs index d56b54e36..f87f74537 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/LocalHttpRequestTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/LocalHttpRequestTests.cs @@ -130,8 +130,8 @@ public void Form_is_empty_form_collection_and_cannot_be_changed() public void Headers_dictionary_is_passed_further() { var headers = new HeaderDictionary { ["X-TEST"] = "test" }; - var request = new LocalHttpRequest(Substitute.For(), headers); + var localHttpRequest = new LocalHttpRequest(Substitute.For(), headers); - request.Headers.Should().BeSameAs(headers); + localHttpRequest.Headers.Should().BeSameAs(headers); } } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullConnectionInfoTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullConnectionInfoTests.cs index 63713e8ec..74f742691 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullConnectionInfoTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullConnectionInfoTests.cs @@ -1,4 +1,3 @@ -using System.Net; using System.Security.Cryptography.X509Certificates; using FluentAssertions; using LeanCode.CQRS.AspNetCore.Local.Context; diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullRequestCookieCollectionTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullRequestCookieCollectionTests.cs index ee8bb4c0f..9d14689af 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullRequestCookieCollectionTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/Context/NullRequestCookieCollectionTests.cs @@ -21,7 +21,8 @@ public void ContainsKey_should_always_return_false() [Fact] public void GetEnumerator_should_return_empty_enumerable() { - NullRequestCookieCollection.Empty.GetEnumerator().MoveNext().Should().BeFalse(); + using var enumerator = NullRequestCookieCollection.Empty.GetEnumerator(); + enumerator.MoveNext().Should().BeFalse(); } [Fact] diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedExecutorIntegrationTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedExecutorIntegrationTests.cs index 35e212f8d..490e500ec 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedExecutorIntegrationTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedExecutorIntegrationTests.cs @@ -32,14 +32,14 @@ public MiddlewareBasedExecutorIntegrationTests() .ConfigureServices(services => { services.AddRouting(); - services.AddCQRS(ThisCatalog, ThisCatalog).WithLocalQueries(q => { }); + services.AddCQRS(ThisCatalog, ThisCatalog).WithLocalQueries(_ => { }); }) .Configure(app => { app.UseRouting() .UseEndpoints(e => { - e.MapRemoteCQRS("/cqrs", cqrs => { }); + e.MapRemoteCQRS("/cqrs", _ => { }); }); }); }) diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs index 377a8c6bb..111ec052d 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs @@ -21,8 +21,6 @@ public class MiddlewareBasedLocalExecutorTests private static readonly TypesCatalog ThisCatalog = TypesCatalog.Of(); private readonly LocalDataStorage storage = new(); - private readonly IServiceProvider serviceProvider; - private readonly ICQRSObjectSource objectSource; private readonly MiddlewareBasedLocalCommandExecutor executor; @@ -36,8 +34,8 @@ public MiddlewareBasedLocalExecutorTests() var registrationSource = new CQRSObjectsRegistrationSource(serviceCollection, new ObjectExecutorFactory()); registrationSource.AddCQRSObjects(ThisCatalog, ThisCatalog); - serviceProvider = serviceCollection.BuildServiceProvider(); - objectSource = registrationSource; + var serviceProvider = serviceCollection.BuildServiceProvider(); + var objectSource = registrationSource; executor = new(serviceProvider, objectSource, app => app.UseMiddleware()); } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs index 455144f2c..3ad9c4579 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs @@ -88,14 +88,14 @@ public static ILocalCommandExecutor BuildWith(Action co } } -public record DummyCommand() : ICommand; +public record DummyCommand : ICommand; -public record ExceptionTranslationCommand() : ICommand; +public record ExceptionTranslationCommand : ICommand; -public record ValidatedCommand() : ICommand; +public record ValidatedCommand : ICommand; [AuthorizeWhenHasAnyOf("invalid")] -public record SecuredCommand() : ICommand; +public record SecuredCommand : ICommand; public class DummyCommandHandler : ICommandHandler { @@ -126,7 +126,7 @@ public class ValidatedCommandHandler : ICommandHandler public class CommandValidatorResolver : ICommandValidatorResolver { - public ICommandValidatorWrapper? FindCommandValidator(Type commandType) => new ValidatedCommandValidator(); + public ICommandValidatorWrapper FindCommandValidator(Type commandType) => new ValidatedCommandValidator(); } public class SecureCommandHandler : ICommandHandler diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTestBase.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTestBase.cs index f60c65685..a107f7c1b 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTestBase.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTestBase.cs @@ -21,7 +21,7 @@ public abstract class CQRSMiddlewareTestBase : IAsyncLifetime, IDis protected IHost Host { get; } protected TestServer Server { get; } - protected RequestDelegate FinalPipeline { get; set; } = ctx => Task.CompletedTask; + protected RequestDelegate FinalPipeline { get; set; } = _ => Task.CompletedTask; protected virtual void ConfigureServices(IServiceCollection services) { } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTests.cs index 8246d9773..5ccd9b8df 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSMiddlewareTests.cs @@ -150,7 +150,7 @@ public async Task Returns_500InternalServerError_if_pipeline_execution_thrown_an var query = new Query(); SetDeserializerResult(query); - FinalPipeline = ctx => throw new InvalidOperationException(); + FinalPipeline = _ => throw new InvalidOperationException(); var httpContext = await SendAsync(); @@ -164,7 +164,7 @@ public async Task Correctly_passes_payload_and_context() var query = new Query(); SetDeserializerResult(query); - object? interceptedPayload = null!; + object interceptedPayload = null!; FinalPipeline = ctx => { diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSSecurityMiddlewareTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSSecurityMiddlewareTests.cs index 227d32b02..e76f82af9 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSSecurityMiddlewareTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSSecurityMiddlewareTests.cs @@ -112,7 +112,7 @@ await Assert.ThrowsAsync( public async Task Passes_custom_authorizer_data_to_authorizers() { var cmd = new SingleAuthorizer(); - var httpContext = await SendPayloadAsync(cmd, AuthenticatedUser()); + await SendPayloadAsync(cmd, AuthenticatedUser()); await firstAuthorizer .Received() @@ -174,9 +174,9 @@ public class MultipleAuthorizers : ICommand { } private sealed class NotImplementedAuthorizer { } // Public, so that NSubstitute could mock it - public interface IFirstAuthorizer { } + public interface IFirstAuthorizer : ICustomAuthorizer { } - public interface ISecondAuthorizer { } + public interface ISecondAuthorizer : ICustomAuthorizer { } public interface INotImplementedAuthorizer { } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSValidationMiddlewareTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSValidationMiddlewareTests.cs index 0a2e7d0cb..931285566 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSValidationMiddlewareTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/CQRSValidationMiddlewareTests.cs @@ -27,8 +27,7 @@ public CQRSValidationMiddlewareTests() FinalPipeline = ctx => { - ctx.GetCQRSRequestPayload() - .SetResult(ExecutionResult.WithPayload(CommandResult.Success, StatusCodes.Status200OK)); + ctx.GetCQRSRequestPayload().SetResult(ExecutionResult.WithPayload(CommandResult.Success)); return Task.CompletedTask; }; } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs index f60326f7a..036f02b9b 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs @@ -237,25 +237,25 @@ private static CQRSEndpointsDataSource CreateDataSource(Type forObject) } } -public record QueryResultDTO(); +public record QueryResultDTO; -public record Query() : IQuery; +public record Query : IQuery; public class QueryQH : IQueryHandler { public Task ExecuteAsync(HttpContext context, Query query) => throw new NotImplementedException(); } -public record Command() : ICommand; +public record Command : ICommand; public class CommandCH : ICommandHandler { public Task ExecuteAsync(HttpContext context, Command command) => throw new NotImplementedException(); } -public record OperationResultDTO(); +public record OperationResultDTO; -public record Operation() : IOperation; +public record Operation : IOperation; public class OperationOH : IOperationHandler { diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs index bdb743075..5af40a0a5 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceCollectionExtensionsTests.cs @@ -4,6 +4,7 @@ namespace LeanCode.CQRS.AspNetCore.Tests; +// ReSharper disable once UnusedTypeParameter internal interface IGenericService { } internal sealed class Type1 { } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs index 52bb43f86..144d08956 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs @@ -117,20 +117,15 @@ CancellationToken cancellationToken public ServiceProviderAssertions(ServiceProvider subject) : base(subject) { } - public AndConstraint HaveService(string because = "", params object[] becauseArgs) + public void HaveService(string because = "", params object[] becauseArgs) { Execute .Assertion.BecauseOf(because, becauseArgs) .ForCondition(Subject.GetRequiredService().IsService(typeof(T))) .FailWith("Expected to have {0} registered{reason}", typeof(T)); - return new AndConstraint(this); } - public AndConstraint HaveKeyedService( - object? serviceKey, - string because = "", - params object[] becauseArgs - ) + public void HaveKeyedService(object? serviceKey, string because = "", params object[] becauseArgs) { Execute .Assertion.BecauseOf(because, becauseArgs) @@ -138,16 +133,14 @@ params object[] becauseArgs Subject.GetRequiredService().IsKeyedService(typeof(T), serviceKey) ) .FailWith("Expected to have {0} registered as key {1}{reason}", typeof(T), serviceKey); - return new AndConstraint(this); } - public AndConstraint NotHaveService(string because = "", params object[] becauseArgs) + public void NotHaveService(string because = "", params object[] becauseArgs) { Execute .Assertion.BecauseOf(because, becauseArgs) .ForCondition(!Subject.GetRequiredService().IsService(typeof(T))) .FailWith("Expected to have {0} registered{reason}", typeof(T)); - return new AndConstraint(this); } } diff --git a/test/CQRS/LeanCode.CQRS.MassTransitRelay.Tests/Middleware/EventsPublisherFilterTests.cs b/test/CQRS/LeanCode.CQRS.MassTransitRelay.Tests/Middleware/EventsPublisherFilterTests.cs index 05108a3ae..7f296cf8b 100644 --- a/test/CQRS/LeanCode.CQRS.MassTransitRelay.Tests/Middleware/EventsPublisherFilterTests.cs +++ b/test/CQRS/LeanCode.CQRS.MassTransitRelay.Tests/Middleware/EventsPublisherFilterTests.cs @@ -1,6 +1,7 @@ #nullable enable using LeanCode.CQRS.MassTransitRelay.Middleware; using LeanCode.DomainModels.Model; +using LeanCode.TimeProvider; using MassTransit; using MassTransit.Testing; using Microsoft.Extensions.DependencyInjection; @@ -64,7 +65,7 @@ private sealed class TestEvent : IDomainEvent private sealed class TestConsumer : IConsumer { - public static readonly TestEvent Event = new() { Id = Guid.NewGuid() }; + public static readonly TestEvent Event = new() { Id = Guid.NewGuid(), DateOccurred = Time.UtcNow }; public Task Consume(ConsumeContext context) { diff --git a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpCommandsExecutorTests.cs b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpCommandsExecutorTests.cs index d81854eef..174d15cda 100644 --- a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpCommandsExecutorTests.cs +++ b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpCommandsExecutorTests.cs @@ -1,8 +1,5 @@ -using System; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; using LeanCode.Contracts; using Xunit; @@ -32,7 +29,7 @@ public async Task Serializes_the_request_payload() await exec.RunAsync(new ExampleCommand { RequestData = "data" }); Assert.NotNull(handler.Request); - var content = await handler!.Request!.Content!.ReadAsStringAsync(); + var content = await handler.Request!.Content!.ReadAsStringAsync(); Assert.Equal("{\"RequestData\":\"data\"}", content); } diff --git a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpOperationsExecutorTests.cs b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpOperationsExecutorTests.cs index c1c2e4a02..0e1113c7f 100644 --- a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpOperationsExecutorTests.cs +++ b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpOperationsExecutorTests.cs @@ -1,7 +1,4 @@ -using System; using System.Net; -using System.Net.Http; -using System.Threading.Tasks; using LeanCode.Contracts; using Xunit; @@ -31,7 +28,7 @@ public async Task Serializes_the_request_payload() await exec.GetAsync(new ExampleOperation { RequestData = "data" }); Assert.NotNull(handler.Request); - var content = await handler!.Request!.Content!.ReadAsStringAsync(); + var content = await handler.Request!.Content!.ReadAsStringAsync(); Assert.Equal("{\"RequestData\":\"data\"}", content); } diff --git a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpQueriesExecutorTests.cs b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpQueriesExecutorTests.cs index af9cbffe9..eff233850 100644 --- a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpQueriesExecutorTests.cs +++ b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/HttpQueriesExecutorTests.cs @@ -1,7 +1,4 @@ -using System; using System.Net; -using System.Net.Http; -using System.Threading.Tasks; using LeanCode.Contracts; using Xunit; @@ -28,7 +25,7 @@ public async Task Serializes_the_request_payload() await exec.GetAsync(new ExampleQuery { RequestData = "data" }); Assert.NotNull(handler.Request); - var content = await handler!.Request!.Content!.ReadAsStringAsync(); + var content = await handler.Request!.Content!.ReadAsStringAsync(); Assert.Equal("{\"RequestData\":\"data\"}", content); } diff --git a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/ShortcircuitingJsonHandler.cs b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/ShortcircuitingJsonHandler.cs index 2d39fb30c..d11024c27 100644 --- a/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/ShortcircuitingJsonHandler.cs +++ b/test/CQRS/LeanCode.CQRS.RemoteHttp.Client.Tests/ShortcircuitingJsonHandler.cs @@ -1,10 +1,5 @@ -using System.Collections.Generic; -using System.IO; using System.Net; -using System.Net.Http; using System.Text; -using System.Threading; -using System.Threading.Tasks; namespace LeanCode.CQRS.RemoteHttp.Client.Tests; @@ -45,12 +40,9 @@ private static async Task CloneRequestAsync(HttpRequestMessa ms.Position = 0; clone.Content = new StreamContent(ms); - if (req.Content.Headers != null) + foreach (var h in req.Content.Headers) { - foreach (var h in req.Content.Headers) - { - clone.Content.Headers.Add(h.Key, h.Value); - } + clone.Content.Headers.Add(h.Key, h.Value); } } diff --git a/test/CQRS/LeanCode.CQRS.Security.Tests/ClaimsPrinicipalTests.cs b/test/CQRS/LeanCode.CQRS.Security.Tests/ClaimsPrinicipalTests.cs index 4b64ce739..619ab399e 100644 --- a/test/CQRS/LeanCode.CQRS.Security.Tests/ClaimsPrinicipalTests.cs +++ b/test/CQRS/LeanCode.CQRS.Security.Tests/ClaimsPrinicipalTests.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; using System.Security.Claims; -using System.Threading.Tasks; -using LeanCode.CQRS.Security; -using LeanCode.CQRS.Security.Exceptions; -using NSubstitute; using Xunit; -namespace LeanCode.CQRS.Default.Tests.Security; +namespace LeanCode.CQRS.Security.Tests; public class ClaimsPrincipalTests { @@ -120,11 +113,10 @@ private static ClaimsPrincipal CreateUser(params string[] roles) private sealed class RoleRegistration : IRoleRegistration { public IEnumerable Roles { get; } = - new Role[] - { + [ new Role(Reg.User, Permissions.List, Permissions.Read), new Role(Reg.Admin, Permissions.Create, Permissions.List, Permissions.Read, Permissions.Update), new Role(Reg.Contributor, Permissions.Update), - }; + ]; } } diff --git a/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs b/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs index ca6597bc4..73ceae834 100644 --- a/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs +++ b/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs @@ -1,11 +1,10 @@ using System.Security.Claims; using FluentAssertions; -using LeanCode.CQRS.Security; using Microsoft.AspNetCore.Http; using NSubstitute; using Xunit; -namespace LeanCode.CQRS.Default.Tests.Security; +namespace LeanCode.CQRS.Security.Tests; public class CustomAuthorizerTests { diff --git a/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs b/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs index 762b40513..2294c7adb 100644 --- a/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs +++ b/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs @@ -60,7 +60,7 @@ public async Task Passes_http_context_to_validation_context() var validator = Substitute.For(); var httpContext = MockHttpContext(); var command = new Command(); - var adapter = new FluentValidationCommandValidatorAdapter(validator); + var validatorAdapter = new FluentValidationCommandValidatorAdapter(validator); HttpContext interceptedHttpContext = null; _ = validator @@ -70,7 +70,7 @@ public async Task Passes_http_context_to_validation_context() ) .Returns(new ValidationResult()); - await adapter.ValidateAsync(httpContext, command); + await validatorAdapter.ValidateAsync(httpContext, command); interceptedHttpContext.Should().BeSameAs(httpContext); } diff --git a/test/Core/LeanCode.Components.Startup.Tests/LeanStartupTests.cs b/test/Core/LeanCode.Components.Startup.Tests/LeanStartupTests.cs index 7a786bcf9..e02d83a71 100644 --- a/test/Core/LeanCode.Components.Startup.Tests/LeanStartupTests.cs +++ b/test/Core/LeanCode.Components.Startup.Tests/LeanStartupTests.cs @@ -61,6 +61,8 @@ protected override void ConfigureApp(IApplicationBuilder app) { } public class TestStartupWithFalseParameter : LeanStartup { protected override IReadOnlyList Modules { get; } + + // ReSharper disable once UnassignedGetOnlyAutoProperty protected override bool CloseAndFlushLogger { get; } public TestStartupWithFalseParameter(IConfiguration config) diff --git a/test/Domain/LeanCode.DomainModels.EF.Tests/ModelBuilderExtensionsTests.OptimisticConcurrency.cs b/test/Domain/LeanCode.DomainModels.EF.Tests/ModelBuilderExtensionsTests.OptimisticConcurrency.cs index 444a71288..d56545059 100644 --- a/test/Domain/LeanCode.DomainModels.EF.Tests/ModelBuilderExtensionsTests.OptimisticConcurrency.cs +++ b/test/Domain/LeanCode.DomainModels.EF.Tests/ModelBuilderExtensionsTests.OptimisticConcurrency.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics.CodeAnalysis; using LeanCode.DomainModels.Model; using Microsoft.EntityFrameworkCore; @@ -13,11 +12,11 @@ public void When_IOC_is_implemented_explicitly_DateModified_has_correctly_config { using (var db = new ExplicitlyContext()) { - var ent = db.Model.FindEntityType(typeof(ExplicitlyImplemented).FullName); - var prop = ent.FindProperty("DateModified"); + var ent = db.Model.FindEntityType(typeof(ExplicitlyImplemented).FullName!); + var prop = ent!.FindProperty("DateModified"); Assert.Equal( "k__BackingField", - prop.FieldInfo.Name + prop!.FieldInfo!.Name ); } } @@ -27,9 +26,9 @@ public void When_IOC_is_implemented_implicitly_DateModified_has_correctly_config { using (var db = new ImplicitlyContext()) { - var ent = db.Model.FindEntityType(typeof(ImplicitlyImplemented).FullName); - var prop = ent.FindProperty("DateModified"); - Assert.Equal("k__BackingField", prop.FieldInfo.Name); + var ent = db.Model.FindEntityType(typeof(ImplicitlyImplemented).FullName!); + var prop = ent!.FindProperty("DateModified"); + Assert.Equal("k__BackingField", prop!.FieldInfo!.Name); } } @@ -38,7 +37,10 @@ public void When_DateModified_is_implemented_differently_Fails() { using (var db = new WrongDateModifiedContext()) { - Assert.Throws(() => db.Model.FindEntityType(typeof(WrongDateModified).FullName)); + Assert.Throws( + // ReSharper disable once AccessToDisposedClosure + () => db.Model.FindEntityType(typeof(WrongDateModified).FullName!) + ); } } } diff --git a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/Events.cs b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/Events.cs index 4a80f29ad..6e331fab5 100644 --- a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/Events.cs +++ b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/Events.cs @@ -1,5 +1,5 @@ -using System; using LeanCode.DomainModels.Model; +using LeanCode.TimeProvider; namespace LeanCode.DomainModels.EventsExecution.TestHelpers.Tests; @@ -11,6 +11,7 @@ internal sealed class SampleEvent1 : IDomainEvent public SampleEvent1(Guid id) { Id = id; + DateOccurred = Time.UtcNow; } } @@ -22,5 +23,6 @@ internal sealed class SampleEvent2 : IDomainEvent public SampleEvent2(Guid id) { Id = id; + DateOccurred = Time.UtcNow; } } diff --git a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.RaceConds.cs b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.RaceConds.cs index fa1a71f4a..78f30620d 100644 --- a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.RaceConds.cs +++ b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.RaceConds.cs @@ -1,5 +1,3 @@ -using System; -using System.Threading.Tasks; using LeanCode.DomainModels.Model; using LeanCode.Test.Helpers; using LeanCode.UnitTests.TestHelpers; diff --git a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.cs b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.cs index e7fc16536..61cb8a1ea 100644 --- a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.cs +++ b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/EventsInterceptorTests.cs @@ -1,4 +1,3 @@ -using System; using LeanCode.DomainModels.Model; using LeanCode.UnitTests.TestHelpers; using Xunit; diff --git a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests.csproj b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests.csproj index d1111df12..274050294 100644 --- a/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests.csproj +++ b/test/Domain/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests/LeanCode.DomainModels.EventsExecution.TestHelpers.Tests.csproj @@ -2,6 +2,7 @@ + diff --git a/test/Domain/LeanCode.DomainModels.Tests/DataAccess/IRepositoryExtensionsTests.cs b/test/Domain/LeanCode.DomainModels.Tests/DataAccess/IRepositoryExtensionsTests.cs index ed5ba25f5..3efa4e169 100644 --- a/test/Domain/LeanCode.DomainModels.Tests/DataAccess/IRepositoryExtensionsTests.cs +++ b/test/Domain/LeanCode.DomainModels.Tests/DataAccess/IRepositoryExtensionsTests.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using LeanCode.DomainModels.DataAccess; using LeanCode.DomainModels.Ids; using LeanCode.DomainModels.Model; diff --git a/test/Domain/LeanCode.DomainModels.Tests/Ids/PrefixedUlidVariationsTests.cs b/test/Domain/LeanCode.DomainModels.Tests/Ids/PrefixedUlidVariationsTests.cs index 063c301c2..8a3202566 100644 --- a/test/Domain/LeanCode.DomainModels.Tests/Ids/PrefixedUlidVariationsTests.cs +++ b/test/Domain/LeanCode.DomainModels.Tests/Ids/PrefixedUlidVariationsTests.cs @@ -1,4 +1,3 @@ -using System.Globalization; using FluentAssertions; using LeanCode.DomainModels.Ids; using Xunit; diff --git a/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs b/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs index c46df2e2d..6b10f268f 100644 --- a/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs +++ b/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs @@ -6,12 +6,10 @@ namespace LeanCode.UserIdExtractors.Tests; public class UserIdExtractorsRegistrationTests { - private const string UserIdClaim = "sub"; - [Fact] public void String_IUserIdExtractor_is_correctly_registered() { - var serviceProvider = BuildServiceProvider(services => services.AddStringUserIdExtractor(UserIdClaim)); + var serviceProvider = BuildServiceProvider(services => services.AddStringUserIdExtractor()); var userIdExtractor = serviceProvider.GetService>(); Assert.NotNull(userIdExtractor); @@ -21,7 +19,7 @@ public void String_IUserIdExtractor_is_correctly_registered() [Fact] public void Guid_IUserIdExtractor_is_correctly_registered() { - var serviceProvider = BuildServiceProvider(services => services.AddGuidUserIdExtractor(UserIdClaim)); + var serviceProvider = BuildServiceProvider(services => services.AddGuidUserIdExtractor()); var userIdExtractor = serviceProvider.GetService>(); Assert.NotNull(userIdExtractor); @@ -31,9 +29,7 @@ public void Guid_IUserIdExtractor_is_correctly_registered() [Fact] public void Raw_typed_IUserIdExtractor_is_correctly_registered() { - var serviceProvider = BuildServiceProvider(services => - services.AddRawTypedUserIdExtractor(UserIdClaim) - ); + var serviceProvider = BuildServiceProvider(services => services.AddRawTypedUserIdExtractor()); var userIdExtractor = serviceProvider.GetService>(); Assert.NotNull(userIdExtractor); @@ -44,7 +40,7 @@ public void Raw_typed_IUserIdExtractor_is_correctly_registered() public void Prefixed_typed_IUserIdExtractor_is_correctly_registered() { var serviceProvider = BuildServiceProvider(services => - services.AddPrefixedUserIdExtractor(UserIdClaim) + services.AddPrefixedUserIdExtractor() ); var userIdExtractor = serviceProvider.GetService>(); @@ -56,7 +52,7 @@ public void Prefixed_typed_IUserIdExtractor_is_correctly_registered() public void Non_generic_IUserIdExtractor_is_registered_for_other_user_id_types() { var serviceProvider = BuildServiceProvider(services => - services.AddPrefixedUserIdExtractor(UserIdClaim) + services.AddPrefixedUserIdExtractor() ); var userIdExtractor = serviceProvider.GetService(); diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs index 64397c55e..da924c508 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs @@ -85,7 +85,7 @@ public AuditLogsIntegrationTests() } ); }); - app.Run(ctx => + app.Run(_ => { return Task.CompletedTask; }); diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsMiddlewareTests.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsMiddlewareTests.cs index a204707df..c6534a3bd 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsMiddlewareTests.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsMiddlewareTests.cs @@ -14,9 +14,9 @@ public async Task Extracts_changes_after_pipeline_execution() using var dbContext = new TestDbContext(); var bus = Substitute.For(); var publisher = Substitute.For(); - var middleware = new AuditLogsMiddleware(c => Task.CompletedTask); + var middleware = new AuditLogsMiddleware(_ => Task.CompletedTask); var httpContext = Substitute.For(); - httpContext.Request.Path.Returns(PathString.FromUriComponent(RequestPath)); + httpContext.Request.Path.Returns(PathString.FromUriComponent(new Uri(RequestPath))); await middleware.InvokeAsync(httpContext, dbContext, bus, publisher); diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsPublisherTests.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsPublisherTests.cs index 7a52dd462..9dbdd1e4b 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsPublisherTests.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsPublisherTests.cs @@ -21,7 +21,7 @@ public async Task Check_if_publisher_does_nothing_when_nothing_changed() var bus = Substitute.For(); await auditLogsPublisher.ExtractAndPublishAsync(dbContext, bus, string.Empty, default); - await bus.DidNotReceiveWithAnyArgs().Publish(default!, default!); + await bus.DidNotReceiveWithAnyArgs().Publish(default!); } [Fact] @@ -31,7 +31,7 @@ public async Task Check_if_publishes_change() var bus = Substitute.For(); await auditLogsPublisher.ExtractAndPublishAsync(dbContext, bus, string.Empty, default); - await bus.ReceivedWithAnyArgs(1).Publish((AuditLogMessage)default!, default!); + await bus.ReceivedWithAnyArgs(1).Publish((AuditLogMessage)default!); } public void Dispose() diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs index acb8d4fc7..af88e89e6 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs @@ -38,7 +38,7 @@ public void Check_if_added_entity_is_extracted() .BeEquivalentTo( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, EntityState = "Added", Changes = JsonSerializer.SerializeToDocument(testEntity, Options), @@ -67,7 +67,7 @@ public void Check_if_updated_entity_is_extracted() .BeEquivalentTo( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Modified", @@ -94,7 +94,7 @@ public void Check_if_deleted_entity_is_extracted() .BeEquivalentTo( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Deleted", @@ -138,7 +138,7 @@ public void Check_if_root_entity_is_extracted_when_owned_entities_are_added() .ContainEquivalentOf( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Modified", @@ -168,7 +168,7 @@ public void Check_if_root_entity_is_extracted_when_owned_entities_are_updated() .ContainEquivalentOf( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Modified", @@ -196,7 +196,7 @@ public void Check_if_root_entity_is_extracted_when_owned_entities_are_removed() .ContainEquivalentOf( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Modified", @@ -222,7 +222,7 @@ public void Check_if_root_entity_is_extracted_when_included_entities_are_added() .ContainEquivalentOf( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Modified", @@ -250,7 +250,7 @@ public void Check_if_root_entity_is_extracted_when_included_entities_are_updated .ContainEquivalentOf( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Modified", @@ -278,7 +278,7 @@ public void Check_if_root_entity_is_extracted_when_included_entities_are_removed .ContainEquivalentOf( new { - Ids = new string[] { SomeId }, + Ids = new[] { SomeId }, Type = typeof(TestEntity).FullName, Changes = JsonSerializer.SerializeToDocument(testEntity, Options), EntityState = "Modified", @@ -303,7 +303,7 @@ public void Check_if_returns_nothing_when_nothing_was_changed() dbContext.TestEntities.Add(TestEntity.Create(SomeId)); dbContext.SaveChanges(); - var testEntity = dbContext.TestEntities.Find(SomeId); + dbContext.TestEntities.Find(SomeId); var changes = ChangedEntitiesExtractor.Extract(dbContext); changes.Should().BeEmpty(); @@ -314,7 +314,7 @@ public void Dispose() Dispose(true); } - protected virtual void Dispose(bool disposing) + protected virtual void Dispose(bool _) { dbContext.Dispose(); } diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs index fd3cf0cec..bacc624df 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs @@ -106,6 +106,7 @@ public class OwnedEntity public int SomeInt { get; set; } public string SomeString { get; set; } = null!; + // ReSharper disable once UnusedMember.Local private OwnedEntity() { } public OwnedEntity(int someInt, string someString) @@ -119,7 +120,7 @@ public class IncludedEntity { public TestEntity TestEntity { get; private init; } = null!; public string TestEntityId { get; private init; } = null!; - public int SomeInt { get; set; } + public int SomeInt { get; private init; } public string SomeString { get; set; } = null!; private IncludedEntity() { } diff --git a/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs b/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs index ae0c62c40..4afda0d91 100644 --- a/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs +++ b/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs @@ -1,4 +1,3 @@ -using System.Text; using System.Text.Json; using Azure.Data.Tables; using Azure.Storage.Blobs; @@ -7,7 +6,6 @@ using LeanCode.AuditLogs; using LeanCode.Test.Helpers; using LeanCode.TimeProvider; -using Xunit; namespace LeanCode.Azure.Tests; @@ -95,7 +93,7 @@ await storage.StoreEventAsync( ); } - var containerClient = blobServiceClient.GetBlobContainerClient( + blobServiceClient.GetBlobContainerClient( Environment.GetEnvironmentVariable(Env.AzureBlobStorageContainerNameKey) ); @@ -132,7 +130,7 @@ await storage.StoreEventAsync( ); } - var containerClient = blobServiceClient.GetBlobContainerClient( + blobServiceClient.GetBlobContainerClient( Environment.GetEnvironmentVariable(Env.AzureBlobStorageContainerNameKey) ); diff --git a/test/Infrastructure/LeanCode.Azure.Tests/PostgresAD/NpgsqlActiveDirectoryAuthenticationTests.cs b/test/Infrastructure/LeanCode.Azure.Tests/PostgresAD/NpgsqlActiveDirectoryAuthenticationTests.cs index e90f525ec..767e1e567 100644 --- a/test/Infrastructure/LeanCode.Azure.Tests/PostgresAD/NpgsqlActiveDirectoryAuthenticationTests.cs +++ b/test/Infrastructure/LeanCode.Azure.Tests/PostgresAD/NpgsqlActiveDirectoryAuthenticationTests.cs @@ -2,7 +2,6 @@ using LeanCode.Npgsql.ActiveDirectory; using LeanCode.Test.Helpers; using Npgsql; -using Xunit; namespace LeanCode.Azure.Tests.PostgresAD; diff --git a/test/Infrastructure/LeanCode.Dapper.Tests/DbContextExtensionsTests.cs b/test/Infrastructure/LeanCode.Dapper.Tests/DbContextExtensionsTests.cs index 993b92210..1d9b64b87 100644 --- a/test/Infrastructure/LeanCode.Dapper.Tests/DbContextExtensionsTests.cs +++ b/test/Infrastructure/LeanCode.Dapper.Tests/DbContextExtensionsTests.cs @@ -55,6 +55,7 @@ private sealed class Entity private abstract class BaseContext : DbContext { + // ReSharper disable once UnusedMember.Local public DbSet Entities { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) diff --git a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientLocalizationTests.cs b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientLocalizationTests.cs index 489360711..e828d6951 100644 --- a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientLocalizationTests.cs +++ b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientLocalizationTests.cs @@ -1,6 +1,5 @@ using System.Globalization; using FirebaseAdmin.Messaging; -using LeanCode.Firebase; using LeanCode.Localization.StringLocalizers; using NSubstitute; using Xunit; @@ -50,11 +49,11 @@ public void Localizes_body_correctly() [Fact] public void Localizes_ImageUrl_correctly() { - const string Key = "URL"; - const string Value = "formatted image url"; + const string Key = "https://example.com/image.jpg"; + const string Value = "https://example.com/image_en.jpg"; stringLocalizer[Culture, Key].Returns(Value); - var n = client.Localize(Culture).ImageUrl(Key, System.Array.Empty()).Build(); + var n = client.Localize(Culture).ImageUrl(new Uri(Key), []).Build(); Assert.Equal(Value, n.ImageUrl); } @@ -62,9 +61,9 @@ public void Localizes_ImageUrl_correctly() [Fact] public void Does_not_localize_raw_url() { - const string Value = "raw image url"; + const string Value = "https://example.com/image.jpg"; - var n = client.Localize(Culture).RawImageUrl(Value).Build(); + var n = client.Localize(Culture).RawImageUrl(new Uri(Value)).Build(); Assert.Equal(Value, n.ImageUrl); } diff --git a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientTests.cs b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientTests.cs index c84ee0452..473173e5b 100644 --- a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientTests.cs +++ b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/FCMClientTests.cs @@ -16,12 +16,11 @@ public class FCMClientTests FirebaseConfiguration.Prepare(Key) ); - private readonly StubStore store; private readonly FCMClient client; public FCMClientTests() { - store = new StubStore(UserId, Token); + var store = new StubStore(UserId, Token); client = new FCMClient(Messaging, store, Substitute.For()); } diff --git a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/NotificationConversionTests.cs b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/NotificationConversionTests.cs index d3c21ca98..3b53132b6 100644 --- a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/NotificationConversionTests.cs +++ b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/NotificationConversionTests.cs @@ -45,12 +45,14 @@ public void Applies_custom_value_formatters_for_nullable_types() data.Should().ContainKey("Date").WhoseValue.Should().Be("2024-09-25T13:56:48.0000000+02:00"); } + // ReSharper disable once UnusedMember.Local private enum IntEnum { First = 0, Second = 1, } + // ReSharper disable once UnusedMember.Local private enum ByteEnum : byte { First = 0, diff --git a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/StubStore.cs b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/StubStore.cs index b73545ec8..80193cb49 100644 --- a/test/Infrastructure/LeanCode.Firebase.FCM.Tests/StubStore.cs +++ b/test/Infrastructure/LeanCode.Firebase.FCM.Tests/StubStore.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - namespace LeanCode.Firebase.FCM.Tests; internal sealed class StubStore : IPushNotificationTokenStore diff --git a/test/Infrastructure/LeanCode.Kratos.Tests/KratosAuthenticationHandlerTests.cs b/test/Infrastructure/LeanCode.Kratos.Tests/KratosAuthenticationHandlerTests.cs index fe9f40bfa..ba92e3e87 100644 --- a/test/Infrastructure/LeanCode.Kratos.Tests/KratosAuthenticationHandlerTests.cs +++ b/test/Infrastructure/LeanCode.Kratos.Tests/KratosAuthenticationHandlerTests.cs @@ -275,7 +275,7 @@ private static (KratosAuthenticationHandler, IFrontendApi) ConfigureServices( cfg.RoleClaimType = "role"; cfg.NameClaimType = "sub"; - cfg.ClaimsExtractor = (s, o, c) => { }; + cfg.ClaimsExtractor = (_, _, _) => { }; configureAuthenticationOptions?.Invoke(cfg); }); diff --git a/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs b/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs index 1a9df81c5..22ca49c00 100644 --- a/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs +++ b/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs @@ -14,7 +14,7 @@ public class KratosWebHookHandlerTests [Fact] public async Task Responds_with_status_code_403_without_running_inner_handler_if_api_key_is_invalid() { - var handler = new KratosWebHookTestHandler(ctx => throw new UnreachableException()); + var handler = new KratosWebHookTestHandler(_ => throw new UnreachableException()); var ctx = await RunAsync(handler, new() { [handler.ApiKeyHeaderName] = Guid.NewGuid().ToString() }); Assert.Equal(403, ctx.Response.StatusCode); @@ -32,7 +32,7 @@ public async Task Runs_inner_handler_if_api_key_is_valid() [Fact] public async Task Swallows_unhandled_exceptions_thrown_by_inner_handler_and_responds_with_status_code_500() { - var handler = new KratosWebHookTestHandler(ctx => throw new InvalidOperationException()); + var handler = new KratosWebHookTestHandler(_ => throw new InvalidOperationException()); var ctx = await RunAsync(handler, new() { [handler.ApiKeyHeaderName] = ApiKey }); Assert.Equal(500, ctx.Response.StatusCode); diff --git a/test/Infrastructure/LeanCode.Localization.Tests/Infrastructure/LeanCode.Localization.Tests/ResourceManagerStringLocalizerTests.cs b/test/Infrastructure/LeanCode.Localization.Tests/Infrastructure/LeanCode.Localization.Tests/ResourceManagerStringLocalizerTests.cs index 2f24fb7da..dbdb7ed61 100644 --- a/test/Infrastructure/LeanCode.Localization.Tests/Infrastructure/LeanCode.Localization.Tests/ResourceManagerStringLocalizerTests.cs +++ b/test/Infrastructure/LeanCode.Localization.Tests/Infrastructure/LeanCode.Localization.Tests/ResourceManagerStringLocalizerTests.cs @@ -1,4 +1,3 @@ -using System; using LeanCode.Localization.StringLocalizers; using Xunit; using static System.Globalization.CultureInfo; diff --git a/test/Infrastructure/LeanCode.Logging.Tests/BaseSanitizerTests.cs b/test/Infrastructure/LeanCode.Logging.Tests/BaseSanitizerTests.cs index b4e4ceb4f..c94346e21 100644 --- a/test/Infrastructure/LeanCode.Logging.Tests/BaseSanitizerTests.cs +++ b/test/Infrastructure/LeanCode.Logging.Tests/BaseSanitizerTests.cs @@ -1,4 +1,3 @@ -using System; using NSubstitute; using Serilog.Core; using Serilog.Events; @@ -35,9 +34,7 @@ public void Calls_property_factory_when_sanitizing_object() { SanitizeRight(Payload.Workable); - factory - .Received(1) - .CreatePropertyValue(Arg.Is((Payload p) => p.Value == RightSanitizer.Result.Value), true); + factory.Received(1).CreatePropertyValue(Arg.Is((Payload p) => p.Value == RightSanitizer.Result.Value), true); } [Fact] diff --git a/test/Infrastructure/LeanCode.Mixpanel.Tests/MixpanelAnalyticsTests.cs b/test/Infrastructure/LeanCode.Mixpanel.Tests/MixpanelAnalyticsTests.cs index ee8b7a36b..50b541a69 100644 --- a/test/Infrastructure/LeanCode.Mixpanel.Tests/MixpanelAnalyticsTests.cs +++ b/test/Infrastructure/LeanCode.Mixpanel.Tests/MixpanelAnalyticsTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; using LeanCode.Test.Helpers; -using Xunit; namespace LeanCode.Mixpanel.Tests; diff --git a/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs b/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs index b16bb7194..986a38c54 100644 --- a/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs +++ b/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs @@ -1,9 +1,6 @@ -using System; using System.Globalization; -using System.Linq; using System.Text; using System.Text.Json; -using System.Threading.Tasks; using LeanCode.Localization.StringLocalizers; using LeanCode.SendGrid; using LeanCode.Test.Helpers; @@ -48,7 +45,7 @@ public SendGridRazorClientTests() .ReturnsForAnyArgs(ci => { var culture = ci.Arg(); - var cultureName = culture == CultureInfo.InvariantCulture ? "InvariantCulture" : culture.Name; + var cultureName = Equals(culture, CultureInfo.InvariantCulture) ? "InvariantCulture" : culture.Name; var keyName = ci.Arg(); return $"[{cultureName}] {keyName}"; @@ -68,8 +65,8 @@ public async Task Sends_email_correctly() .WithSender(EmailFrom, "LeanCode Tester") .WithRecipient(EmailTo) .WithSubject("email.subject.test") - .WithPlainTextContent(new EmailTextVM { }) - .WithHtmlContent(new EmailHtmlVM { }) + .WithPlainTextContent(new EmailTextVM()) + .WithHtmlContent(new EmailHtmlVM()) .WithAttachment( Convert.ToBase64String(Encoding.UTF8.GetBytes("Attachment content.")), "Attachment.txt", @@ -87,8 +84,8 @@ public async Task Throws_when_sending_failed() .WithSender(EmailFrom, "LeanCode Tester") // .WithRecipient(EmailTo) omitted on purpose to cause a failure .WithSubject("email.subject.test") - .WithPlainTextContent(new EmailTextVM { }) - .WithHtmlContent(new EmailHtmlVM { }) + .WithPlainTextContent(new EmailTextVM()) + .WithHtmlContent(new EmailHtmlVM()) .WithAttachment( Convert.ToBase64String(Encoding.UTF8.GetBytes("Attachment content.")), "Attachment.txt", @@ -104,11 +101,13 @@ public async Task Throws_when_sending_failed() ); } + // ReSharper disable once UnusedMember.Local private sealed class EmailTextVM { public string Value { get; set; } = "Text"; } + // ReSharper disable once UnusedMember.Local private sealed class EmailHtmlVM { public string Value { get; set; } = "Html"; diff --git a/test/Infrastructure/LeanCode.Serialization.Tests/JsonContentTests.cs b/test/Infrastructure/LeanCode.Serialization.Tests/JsonContentTests.cs index 0ad7ef9a7..d8b7d600e 100644 --- a/test/Infrastructure/LeanCode.Serialization.Tests/JsonContentTests.cs +++ b/test/Infrastructure/LeanCode.Serialization.Tests/JsonContentTests.cs @@ -1,7 +1,6 @@ using System.Net.Http.Json; using System.Text; using System.Text.Json; -using System.Threading.Tasks; using Xunit; namespace LeanCode.Serialization.Tests; diff --git a/test/Infrastructure/LeanCode.SmsSender.Tests/SmsSenderClientTests.cs b/test/Infrastructure/LeanCode.SmsSender.Tests/SmsSenderClientTests.cs index 79be82200..fa631e57c 100644 --- a/test/Infrastructure/LeanCode.SmsSender.Tests/SmsSenderClientTests.cs +++ b/test/Infrastructure/LeanCode.SmsSender.Tests/SmsSenderClientTests.cs @@ -1,6 +1,3 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; using LeanCode.SmsSender.Exceptions; using LeanCode.Test.Helpers; using Xunit; diff --git a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/CompiledViewsCacheTests.cs b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/CompiledViewsCacheTests.cs index f95e5e059..40c71231c 100644 --- a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/CompiledViewsCacheTests.cs +++ b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/CompiledViewsCacheTests.cs @@ -1,5 +1,3 @@ -using System.Linq; -using System.Threading.Tasks; using LeanCode.Test.Helpers; using Xunit; diff --git a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/RazorViewRendererTests.cs b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/RazorViewRendererTests.cs index ffb7450cc..d35b3b4b9 100644 --- a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/RazorViewRendererTests.cs +++ b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/RazorViewRendererTests.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using Xunit; namespace LeanCode.ViewRenderer.Razor.Tests; diff --git a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewCompilerTests.cs b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewCompilerTests.cs index 654720804..e7da7de5f 100644 --- a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewCompilerTests.cs +++ b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewCompilerTests.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; using System.Text; -using System.Threading.Tasks; using LeanCode.ViewRenderer.Razor.ViewBase; using Xunit; diff --git a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewLocatorTests.cs b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewLocatorTests.cs index 9aa4d96fd..35fca9df5 100644 --- a/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewLocatorTests.cs +++ b/test/Infrastructure/LeanCode.ViewRenderer.Razor.Tests/ViewLocatorTests.cs @@ -1,4 +1,3 @@ -using System.IO; using Xunit; namespace LeanCode.ViewRenderer.Razor.Tests; diff --git a/test/LeanCode.IntegrationTests/App/AppRoles.cs b/test/LeanCode.IntegrationTests/App/AppRoles.cs index 77b627534..ce9fa2274 100644 --- a/test/LeanCode.IntegrationTests/App/AppRoles.cs +++ b/test/LeanCode.IntegrationTests/App/AppRoles.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; using LeanCode.CQRS.Security; namespace LeanCode.IntegrationTests.App; public class AppRoles : IRoleRegistration { - public IEnumerable Roles { get; } = new Role[] { new Role("user", "user") }; + public IEnumerable Roles { get; } = [new Role("user", "user")]; } diff --git a/test/LeanCode.IntegrationTests/App/Program.cs b/test/LeanCode.IntegrationTests/App/Program.cs index d83509e96..318611d8a 100644 --- a/test/LeanCode.IntegrationTests/App/Program.cs +++ b/test/LeanCode.IntegrationTests/App/Program.cs @@ -1,6 +1,5 @@ using System.Diagnostics.CodeAnalysis; using LeanCode.AzureIdentity; -using LeanCode.Components; using LeanCode.Logging; using LeanCode.Startup.MicrosoftDI; using Microsoft.Extensions.Hosting; diff --git a/test/LeanCode.IntegrationTests/App/Startup.cs b/test/LeanCode.IntegrationTests/App/Startup.cs index 00673c23f..b7e4398b3 100644 --- a/test/LeanCode.IntegrationTests/App/Startup.cs +++ b/test/LeanCode.IntegrationTests/App/Startup.cs @@ -17,6 +17,7 @@ public class Startup : LeanStartup private static readonly TypesCatalog CQRSTypes = TypesCatalog.Of(); private readonly TestDatabaseConfig testDatabaseConfig; + // ReSharper disable once UnassignedGetOnlyAutoProperty protected override bool CloseAndFlushLogger { get; } public Startup(IConfiguration config) diff --git a/test/LeanCode.IntegrationTests/PushNotificationTokenStoreTests.cs b/test/LeanCode.IntegrationTests/PushNotificationTokenStoreTests.cs index 6943e270d..76a7dc7ff 100644 --- a/test/LeanCode.IntegrationTests/PushNotificationTokenStoreTests.cs +++ b/test/LeanCode.IntegrationTests/PushNotificationTokenStoreTests.cs @@ -1,4 +1,3 @@ -using System.Diagnostics.CodeAnalysis; using LeanCode.Firebase.FCM; using LeanCode.IntegrationTests.App; using LeanCode.Test.Helpers; @@ -10,7 +9,7 @@ namespace LeanCode.IntegrationTests; public class PushNotificationTokenStoreTests : IAsyncLifetime { private readonly TestApp app; - private AsyncServiceScope scope = default!; + private AsyncServiceScope scope; private PushNotificationTokenStore store = default!; public PushNotificationTokenStoreTests() diff --git a/test/LeanCode.IntegrationTests/TestDatabaseConfig.cs b/test/LeanCode.IntegrationTests/TestDatabaseConfig.cs index f5ce9d21f..5adf4befd 100644 --- a/test/LeanCode.IntegrationTests/TestDatabaseConfig.cs +++ b/test/LeanCode.IntegrationTests/TestDatabaseConfig.cs @@ -4,7 +4,6 @@ using MassTransit.EntityFrameworkCoreIntegration; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; -using Npgsql; namespace LeanCode.IntegrationTests; diff --git a/test/LeanCode.Test.Helpers/ExternalServiceFactAttribute.cs b/test/LeanCode.Test.Helpers/ExternalServiceFactAttribute.cs index a7042584c..0a420e5eb 100644 --- a/test/LeanCode.Test.Helpers/ExternalServiceFactAttribute.cs +++ b/test/LeanCode.Test.Helpers/ExternalServiceFactAttribute.cs @@ -10,7 +10,7 @@ public abstract class ExternalServiceFactAttribute : FactAttribute, ITraitAttrib protected abstract IReadOnlyCollection RequiredEnvVariables { get; } protected abstract string ServiceType { get; } - public ExternalServiceFactAttribute() + protected ExternalServiceFactAttribute() { Explicit = true; } diff --git a/test/LeanCode.Test.Helpers/IntegrationFactAttribute.cs b/test/LeanCode.Test.Helpers/IntegrationFactAttribute.cs index 7a0ceb69c..c9ffd2fb5 100644 --- a/test/LeanCode.Test.Helpers/IntegrationFactAttribute.cs +++ b/test/LeanCode.Test.Helpers/IntegrationFactAttribute.cs @@ -1,8 +1,10 @@ +using System.Diagnostics.CodeAnalysis; using Xunit; using Xunit.v3; namespace LeanCode.Test.Helpers; +[SuppressMessage("?", "CA1813", Justification = "The attribute is inherited by other attributes and cannot be sealed.")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class IntegrationFactAttribute : FactAttribute, ITraitAttribute { diff --git a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Command.cs b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Command.cs index 7f5d87d8a..d6116e359 100644 --- a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Command.cs +++ b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Command.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using LeanCode.Contracts; using LeanCode.CQRS.Execution; using Microsoft.AspNetCore.Http; diff --git a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/ConnectionKeeper.cs b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/ConnectionKeeper.cs index 59554c2ff..59146c6e3 100644 --- a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/ConnectionKeeper.cs +++ b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/ConnectionKeeper.cs @@ -1,5 +1,3 @@ -using System.Threading; -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; diff --git a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Query.cs b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Query.cs index 536c6dadf..70b99aeb8 100644 --- a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Query.cs +++ b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Query.cs @@ -1,5 +1,3 @@ -using System.Linq; -using System.Threading.Tasks; using LeanCode.Contracts; using LeanCode.CQRS.Execution; using Microsoft.AspNetCore.Http; diff --git a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Startup.cs b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Startup.cs index f1825a393..169c7e747 100644 --- a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Startup.cs +++ b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/App/Startup.cs @@ -11,6 +11,7 @@ namespace LeanCode.IntegrationTestHelpers.Tests.App; public class Startup : LeanStartup { + // ReSharper disable once UnassignedGetOnlyAutoProperty protected override bool CloseAndFlushLogger { get; } public Startup(IConfiguration config) @@ -38,6 +39,6 @@ protected override void ConfigureApp(IApplicationBuilder app) { app.UseRouting(); app.UseAuthentication(); - app.UseEndpoints(e => e.MapRemoteCQRS("/api", cqrs => { })); + app.UseEndpoints(e => e.MapRemoteCQRS("/api", _ => { })); } } diff --git a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestApp.cs b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestApp.cs index 7ed135f3b..4be130c74 100644 --- a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestApp.cs +++ b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestApp.cs @@ -2,12 +2,10 @@ using LeanCode.IntegrationTestHelpers.Tests.App; using LeanCode.Logging; using LeanCode.Startup.MicrosoftDI; -using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Serilog.Events; namespace LeanCode.IntegrationTestHelpers.Tests; diff --git a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestConnectionStringTests.cs b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestConnectionStringTests.cs index a5af33e43..003c82457 100644 --- a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestConnectionStringTests.cs +++ b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/TestConnectionStringTests.cs @@ -42,7 +42,7 @@ public void Final_connection_string_contains_base_connection_string() config[ConnectionStringKey].Should().Contain(BaseConnectionString); } - private IConfiguration Build(string baseConnectionString) + private static IConfiguration Build(string baseConnectionString) { var builder = new ConfigurationBuilder(); builder.Add(new ConfigurationOverrides(new() { [BaseKey] = baseConnectionString })); diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddAuthorizationAttributeCodeActionTests.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddAuthorizationAttributeCodeActionTests.cs index 2f94f56c4..5b32d9e42 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddAuthorizationAttributeCodeActionTests.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddAuthorizationAttributeCodeActionTests.cs @@ -1,5 +1,3 @@ -using System.Linq; -using System.Threading.Tasks; using LeanCode.CodeAnalysis.Analyzers; using LeanCode.CodeAnalysis.CodeFixProviders; using LeanCode.CodeAnalysis.Tests.Verifiers; diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddCommandValidatorCodeActionTests.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddCommandValidatorCodeActionTests.cs index 78b3291fc..cf4955db6 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddCommandValidatorCodeActionTests.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/CodeActions/AddCommandValidatorCodeActionTests.cs @@ -1,4 +1,3 @@ -using System.Threading.Tasks; using LeanCode.CodeAnalysis.Analyzers; using LeanCode.CodeAnalysis.CodeFixProviders; using LeanCode.CodeAnalysis.Tests.Verifiers; diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Accepted/CQRS/Validators.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Accepted/CQRS/Validators.cs index a7f6cb644..35839b057 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Accepted/CQRS/Validators.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Accepted/CQRS/Validators.cs @@ -9,13 +9,7 @@ public class ValidatorCommand : ICommand { } public class ValidatorOperation : IOperation { } -public class ValidatorCommandCV : AbstractValidator -{ - public ValidatorCommandCV() { } -} +public class ValidatorCommandCV : AbstractValidator { } // Do not raise diagnostics for classes not implementing `ICommand` interface. -public class Validator : AbstractValidator -{ - public Validator() { } -} +public class Validator : AbstractValidator { } diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Rejected/CQRS/Validators.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Rejected/CQRS/Validators.cs index 5337fe6fa..891952aed 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Rejected/CQRS/Validators.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/TestSamples/Rejected/CQRS/Validators.cs @@ -7,7 +7,4 @@ namespace LeanCode.CodeAnalysis.Tests.TestSamples.Rejected.CQRS; // to check if it implements `ICommand` interface. public class ValidatorCommand : ICommand { } -public class WrongName : AbstractValidator -{ - public WrongName() { } -} +public class WrongName : AbstractValidator { } diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/CodeFixVerifier.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/CodeFixVerifier.cs index b1ba169b1..d9ee30d5a 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/CodeFixVerifier.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/CodeFixVerifier.cs @@ -1,13 +1,7 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; -using Microsoft.CodeAnalysis.Simplification; using Xunit; namespace LeanCode.CodeAnalysis.Tests.Verifiers; @@ -39,7 +33,7 @@ params string[] additionalSources var context = new CodeFixContext( document, analyzerDiagnostics[0], - (a, d) => actions.Add(a), + (a, _) => actions.Add(a), CancellationToken.None ); await codeFixProvider.RegisterCodeFixesAsync(context); @@ -54,7 +48,8 @@ params string[] additionalSources document = await ApplyFix(document, actions[(int)fixToApply]); } - var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnostics(document)); + var compilerDiagnosticsList = compilerDiagnostics.ToList(); + var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnosticsList, await GetCompilerDiagnostics(document)); if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { @@ -65,7 +60,7 @@ await document.GetSyntaxRootAsync(), document.Project.Solution.Workspace ) ); - newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnostics(document)); + newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnosticsList, await GetCompilerDiagnostics(document)); throw new Xunit.Sdk.XunitException( string.Format( diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticResult.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticResult.cs index 1cf926789..27954c34b 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticResult.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticResult.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.CodeAnalysis; namespace LeanCode.CodeAnalysis.Tests.Verifiers; diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs index 432fec95b..c470bfe88 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs @@ -121,7 +121,7 @@ private Project CreateProject(string[] sources) return solution.GetProject(projectId); } - private static readonly MetadataReference[] CommonReferences = new[] + private static readonly MetadataReference[] CommonReferences = { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(ICommand).Assembly.Location),