From c3fb8ceff97c5dec0fd46d0e277ebbdff082263f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Fija=C5=82kowski?= Date: Fri, 9 Feb 2024 11:32:56 +0100 Subject: [PATCH] Update packages and reformat code with newer CSharpier --- .config/dotnet-tools.json | 2 +- Directory.Build.targets | 30 +-- .../Local/Context/NullHeaderDictionary.cs | 4 +- .../Context/NullRequestCookieCollection.cs | 2 +- .../Local/Context/NullSession.cs | 2 +- .../Local/Context/NullWebSocketManager.cs | 2 +- .../ObjectExecutorFactory.cs | 3 +- .../CQRSApiDescriptionProvider.cs | 200 ++++++++---------- .../CQRSObjectsRegistrationSource.cs | 70 +++--- .../ServiceCollectionCQRSExtensions.cs | 25 ++- ...TransitRelayServiceCollectionExtensions.cs | 11 +- .../Middleware/EventsPublisherMiddleware.cs | 4 +- .../ClaimsPrincipalExtensions.cs | 6 +- .../ServiceCollectionExtensions.cs | 3 +- .../DbContextExtensions.cs | 3 +- .../TypedIdGenerator.cs | 60 +++--- .../LeanCode.DomainModels/Ulids/Ulid.cs | 3 +- .../LeanCode.AuditLogs/AuditLogsPublisher.cs | 25 ++- .../ChangedEntitiesExtractor.cs | 60 +++--- ...sintRegistrationConfigurationExtensions.cs | 4 +- .../LeanCode.Firebase.FCM/FCMClient.cs | 3 +- .../PushNotificationTokenStore.cs | 44 ++-- ...rverKeyVaultServiceCollectionExtensions.cs | 12 +- .../KratosAuthenticationHandler.cs | 19 +- .../IHostBuilderExtensions.cs | 27 +-- .../ActivityLogsEnricher.cs | 6 +- .../Extensions/LayoutNode.cs | 3 +- .../ViewCompiler.cs | 3 +- ...ationTokensShouldFollowNamingConvention.cs | 6 +- .../EnsureCQRSHandlersAreInProperNamespace.cs | 11 +- ...CommandValidatorsFollowNamingConvention.cs | 10 +- .../Analyzers/NamedTypeSymbolExtensions.cs | 13 +- .../SuggestCommandsHaveValidators.cs | 4 +- .../AddCommandValidatorCodeAction.cs | 7 +- .../FixCancellationTokenNamingCodeAction.cs | 5 +- .../CQRSEndpointsDataSourceTests.cs | 48 ++++- .../CQRSServicesBuilderTests.cs | 3 +- .../MiddlewareBasedLocalExecutorTests.cs | 8 +- .../MiddlewaresForLocalExecutionTests.cs | 14 +- .../Middleware/TestHelpers.cs | 3 +- .../CQRSApiDescriptionProviderTests.cs | 15 +- ...viceProviderRegistrationExtensionsTests.cs | 22 +- .../Integration/TestApp.cs | 5 +- .../CustomAuthorizerTests.cs | 4 +- ...apterWithAsyncValidatorIntegrationTests.cs | 3 +- .../CollectionExtensionsTests.cs | 3 +- .../TimestampTzExpressionInterceptorTests.cs | 15 +- .../Ids/ValidConstructTests.cs | 160 +++++++------- .../Model/TimestampTzTests.cs | 3 +- .../UserIdExtractorsRegistrationTests.cs | 12 +- .../UserIdExtractorsTests.cs | 2 +- .../AuditLogsIntegrationTests.cs | 25 +-- .../ChangedEntititesExtractorTests.cs | 9 +- .../LeanCode.AuditLogs.Tests/TestDbContext.cs | 4 +- .../AzureStorageAuditLogIntegrationTests.cs | 6 +- .../KratosWebHookHandlerTests.cs | 4 +- .../SendGridRazorClientTests.cs | 15 +- test/LeanCode.IntegrationTests/App/CQRS.cs | 3 +- test/LeanCode.IntegrationTests/App/Startup.cs | 22 +- test/LeanCode.IntegrationTests/CQRSTests.cs | 7 +- .../TimestampTzTests.cs | 10 +- .../Tests.cs | 3 +- .../Verifiers/DiagnosticVerifier.cs | 5 +- 63 files changed, 524 insertions(+), 601 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index b3fd44b71..5e95da1e0 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "csharpier": { - "version": "0.26.1", + "version": "0.27.2", "commands": [ "dotnet-csharpier" ] diff --git a/Directory.Build.targets b/Directory.Build.targets index 021e1fc20..22fb937e9 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -6,7 +6,7 @@ 4.1.2 8.1.3 - 7.1.2 + 7.3.1 @@ -25,12 +25,12 @@ - - + + - + @@ -48,19 +48,19 @@ - + - + - + - - + + @@ -85,7 +85,7 @@ - + @@ -99,7 +99,7 @@ - + @@ -109,7 +109,7 @@ - + @@ -132,8 +132,8 @@ - - + + @@ -142,4 +142,4 @@ $(MSBuildThisFileDirectory) $(CodeAnalysisSettingsLocation)LeanCode.CodeAnalysis.ruleset - \ No newline at end of file + diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullHeaderDictionary.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullHeaderDictionary.cs index b7824e341..ca3625d22 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullHeaderDictionary.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullHeaderDictionary.cs @@ -21,9 +21,9 @@ public long? ContentLength set { } } - public ICollection Keys { get; } = new ReadOnlyCollection([ ]); + public ICollection Keys { get; } = new ReadOnlyCollection([]); - public ICollection Values { get; } = new ReadOnlyCollection([ ]); + public ICollection Values { get; } = new ReadOnlyCollection([]); public int Count => 0; diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullRequestCookieCollection.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullRequestCookieCollection.cs index 254bc9f51..1bea0e670 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullRequestCookieCollection.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullRequestCookieCollection.cs @@ -12,7 +12,7 @@ internal class NullRequestCookieCollection : IRequestCookieCollection public int Count => 0; - public ICollection Keys => [ ]; + public ICollection Keys => []; private NullRequestCookieCollection() { } diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullSession.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullSession.cs index 84cd9bc30..32591a9bc 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullSession.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullSession.cs @@ -11,7 +11,7 @@ internal class NullSession : ISession public string Id => ""; - public IEnumerable Keys => [ ]; + public IEnumerable Keys => []; private NullSession() { } diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullWebSocketManager.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullWebSocketManager.cs index 5fcf46cf1..c98640e04 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullWebSocketManager.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Local/Context/NullWebSocketManager.cs @@ -10,7 +10,7 @@ internal class NullWebSocketManager : WebSocketManager public override bool IsWebSocketRequest => false; - public override IList WebSocketRequestedProtocols { get; } = new ReadOnlyCollection([ ]); + public override IList WebSocketRequestedProtocols { get; } = new ReadOnlyCollection([]); private NullWebSocketManager() { } diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/ObjectExecutorFactory.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/ObjectExecutorFactory.cs index 0b22aa095..578bfe1b3 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/ObjectExecutorFactory.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/ObjectExecutorFactory.cs @@ -49,8 +49,7 @@ Type GetResultType(Type interfaceType) => objectType .GetInterfaces() .Single(i => i.IsConstructedGenericType && i.GetGenericTypeDefinition() == interfaceType) - .GenericTypeArguments - .First(); + .GenericTypeArguments.First(); } private static async Task ExecuteOperationAsync( diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs index f771994e6..1b5354379 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSApiDescriptionProvider.cs @@ -91,134 +91,114 @@ private static string BuildPath(RoutePattern pattern) private static void DefineCommand(CQRSObjectMetadata metadata, ApiDescription apiDescription) { - apiDescription - .ParameterDescriptions - .Add( - new() - { - IsRequired = true, - Source = BindingSource.Body, - Type = metadata.ObjectType, - ModelMetadata = CreateModelMetadata(metadata.ObjectType), - } - ); + apiDescription.ParameterDescriptions.Add( + new() + { + IsRequired = true, + Source = BindingSource.Body, + Type = metadata.ObjectType, + ModelMetadata = CreateModelMetadata(metadata.ObjectType), + } + ); - apiDescription - .SupportedResponseTypes - .Add( - new() - { - ModelMetadata = CreateModelMetadata(typeof(CommandResult)), - ApiResponseFormats = [ new() { MediaType = ApplicationJson } ], - StatusCode = 200, - Type = typeof(CommandResult), - } - ); + apiDescription.SupportedResponseTypes.Add( + new() + { + ModelMetadata = CreateModelMetadata(typeof(CommandResult)), + ApiResponseFormats = [new() { MediaType = ApplicationJson }], + StatusCode = 200, + Type = typeof(CommandResult), + } + ); - apiDescription - .SupportedResponseTypes - .Add( - new() - { - ModelMetadata = CreateModelMetadata(typeof(CommandResult)), - ApiResponseFormats = [ new() { MediaType = ApplicationJson } ], - StatusCode = 422, - Type = typeof(CommandResult), - } - ); + apiDescription.SupportedResponseTypes.Add( + new() + { + ModelMetadata = CreateModelMetadata(typeof(CommandResult)), + ApiResponseFormats = [new() { MediaType = ApplicationJson }], + StatusCode = 422, + Type = typeof(CommandResult), + } + ); } private static void DefineQuery(CQRSObjectMetadata metadata, ApiDescription apiDescription) { - apiDescription - .ParameterDescriptions - .Add( - new() - { - IsRequired = true, - Source = BindingSource.Body, - Type = metadata.ObjectType, - ModelMetadata = CreateModelMetadata(metadata.ObjectType), - } - ); + apiDescription.ParameterDescriptions.Add( + new() + { + IsRequired = true, + Source = BindingSource.Body, + Type = metadata.ObjectType, + ModelMetadata = CreateModelMetadata(metadata.ObjectType), + } + ); - apiDescription - .SupportedResponseTypes - .Add( - new() - { - ModelMetadata = CreateModelMetadata(metadata.ResultType), - ApiResponseFormats = [ new() { MediaType = ApplicationJson } ], - StatusCode = 200, - Type = metadata.ResultType, - } - ); + apiDescription.SupportedResponseTypes.Add( + new() + { + ModelMetadata = CreateModelMetadata(metadata.ResultType), + ApiResponseFormats = [new() { MediaType = ApplicationJson }], + StatusCode = 200, + Type = metadata.ResultType, + } + ); } private static void DefineOperation(CQRSObjectMetadata metadata, ApiDescription apiDescription) { - apiDescription - .ParameterDescriptions - .Add( - new() - { - IsRequired = true, - Source = BindingSource.Body, - Type = metadata.ObjectType, - ModelMetadata = CreateModelMetadata(metadata.ObjectType), - } - ); + apiDescription.ParameterDescriptions.Add( + new() + { + IsRequired = true, + Source = BindingSource.Body, + Type = metadata.ObjectType, + ModelMetadata = CreateModelMetadata(metadata.ObjectType), + } + ); - apiDescription - .SupportedResponseTypes - .Add( - new() - { - ModelMetadata = CreateModelMetadata(metadata.ResultType), - ApiResponseFormats = [ new() { MediaType = ApplicationJson } ], - StatusCode = 200, - Type = metadata.ResultType, - } - ); + apiDescription.SupportedResponseTypes.Add( + new() + { + ModelMetadata = CreateModelMetadata(metadata.ResultType), + ApiResponseFormats = [new() { MediaType = ApplicationJson }], + StatusCode = 200, + Type = metadata.ResultType, + } + ); } private static void AddCommonResponses(ApiDescription apiDescription) { - apiDescription - .SupportedResponseTypes - .Add( - new() - { - ModelMetadata = CreateModelMetadata(typeof(void)), - ApiResponseFormats = [ new() { MediaType = ApplicationJson } ], - StatusCode = 400, - Type = typeof(void), - } - ); + apiDescription.SupportedResponseTypes.Add( + new() + { + ModelMetadata = CreateModelMetadata(typeof(void)), + ApiResponseFormats = [new() { MediaType = ApplicationJson }], + StatusCode = 400, + Type = typeof(void), + } + ); - apiDescription - .SupportedResponseTypes - .Add( - new() - { - ModelMetadata = CreateModelMetadata(typeof(void)), - ApiResponseFormats = [ new() { MediaType = ApplicationJson } ], - StatusCode = 401, - Type = typeof(void), - } - ); + apiDescription.SupportedResponseTypes.Add( + new() + { + ModelMetadata = CreateModelMetadata(typeof(void)), + ApiResponseFormats = [new() { MediaType = ApplicationJson }], + StatusCode = 401, + Type = typeof(void), + } + ); - apiDescription - .SupportedResponseTypes - .Add( - new() - { - ModelMetadata = CreateModelMetadata(typeof(void)), - ApiResponseFormats = [ new() { MediaType = ApplicationJson } ], - StatusCode = 403, - Type = typeof(void), - } - ); + apiDescription.SupportedResponseTypes.Add( + new() + { + ModelMetadata = CreateModelMetadata(typeof(void)), + ApiResponseFormats = [new() { MediaType = ApplicationJson }], + StatusCode = 403, + Type = typeof(void), + } + ); } private static CQRSBodyModelMetadata CreateModelMetadata(Type type) => new(ModelMetadataIdentity.ForType(type)); diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs index 84943b56a..d9f1fc5c3 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/Registration/CQRSObjectsRegistrationSource.cs @@ -29,13 +29,11 @@ public CQRSObjectsRegistrationSource(IServiceCollection services, IObjectExecuto public void AddCQRSObjects(TypesCatalog contractsCatalog, TypesCatalog handlersCatalog) { var contracts = contractsCatalog - .Assemblies - .SelectMany(a => a.DefinedTypes) + .Assemblies.SelectMany(a => a.DefinedTypes) .Where(t => IsCommand(t) || IsQuery(t) || IsOperation(t)); var handlers = handlersCatalog - .Assemblies - .SelectMany(a => a.DefinedTypes) + .Assemblies.SelectMany(a => a.DefinedTypes) .SelectMany(EnumerateHandledObjects) .ToLookup(h => h.ObjectType); @@ -105,8 +103,8 @@ private FrozenDictionary BuildMetadata() private static bool ValidateContractType(TypeInfo type) { - var implementedContractInterfaces = type.ImplementedInterfaces.Where( - i => IsGenericType(i, typeof(IQuery<>)) || i == typeof(ICommand) || IsGenericType(i, typeof(IOperation<>)) + var implementedContractInterfaces = type.ImplementedInterfaces.Where(i => + IsGenericType(i, typeof(IQuery<>)) || i == typeof(ICommand) || IsGenericType(i, typeof(IOperation<>)) ); return implementedContractInterfaces.Count() == 1; @@ -114,36 +112,32 @@ private static bool ValidateContractType(TypeInfo type) private static IEnumerable EnumerateHandledObjects(TypeInfo t) { - var handledQueries = t.ImplementedInterfaces - .Where(qh => IsGenericType(qh, typeof(IQueryHandler<,>))) - .Select( - qh => - new HandlerDefinition( - CQRSObjectKind.Query, - t, - qh.GenericTypeArguments[0], - qh.GenericTypeArguments[1] - ) - ); - - var handledCommands = t.ImplementedInterfaces - .Where(ch => IsGenericType(ch, typeof(ICommandHandler<>))) - .Select( - ch => - new HandlerDefinition(CQRSObjectKind.Command, t, ch.GenericTypeArguments[0], typeof(CommandResult)) - ); - - var handledOperations = t.ImplementedInterfaces - .Where(oh => IsGenericType(oh, typeof(IOperationHandler<,>))) - .Select( - oh => - new HandlerDefinition( - CQRSObjectKind.Operation, - t, - oh.GenericTypeArguments[0], - oh.GenericTypeArguments[1] - ) - ); + var handledQueries = t + .ImplementedInterfaces.Where(qh => IsGenericType(qh, typeof(IQueryHandler<,>))) + .Select(qh => new HandlerDefinition( + CQRSObjectKind.Query, + t, + qh.GenericTypeArguments[0], + qh.GenericTypeArguments[1] + )); + + var handledCommands = t + .ImplementedInterfaces.Where(ch => IsGenericType(ch, typeof(ICommandHandler<>))) + .Select(ch => new HandlerDefinition( + CQRSObjectKind.Command, + t, + ch.GenericTypeArguments[0], + typeof(CommandResult) + )); + + var handledOperations = t + .ImplementedInterfaces.Where(oh => IsGenericType(oh, typeof(IOperationHandler<,>))) + .Select(oh => new HandlerDefinition( + CQRSObjectKind.Operation, + t, + oh.GenericTypeArguments[0], + oh.GenericTypeArguments[1] + )); return handledQueries.Concat(handledCommands).Concat(handledOperations); } @@ -164,8 +158,8 @@ private static bool IsOperation(TypeInfo type) } private static bool ImplementsGenericType(TypeInfo type, Type implementedType) => - type.ImplementedInterfaces.Any( - i => i.IsConstructedGenericType && i.GetGenericTypeDefinition() == implementedType + type.ImplementedInterfaces.Any(i => + i.IsConstructedGenericType && i.GetGenericTypeDefinition() == implementedType ); private static bool IsGenericType(Type type, Type genericType) diff --git a/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs b/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs index 49be97769..f385392b8 100644 --- a/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.AspNetCore/ServiceCollectionCQRSExtensions.cs @@ -92,26 +92,31 @@ public CQRSServicesBuilder AddOperation() public CQRSServicesBuilder WithLocalCommands(Action configure) { - Services.AddSingleton( - s => new Local.MiddlewareBasedLocalCommandExecutor(s, s.GetRequiredService(), configure) - ); + Services.AddSingleton(s => new Local.MiddlewareBasedLocalCommandExecutor( + s, + s.GetRequiredService(), + configure + )); return this; } public CQRSServicesBuilder WithLocalQueries(Action configure) { - Services.AddSingleton( - s => new Local.MiddlewareBasedLocalQueryExecutor(s, s.GetRequiredService(), configure) - ); + Services.AddSingleton(s => new Local.MiddlewareBasedLocalQueryExecutor( + s, + s.GetRequiredService(), + configure + )); return this; } public CQRSServicesBuilder WithLocalOperations(Action configure) { - Services.AddSingleton( - s => - new Local.MiddlewareBasedLocalOperationExecutor(s, s.GetRequiredService(), configure) - ); + Services.AddSingleton(s => new Local.MiddlewareBasedLocalOperationExecutor( + s, + s.GetRequiredService(), + configure + )); return this; } diff --git a/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRelayServiceCollectionExtensions.cs b/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRelayServiceCollectionExtensions.cs index cd1c1d45d..6e068c63f 100644 --- a/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRelayServiceCollectionExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.MassTransitRelay/MassTransitRelayServiceCollectionExtensions.cs @@ -41,12 +41,11 @@ public static void AddBusActivityMonitor( bool initializeAtStartup = true ) { - services.AddSingleton( - sp => - ResettableBusActivityMonitor.CreateFor( - sp.GetRequiredService(), - inactivityWaitTime ?? TimeSpan.FromSeconds(1) - ) + services.AddSingleton(sp => + ResettableBusActivityMonitor.CreateFor( + sp.GetRequiredService(), + inactivityWaitTime ?? TimeSpan.FromSeconds(1) + ) ); services.AddSingleton(sp => sp.GetRequiredService()); diff --git a/src/CQRS/LeanCode.CQRS.MassTransitRelay/Middleware/EventsPublisherMiddleware.cs b/src/CQRS/LeanCode.CQRS.MassTransitRelay/Middleware/EventsPublisherMiddleware.cs index a0e2166ac..1c764e2ab 100644 --- a/src/CQRS/LeanCode.CQRS.MassTransitRelay/Middleware/EventsPublisherMiddleware.cs +++ b/src/CQRS/LeanCode.CQRS.MassTransitRelay/Middleware/EventsPublisherMiddleware.cs @@ -35,8 +35,8 @@ CancellationToken cancellationToken logger.Debug("Publishing {Count} raised events", events.Count); var conversationId = Guid.NewGuid(); - var publishTasks = events.Select( - evt => PublishEventAsync(publishEndpoint, evt, conversationId, cancellationToken) + var publishTasks = events.Select(evt => + PublishEventAsync(publishEndpoint, evt, conversationId, cancellationToken) ); return Task.WhenAll(publishTasks); diff --git a/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs b/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs index e6054f813..ff4d8cbf7 100644 --- a/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs +++ b/src/CQRS/LeanCode.CQRS.Security/ClaimsPrincipalExtensions.cs @@ -11,8 +11,8 @@ public static bool HasPermission( params string[] permissions ) { - return registry - .All - .Any(role => claimsPrincipal.IsInRole(role.Name) && permissions.Any(role.Permissions.Contains)); + return registry.All.Any(role => + claimsPrincipal.IsInRole(role.Name) && permissions.Any(role.Permissions.Contains) + ); } } diff --git a/src/Core/LeanCode.Components/ServiceCollectionExtensions.cs b/src/Core/LeanCode.Components/ServiceCollectionExtensions.cs index 0f98a162c..b71aff3ed 100644 --- a/src/Core/LeanCode.Components/ServiceCollectionExtensions.cs +++ b/src/Core/LeanCode.Components/ServiceCollectionExtensions.cs @@ -19,8 +19,7 @@ ServiceLifetime lifetime } var implementationTypes = catalog - .Assemblies - .SelectMany(a => a.DefinedTypes) + .Assemblies.SelectMany(a => a.DefinedTypes) .Where(IsConcrete) .Select(type => new { Type = type, ImplementedServices = GetImplementedGenericTypes(type, genericType), }) .Where(t => t.ImplementedServices.Any()); diff --git a/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs b/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs index 8c95d4297..16e1beebe 100644 --- a/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs +++ b/src/Domain/LeanCode.DomainModels.EF/DbContextExtensions.cs @@ -9,8 +9,7 @@ public static class DbContextExtensions public static void SoftDeleteItems(this DbContext dbContext) { var softDeletables = dbContext - .ChangeTracker - .Entries() + .ChangeTracker.Entries() .Where(p => p.State == EntityState.Deleted && p.Entity is ISoftDeletable); foreach (var entry in softDeletables) diff --git a/src/Domain/LeanCode.DomainModels.Generators/TypedIdGenerator.cs b/src/Domain/LeanCode.DomainModels.Generators/TypedIdGenerator.cs index fcd189d28..e34fe0d37 100644 --- a/src/Domain/LeanCode.DomainModels.Generators/TypedIdGenerator.cs +++ b/src/Domain/LeanCode.DomainModels.Generators/TypedIdGenerator.cs @@ -23,40 +23,32 @@ public sealed class TypedIdGenerator : IIncrementalGenerator public void Initialize(IncrementalGeneratorInitializationContext context) { - var src = context - .SyntaxProvider - .ForAttributeWithMetadataName( - AttributeName, - static (n, _) => n is TypeDeclarationSyntax, - static (n, _) => - { - var attribute = n.Attributes.First(a => a.AttributeClass?.Name == "TypedIdAttribute"); - var idFormat = Convert.ToInt32( - attribute.ConstructorArguments.First().Value!, - CultureInfo.InvariantCulture - ); - var customPrefix = attribute - .NamedArguments - .FirstOrDefault(a => a.Key == CustomPrefixField) - .Value - .Value; - var skipRandomGenerator = attribute - .NamedArguments - .FirstOrDefault(a => a.Key == SkipRandomGeneratorField) - .Value - .Value; - var isValid = IsValidSyntaxNode(n.TargetNode); - return new TypedIdData( - (TypedIdFormat)idFormat, - n.TargetSymbol.ContainingNamespace.ToDisplayString(), - n.TargetSymbol.Name, - (string?)customPrefix, - skipRandomGenerator is true, - isValid, - !isValid ? n.TargetNode.GetLocation() : null - ); - } - ); + var src = context.SyntaxProvider.ForAttributeWithMetadataName( + AttributeName, + static (n, _) => n is TypeDeclarationSyntax, + static (n, _) => + { + var attribute = n.Attributes.First(a => a.AttributeClass?.Name == "TypedIdAttribute"); + var idFormat = Convert.ToInt32( + attribute.ConstructorArguments.First().Value!, + CultureInfo.InvariantCulture + ); + var customPrefix = attribute.NamedArguments.FirstOrDefault(a => a.Key == CustomPrefixField).Value.Value; + var skipRandomGenerator = attribute + .NamedArguments.FirstOrDefault(a => a.Key == SkipRandomGeneratorField) + .Value.Value; + var isValid = IsValidSyntaxNode(n.TargetNode); + return new TypedIdData( + (TypedIdFormat)idFormat, + n.TargetSymbol.ContainingNamespace.ToDisplayString(), + n.TargetSymbol.Name, + (string?)customPrefix, + skipRandomGenerator is true, + isValid, + !isValid ? n.TargetNode.GetLocation() : null + ); + } + ); context.RegisterSourceOutput( src, diff --git a/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs b/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs index 7aa7f21b4..f72302129 100644 --- a/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs +++ b/src/Domain/LeanCode.DomainModels/Ulids/Ulid.cs @@ -53,8 +53,7 @@ public readonly record struct Ulid // https://en.wikipedia.org/wiki/Base32 private static readonly ImmutableArray Base32Text = "0123456789ABCDEFGHJKMNPQRSTVWXYZ".ToImmutableArray(); private static readonly ImmutableArray Base32Bytes = Encoding - .UTF8 - .GetBytes(Base32Text.ToArray()) + .UTF8.GetBytes(Base32Text.ToArray()) .ToImmutableArray(); private static readonly ImmutableArray CharToBase32 = new byte[] diff --git a/src/Infrastructure/LeanCode.AuditLogs/AuditLogsPublisher.cs b/src/Infrastructure/LeanCode.AuditLogs/AuditLogsPublisher.cs index c25ac6345..2bd88d6aa 100644 --- a/src/Infrastructure/LeanCode.AuditLogs/AuditLogsPublisher.cs +++ b/src/Infrastructure/LeanCode.AuditLogs/AuditLogsPublisher.cs @@ -22,19 +22,18 @@ CancellationToken cancellationToken var now = Time.NowWithOffset; await Task.WhenAll( - entitiesChanged.Select( - e => - bus.Publish( - new AuditLogMessage( - e, - actionName, - now, - actorId, - Activity.Current?.TraceId.ToString(), - Activity.Current?.SpanId.ToString() - ), - cancellationToken - ) + entitiesChanged.Select(e => + bus.Publish( + new AuditLogMessage( + e, + actionName, + now, + actorId, + Activity.Current?.TraceId.ToString(), + Activity.Current?.SpanId.ToString() + ), + cancellationToken + ) ) ); } diff --git a/src/Infrastructure/LeanCode.AuditLogs/ChangedEntitiesExtractor.cs b/src/Infrastructure/LeanCode.AuditLogs/ChangedEntitiesExtractor.cs index d4cd833c6..ae5bd4803 100644 --- a/src/Infrastructure/LeanCode.AuditLogs/ChangedEntitiesExtractor.cs +++ b/src/Infrastructure/LeanCode.AuditLogs/ChangedEntitiesExtractor.cs @@ -18,44 +18,32 @@ public static class ChangedEntitiesExtractor public static IReadOnlyList Extract(DbContext dbContext) { return dbContext - .ChangeTracker - .Entries() + .ChangeTracker.Entries() .Where(e => e.State != EntityState.Unchanged && e.State != EntityState.Detached) - .Select( - e => - new EntityData( - // This method does not extract key name for owned properties - we are ok with it since the - // focus of this feature is to extract root entities. - e.Metadata - .FindPrimaryKey()! - .Properties - .Select( - p => - // This may lose some info comparing to JsonSerializer.Serialize , but we don't get - // values in unnecessary "". We accept this tradeoff - p.PropertyInfo?.GetValue(e.Entity, null)?.ToString() - ?? "Cannot extract key property" - ) - .ToList(), - e.Metadata.ClrType.ToString(), - JsonSerializer.SerializeToDocument(e.Entity, Options), - JsonSerializer.SerializeToDocument( - e.Properties - .Where(p => p.Metadata.IsShadowProperty()) - .Select( - p => - new - { - p.Metadata.Name, - p.OriginalValue, - p.CurrentValue - } - ), - Options - ), - e.State.ToString() + .Select(e => new EntityData( + // This method does not extract key name for owned properties - we are ok with it since the + // focus of this feature is to extract root entities. + e.Metadata.FindPrimaryKey()! + .Properties.Select(p => + // This may lose some info comparing to JsonSerializer.Serialize , but we don't get + // values in unnecessary "". We accept this tradeoff + p.PropertyInfo?.GetValue(e.Entity, null)?.ToString() ?? "Cannot extract key property" ) - ) + .ToList(), + e.Metadata.ClrType.ToString(), + JsonSerializer.SerializeToDocument(e.Entity, Options), + JsonSerializer.SerializeToDocument( + e.Properties.Where(p => p.Metadata.IsShadowProperty()) + .Select(p => new + { + p.Metadata.Name, + p.OriginalValue, + p.CurrentValue + }), + Options + ), + e.State.ToString() + )) .ToList(); } } diff --git a/src/Infrastructure/LeanCode.AuditLogs/MassTransintRegistrationConfigurationExtensions.cs b/src/Infrastructure/LeanCode.AuditLogs/MassTransintRegistrationConfigurationExtensions.cs index 08d5b27ef..bc62dee71 100644 --- a/src/Infrastructure/LeanCode.AuditLogs/MassTransintRegistrationConfigurationExtensions.cs +++ b/src/Infrastructure/LeanCode.AuditLogs/MassTransintRegistrationConfigurationExtensions.cs @@ -23,8 +23,8 @@ protected override void ConfigureConsumer( IRegistrationContext context ) { - endpointConfigurator.UseMessageRetry( - r => r.Immediate(1).Incremental(3, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)) + endpointConfigurator.UseMessageRetry(r => + r.Immediate(1).Incremental(3, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)) ); } } diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs b/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs index 850e4fd78..0703d6270 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/FCMClient.cs @@ -135,8 +135,7 @@ CancellationToken cancellationToken { // Remove the leftover tokens var tokensToRemove = response - .Responses - .Zip(tokensUsed) + .Responses.Zip(tokensUsed) .Where(ShouldTokenBeRemoved) .Select(p => p.Second) .ToList(); diff --git a/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs b/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs index 90e0324e3..d889c1b38 100644 --- a/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs +++ b/src/Infrastructure/LeanCode.Firebase.FCM/PushNotificationTokenStore.cs @@ -68,29 +68,27 @@ public async Task AddUserTokenAsync(TUserId userId, string newToken, Cancellatio var dateCreatedColumn = GetTokensColumnName(nameof(PushNotificationTokenEntity.DateCreated)); // perform an upsert using SQL merge, ensuring that given token is assigned to our user and no-one else - await dbContext - .Database - .ExecuteSqlInterpolatedAsync( - FormattableStringFactory.Create( - $$""" - MERGE INTO {{tokensTable}} "pt" - USING ( - VALUES ({0}, {1}, {2}) - ) AS "nt" ("UserId", "Token", "DateCreated") - ON "nt"."Token" = "pt".{{tokenColumn}} - WHEN MATCHED THEN - UPDATE SET {{userIdColumn}} = "nt"."UserId", - {{dateCreatedColumn}} = "nt"."DateCreated" - WHEN NOT MATCHED THEN - INSERT ({{userIdColumn}}, {{tokenColumn}}, {{dateCreatedColumn}}) - VALUES ("nt"."UserId", "nt"."Token", "nt"."DateCreated"); - """, - userId, - newToken, - TimeProvider.Time.UtcNow - ), - cancellationToken - ); + await dbContext.Database.ExecuteSqlInterpolatedAsync( + FormattableStringFactory.Create( + $$""" + MERGE INTO {{tokensTable}} "pt" + USING ( + VALUES ({0}, {1}, {2}) + ) AS "nt" ("UserId", "Token", "DateCreated") + ON "nt"."Token" = "pt".{{tokenColumn}} + WHEN MATCHED THEN + UPDATE SET {{userIdColumn}} = "nt"."UserId", + {{dateCreatedColumn}} = "nt"."DateCreated" + WHEN NOT MATCHED THEN + INSERT ({{userIdColumn}}, {{tokenColumn}}, {{dateCreatedColumn}}) + VALUES ("nt"."UserId", "nt"."Token", "nt"."DateCreated"); + """, + userId, + newToken, + TimeProvider.Time.UtcNow + ), + cancellationToken + ); logger.Information("Added push notification token for user {UserId} to the store", userId); diff --git a/src/Infrastructure/LeanCode.IdentityServer.KeyVault/IdentityServerKeyVaultServiceCollectionExtensions.cs b/src/Infrastructure/LeanCode.IdentityServer.KeyVault/IdentityServerKeyVaultServiceCollectionExtensions.cs index fd5ed8aed..e4e98b08a 100644 --- a/src/Infrastructure/LeanCode.IdentityServer.KeyVault/IdentityServerKeyVaultServiceCollectionExtensions.cs +++ b/src/Infrastructure/LeanCode.IdentityServer.KeyVault/IdentityServerKeyVaultServiceCollectionExtensions.cs @@ -18,14 +18,10 @@ Uri signingKeyUrl { services.TryAddTransient(); services.TryAddSingleton(); - services.TryAddSingleton( - ctx => - new SigningService( - ctx.GetRequiredService(), - ctx.GetRequiredService>() - .CreateClient(TokenSigningKeyClientName) - ) - ); + services.TryAddSingleton(ctx => new SigningService( + ctx.GetRequiredService(), + ctx.GetRequiredService>().CreateClient(TokenSigningKeyClientName) + )); services.AddAzureClients(cfg => { diff --git a/src/Infrastructure/LeanCode.Kratos/KratosAuthenticationHandler.cs b/src/Infrastructure/LeanCode.Kratos/KratosAuthenticationHandler.cs index 67e41323c..facaa9abf 100644 --- a/src/Infrastructure/LeanCode.Kratos/KratosAuthenticationHandler.cs +++ b/src/Infrastructure/LeanCode.Kratos/KratosAuthenticationHandler.cs @@ -141,16 +141,15 @@ private static ImmutableDictionary ExtractEnumNames< { return Enum.GetValues() .Distinct() - .Select( - v => - ( - Value: v, - Name: ( - typeof(T) - .GetField(v.ToString(), BindingFlags.Public | BindingFlags.Static) - ?.GetCustomAttribute(typeof(EnumMemberAttribute)) as EnumMemberAttribute - )?.Value - ) + .Select(v => + ( + Value: v, + Name: ( + typeof(T) + .GetField(v.ToString(), BindingFlags.Public | BindingFlags.Static) + ?.GetCustomAttribute(typeof(EnumMemberAttribute)) as EnumMemberAttribute + )?.Value + ) ) .Where(t => t.Name is not null) .ToImmutableDictionary(t => t.Value, t => t.Name!); diff --git a/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs b/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs index 84a584cc9..6bc4e0131 100644 --- a/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs +++ b/src/Infrastructure/LeanCode.Logging/IHostBuilderExtensions.cs @@ -49,16 +49,11 @@ public static IHostBuilder ConfigureDefaultLogging( var minLogLevel = configuration.GetValue(MinimumLogLevelKey, LogEventLevel.Verbose); var loggerConfiguration = new LoggerConfiguration() - .ReadFrom - .Configuration(configuration) - .Enrich - .FromLogContext() - .Enrich - .WithProperty("project", projectName) - .Enrich - .WithProperty("app_name", appName) - .MinimumLevel - .Is(minLogLevel) + .ReadFrom.Configuration(configuration) + .Enrich.FromLogContext() + .Enrich.WithProperty("project", projectName) + .Enrich.WithProperty("app_name", appName) + .MinimumLevel.Is(minLogLevel) .DestructureCommonObjects(destructurers); if (!configuration.GetValue(EnableDetailedInternalLogsKey)) @@ -66,14 +61,10 @@ public static IHostBuilder ConfigureDefaultLogging( var internalLogLevel = minLogLevel > InternalDefaultLogLevel ? minLogLevel : InternalDefaultLogLevel; loggerConfiguration - .MinimumLevel - .Override("Microsoft", internalLogLevel) - .MinimumLevel - .Override("System", internalLogLevel) - .MinimumLevel - .Override("Azure.Identity", internalLogLevel) - .MinimumLevel - .Override("Azure.Core", internalLogLevel); + .MinimumLevel.Override("Microsoft", internalLogLevel) + .MinimumLevel.Override("System", internalLogLevel) + .MinimumLevel.Override("Azure.Identity", internalLogLevel) + .MinimumLevel.Override("Azure.Core", internalLogLevel); } if (configuration.GetValue(SeqEndpointKey) is string seqEndpoint) diff --git a/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs b/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs index c0b0dd7b8..2f80ad05d 100644 --- a/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs +++ b/src/Infrastructure/LeanCode.OpenTelemetry/ActivityLogsEnricher.cs @@ -32,12 +32,10 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) if (useDatadogFormat) { var traceIdStr = activity - .TraceId - .ToDatadogFormat() + .TraceId.ToDatadogFormat() .ToString(System.Globalization.CultureInfo.InvariantCulture); var spanIdStr = activity - .SpanId - .ToDatadogFormat() + .SpanId.ToDatadogFormat() .ToString(System.Globalization.CultureInfo.InvariantCulture); traceId = propertyFactory.CreateProperty(traceIdKey, traceIdStr); spanId = propertyFactory.CreateProperty(spanIdKey, spanIdStr); diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs index ea03daae4..95dcc7877 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/Extensions/LayoutNode.cs @@ -28,8 +28,7 @@ public override void WriteNode(CodeTarget target, CodeRenderingContext context) else { context - .CodeWriter - .Write("public static readonly string ") + .CodeWriter.Write("public static readonly string ") .Write(LayoutFieldName) .Write(" = \"") .Write(LayoutName) diff --git a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs index 99547ba70..a8b3488a8 100644 --- a/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs +++ b/src/Infrastructure/LeanCode.ViewRenderer.Razor/ViewCompiler.cs @@ -121,8 +121,7 @@ private Assembly GenerateAssembly(string fullPath, string code) if (!compilationResult.Success) { var errors = compilationResult - .Diagnostics - .Select(d => d.GetMessage(CultureInfo.InvariantCulture)) + .Diagnostics.Select(d => d.GetMessage(CultureInfo.InvariantCulture)) .ToList(); logger.Warning("Cannot emit IL to in-memory stream for view {ViewPath}, errors:", fullPath); diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/CancellationTokensShouldFollowNamingConvention.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/CancellationTokensShouldFollowNamingConvention.cs index 708d0c655..71c88907d 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/CancellationTokensShouldFollowNamingConvention.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/CancellationTokensShouldFollowNamingConvention.cs @@ -38,9 +38,9 @@ private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) // Skip analyzing methods with 'override' or 'new' keywords as they might come from external source if ( context.Node is MethodDeclarationSyntax methodDeclaration - && !methodDeclaration - .Modifiers - .Any(modifier => modifier.IsKind(SyntaxKind.OverrideKeyword) || modifier.IsKind(SyntaxKind.NewKeyword)) + && !methodDeclaration.Modifiers.Any(modifier => + modifier.IsKind(SyntaxKind.OverrideKeyword) || modifier.IsKind(SyntaxKind.NewKeyword) + ) ) { foreach (var parameter in methodDeclaration.ParameterList.Parameters) diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCQRSHandlersAreInProperNamespace.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCQRSHandlersAreInProperNamespace.cs index fc2d4ca15..aa4c5e67f 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCQRSHandlersAreInProperNamespace.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCQRSHandlersAreInProperNamespace.cs @@ -76,8 +76,8 @@ INamespaceSymbol namespaceSymbol foreach (var type in namespaceSymbol.GetTypeMembers()) { - var implementedContracts = type.AllInterfaces - .Where(i => CqrsHandlerTypes.Contains(i.GetFullNamespaceName())) + var implementedContracts = type + .AllInterfaces.Where(i => CqrsHandlerTypes.Contains(i.GetFullNamespaceName())) .Select(i => i.TypeArguments.First()); foreach (var c in implementedContracts) @@ -165,9 +165,10 @@ INamespaceSymbol namespaceSymbol { if ( node is BaseNamespaceDeclarationSyntax namespaceDeclaration - && SymbolEqualityComparer - .Default - .Equals(semanticModel.GetDeclaredSymbol(namespaceDeclaration), namespaceSymbol) + && SymbolEqualityComparer.Default.Equals( + semanticModel.GetDeclaredSymbol(namespaceDeclaration), + namespaceSymbol + ) ) { return namespaceDeclaration; diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandValidatorsFollowNamingConvention.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandValidatorsFollowNamingConvention.cs index 11ff1172b..a7936bc24 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandValidatorsFollowNamingConvention.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/EnsureCommandValidatorsFollowNamingConvention.cs @@ -56,8 +56,8 @@ internal static string GetCommandValidatorExpectedName(INamedTypeSymbol commandV internal static INamedTypeSymbol? GetImplementedValidator(INamedTypeSymbol type) { - return type.AllInterfaces.FirstOrDefault( - interfaceSymbol => interfaceSymbol.GetFullNamespaceName() == ValidatorTypeName + return type.AllInterfaces.FirstOrDefault(interfaceSymbol => + interfaceSymbol.GetFullNamespaceName() == ValidatorTypeName ); } @@ -69,10 +69,8 @@ private static bool TryGetCommandValidator( var validator = GetImplementedValidator(type); var isCommandValidator = validator - ?.TypeArguments - .First() - .AllInterfaces - .Any(i => i.GetFullNamespaceName() == CommandTypeName); + ?.TypeArguments.First() + .AllInterfaces.Any(i => i.GetFullNamespaceName() == CommandTypeName); commandValidator = isCommandValidator == true ? validator : null; diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs index 1355e52b8..7f4f44129 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/NamedTypeSymbolExtensions.cs @@ -43,13 +43,12 @@ public static bool HasAuthorizationAttribute(this INamedTypeSymbol type) { var attributes = type.GetAttributes(); if ( - attributes.Any( - attr => - attr.AttributeClass is object - && ( - attr.AttributeClass.ImplementsInterfaceOrBaseClass(AuthorizeWhenTypeName) - || attr.AttributeClass.ImplementsInterfaceOrBaseClass(AllowUnauthorizedTypeName) - ) + attributes.Any(attr => + attr.AttributeClass is object + && ( + attr.AttributeClass.ImplementsInterfaceOrBaseClass(AuthorizeWhenTypeName) + || attr.AttributeClass.ImplementsInterfaceOrBaseClass(AllowUnauthorizedTypeName) + ) ) ) { diff --git a/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs b/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs index b003550aa..6c05bc279 100644 --- a/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs +++ b/src/Tools/LeanCode.CodeAnalysis/Analyzers/SuggestCommandsHaveValidators.cs @@ -85,8 +85,8 @@ private static bool CommandIsValidated(INamedTypeSymbol command, SyntaxTree tree private static bool IsThisCommandValidator(INamedTypeSymbol command, ITypeSymbol type) { - return type.AllInterfaces - .Where(i => i.GetFullNamespaceName() == ValidatorTypeName) + return type + .AllInterfaces.Where(i => i.GetFullNamespaceName() == ValidatorTypeName) .Where(i => SymbolEqualityComparer.Default.Equals(i.TypeArguments.First(), command)) .Any(); } diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs b/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs index d7c3c7ec2..a3a2719d1 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeActions/AddCommandValidatorCodeAction.cs @@ -45,9 +45,10 @@ protected override async Task GetChangedDocumentAsync(CancellationToke var handlerSyntax = root.FindNode(handlerSpan).FirstAncestorOrSelf() ?? throw new InvalidOperationException("Cannot find parent class."); - var concreteHandler = editor - .SemanticModel - .GetDeclaredSymbol(handlerSyntax, cancellationToken: cancellationToken)!; + var concreteHandler = editor.SemanticModel.GetDeclaredSymbol( + handlerSyntax, + cancellationToken: cancellationToken + )!; var handlerInteface = concreteHandler.AllInterfaces.FirstOrDefault(i => i.GetFullNamespaceName() == HandlerFullTypeName) ?? throw new InvalidOperationException("Cannot find handler interface implementation."); diff --git a/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs b/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs index 24b29c4e7..f8145025f 100644 --- a/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs +++ b/src/Tools/LeanCode.CodeAnalysis/CodeActions/FixCancellationTokenNamingCodeAction.cs @@ -47,9 +47,8 @@ token.Parent is ParameterSyntax parameter // Find all references to the old parameter name replace them. var references = containingMethod .DescendantNodes() - .Where( - node => - node is IdentifierNameSyntax identifier && identifier.Identifier.Text == oldIdentifierText + .Where(node => + node is IdentifierNameSyntax identifier && identifier.Identifier.Text == oldIdentifierText ) .Append(parameter); diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs index c2184f923..f31a32caf 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSEndpointsDataSourceTests.cs @@ -141,12 +141,48 @@ private static CQRSEndpointsDataSource PrepareEndpointsSource() dataSource.AddEndpointsFor( [ - new(CQRSObjectKind.Command, typeof(Command), typeof(CommandResult), typeof(IgnoreHandler), (_, __) => Task.FromResult(null)), - new(CQRSObjectKind.Command, typeof(AliasedCommand), typeof(CommandResult), typeof(IgnoreHandler), (_, __) => Task.FromResult(null)), - new(CQRSObjectKind.Query, typeof(Query), typeof(Result), typeof(IgnoreHandler), (_, __) => Task.FromResult(null)), - new(CQRSObjectKind.Query, typeof(AliasedQuery), typeof(Result), typeof(IgnoreHandler), (_, __) => Task.FromResult(null)), - new(CQRSObjectKind.Operation, typeof(Operation), typeof(Result), typeof(IgnoreHandler), (_, __) => Task.FromResult(null)), - new(CQRSObjectKind.Operation, typeof(AliasedOperation), typeof(Result), typeof(IgnoreHandler), (_, __) => Task.FromResult(null)), + new( + CQRSObjectKind.Command, + typeof(Command), + typeof(CommandResult), + typeof(IgnoreHandler), + (_, __) => Task.FromResult(null) + ), + new( + CQRSObjectKind.Command, + typeof(AliasedCommand), + typeof(CommandResult), + typeof(IgnoreHandler), + (_, __) => Task.FromResult(null) + ), + new( + CQRSObjectKind.Query, + typeof(Query), + typeof(Result), + typeof(IgnoreHandler), + (_, __) => Task.FromResult(null) + ), + new( + CQRSObjectKind.Query, + typeof(AliasedQuery), + typeof(Result), + typeof(IgnoreHandler), + (_, __) => Task.FromResult(null) + ), + new( + CQRSObjectKind.Operation, + typeof(Operation), + typeof(Result), + typeof(IgnoreHandler), + (_, __) => Task.FromResult(null) + ), + new( + CQRSObjectKind.Operation, + typeof(AliasedOperation), + typeof(Result), + typeof(IgnoreHandler), + (_, __) => Task.FromResult(null) + ), ], pipeline, pipeline, diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs index 6e897f586..4a5fa34d5 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/CQRSServicesBuilderTests.cs @@ -121,8 +121,7 @@ private void AssertOperationRegistered() where THandler : IOperationHandler { var cqrsObject = registrationSource - .Objects - .Should() + .Objects.Should() .ContainSingle(o => o.ObjectType == typeof(TOperation)) .Which; diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs index 0b63e5304..6964c5f44 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewareBasedLocalExecutorTests.cs @@ -71,7 +71,7 @@ public async Task Each_run_opens_separate_DI_scope() await executor.RunAsync(command1, new ClaimsPrincipal()); await executor.RunAsync(command2, new ClaimsPrincipal()); - storage.Commands.Should().BeEquivalentTo([ command1, command2 ]); + storage.Commands.Should().BeEquivalentTo([command1, command2]); storage.Handlers.Should().HaveCount(2); storage.Handlers.Should().HaveCount(2); } @@ -131,9 +131,9 @@ public async Task Decodes_499_status_code_as_unknown() public class LocalDataStorage { - public List Middlewares { get; } = [ ]; - public List Handlers { get; } = [ ]; - public List Commands { get; } = [ ]; + public List Middlewares { get; } = []; + public List Handlers { get; } = []; + public List Commands { get; } = []; } public record LocalCommand(bool Fail = false, bool Cancel = false, bool CheckMetadata = false) : ICommand; diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs index ecfdf0530..455144f2c 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Local/MiddlewaresForLocalExecutionTests.cs @@ -41,11 +41,9 @@ public async Task Exception_translation_middleware_works() var result = await executor.RunAsync(new ExceptionTranslationCommand(), new()); result.WasSuccessful.Should().BeFalse(); result - .ValidationErrors - .Should() + .ValidationErrors.Should() .ContainSingle() - .Which - .Should() + .Which.Should() .BeEquivalentTo(new ValidationError("", "Message", 100)); } @@ -57,11 +55,9 @@ public async Task Validation_middleware_works() var result = await executor.RunAsync(new ValidatedCommand(), new()); result.WasSuccessful.Should().BeFalse(); result - .ValidationErrors - .Should() + .ValidationErrors.Should() .ContainSingle() - .Which - .Should() + .Which.Should() .BeEquivalentTo(new ValidationError("", "FromValidator", 101)); } @@ -117,7 +113,7 @@ public Task ExecuteAsync(HttpContext context, ExceptionTranslationCommand comman public class ValidatedCommandValidator : ICommandValidator, ICommandValidatorWrapper { public Task ValidateAsync(HttpContext httpContext, ValidatedCommand command) => - Task.FromResult(new ValidationResult([ new ValidationError("", "FromValidator", 101) ])); + Task.FromResult(new ValidationResult([new ValidationError("", "FromValidator", 101)])); public Task ValidateAsync(HttpContext appContext, ICommand command) => ValidateAsync(appContext, (ValidatedCommand)command); diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/TestHelpers.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/TestHelpers.cs index 1304976a1..f802ab629 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/TestHelpers.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Middleware/TestHelpers.cs @@ -28,8 +28,7 @@ public static ExecutionResult ShouldContainExecutionResult(this HttpContext http public static CommandResult ShouldContainCommandResult(this ExecutionResult executionResult) { return executionResult - .Payload - .Should() + .Payload.Should() .BeOfType("because execution result should be a command result") .Subject; } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs index 21aa35eb5..44db1675c 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/Registration/CQRSApiDescriptionProviderTests.cs @@ -65,10 +65,9 @@ public void Query_defines_all_responses() var query = allDescriptors.Should().ContainSingle().Which; query - .SupportedResponseTypes - .Should() + .SupportedResponseTypes.Should() .BeEquivalentTo( - [ ResponseOf(200), ResponseOfVoid(400), ResponseOfVoid(401), ResponseOfVoid(403), ] + [ResponseOf(200), ResponseOfVoid(400), ResponseOfVoid(401), ResponseOfVoid(403),] ); } @@ -102,8 +101,7 @@ public void Command_defines_all_responses() var query = allDescriptors.Should().ContainSingle().Which; query - .SupportedResponseTypes - .Should() + .SupportedResponseTypes.Should() .BeEquivalentTo( [ ResponseOf(200), @@ -145,10 +143,9 @@ public void Operation_defines_all_responses() var query = allDescriptors.Should().ContainSingle().Which; query - .SupportedResponseTypes - .Should() + .SupportedResponseTypes.Should() .BeEquivalentTo( - [ ResponseOf(200), ResponseOfVoid(400), ResponseOfVoid(401), ResponseOfVoid(403), ] + [ResponseOf(200), ResponseOfVoid(400), ResponseOfVoid(401), ResponseOfVoid(403),] ); } @@ -193,7 +190,7 @@ private static List ListApisFor() private static List ListApis(Type forObject) { var dataSource = CreateDataSource(forObject); - var context = new ApiDescriptionProviderContext([ ]); + var context = new ApiDescriptionProviderContext([]); new CQRSApiDescriptionProvider(dataSource).OnProvidersExecuting(context); return context.Results.ToList(); } diff --git a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs index ec6dcbdbf..52bb43f86 100644 --- a/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs +++ b/test/CQRS/LeanCode.CQRS.AspNetCore.Tests/ServiceProviderRegistrationExtensionsTests.cs @@ -53,8 +53,8 @@ public void Does_not_register_local_executors_by_default() [Fact] public void Registers_local_executors_on_request() { - var sp = BuildProvider( - c => c.WithLocalCommands(_ => { }).WithLocalQueries(_ => { }).WithLocalOperations(_ => { }) + var sp = BuildProvider(c => + c.WithLocalCommands(_ => { }).WithLocalQueries(_ => { }).WithLocalOperations(_ => { }) ); sp.Should().HaveService(); @@ -65,11 +65,10 @@ public void Registers_local_executors_on_request() [Fact] public void Registers_keyed_local_executors_on_request() { - var sp = BuildProvider( - c => - c.WithKeyedLocalCommands("commands", _ => { }) - .WithKeyedLocalQueries("queries", _ => { }) - .WithKeyedLocalOperations("operations", _ => { }) + var sp = BuildProvider(c => + c.WithKeyedLocalCommands("commands", _ => { }) + .WithKeyedLocalQueries("queries", _ => { }) + .WithKeyedLocalOperations("operations", _ => { }) ); sp.Should().HaveKeyedService("commands"); @@ -121,8 +120,7 @@ public ServiceProviderAssertions(ServiceProvider subject) public AndConstraint HaveService(string because = "", params object[] becauseArgs) { Execute - .Assertion - .BecauseOf(because, becauseArgs) + .Assertion.BecauseOf(because, becauseArgs) .ForCondition(Subject.GetRequiredService().IsService(typeof(T))) .FailWith("Expected to have {0} registered{reason}", typeof(T)); return new AndConstraint(this); @@ -135,8 +133,7 @@ params object[] becauseArgs ) { Execute - .Assertion - .BecauseOf(because, becauseArgs) + .Assertion.BecauseOf(because, becauseArgs) .ForCondition( Subject.GetRequiredService().IsKeyedService(typeof(T), serviceKey) ) @@ -147,8 +144,7 @@ params object[] becauseArgs public AndConstraint NotHaveService(string because = "", params object[] becauseArgs) { Execute - .Assertion - .BecauseOf(because, becauseArgs) + .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/Integration/TestApp.cs b/test/CQRS/LeanCode.CQRS.MassTransitRelay.Tests/Integration/TestApp.cs index 805df6a0a..bdd2976bf 100644 --- a/test/CQRS/LeanCode.CQRS.MassTransitRelay.Tests/Integration/TestApp.cs +++ b/test/CQRS/LeanCode.CQRS.MassTransitRelay.Tests/Integration/TestApp.cs @@ -112,9 +112,8 @@ public async Task RunCommand(ICommand command) { var response = await server .CreateRequest($"/cqrs/command/{command.GetType().FullName}") - .And( - cfg => - cfg.Content = JsonContent.Create(command, command.GetType(), options: new JsonSerializerOptions()) + .And(cfg => + cfg.Content = JsonContent.Create(command, command.GetType(), options: new JsonSerializerOptions()) ) .PostAsync(); response.EnsureSuccessStatusCode(); diff --git a/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs b/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs index 4adfdee22..ca6597bc4 100644 --- a/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs +++ b/test/CQRS/LeanCode.CQRS.Security.Tests/CustomAuthorizerTests.cs @@ -47,8 +47,8 @@ public async Task CustomAuthorizerTObjectTCustomData_casts_data_properly_as_IHtt var customAuthorizer = new CustomAuthorizer(); await customAuthorizer - .Awaiting( - c => ((IHttpContextCustomAuthorizer)c).CheckIfAuthorizedAsync(httpContext, new object(), new object()) + .Awaiting(c => + ((IHttpContextCustomAuthorizer)c).CheckIfAuthorizedAsync(httpContext, new object(), new object()) ) .Should() .ThrowAsync(); diff --git a/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs b/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs index 0ff0002ee..762b40513 100644 --- a/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs +++ b/test/CQRS/LeanCode.CQRS.Validation.Fluent.Tests/AdapterWithAsyncValidatorIntegrationTests.cs @@ -44,8 +44,7 @@ public async Task Correctly_maps_validation_result() ); res.IsValid.Should().BeFalse(); - res.Errors - .Should() + res.Errors.Should() .BeEquivalentTo( new ValidationError[] { diff --git a/test/Domain/LeanCode.DomainModels.EF.Tests/CollectionExtensionsTests.cs b/test/Domain/LeanCode.DomainModels.EF.Tests/CollectionExtensionsTests.cs index 9d7b733c6..22792548e 100644 --- a/test/Domain/LeanCode.DomainModels.EF.Tests/CollectionExtensionsTests.cs +++ b/test/Domain/LeanCode.DomainModels.EF.Tests/CollectionExtensionsTests.cs @@ -36,8 +36,7 @@ public void ConditionalWhere_filters_when_the_predicate_is_true() .ConditionalWhere(a => a.Name == Parrot.Name, true) .Should() .ContainSingle() - .Which - .Should() + .Which.Should() .Be(Parrot); } diff --git a/test/Domain/LeanCode.DomainModels.EF.Tests/TimestampTzExpressionInterceptorTests.cs b/test/Domain/LeanCode.DomainModels.EF.Tests/TimestampTzExpressionInterceptorTests.cs index 308f0b7bc..593a24dd3 100644 --- a/test/Domain/LeanCode.DomainModels.EF.Tests/TimestampTzExpressionInterceptorTests.cs +++ b/test/Domain/LeanCode.DomainModels.EF.Tests/TimestampTzExpressionInterceptorTests.cs @@ -13,8 +13,7 @@ public void LocalTimestampWithoutOffsetProperty_accesses_expected_property() var timestampTz = new TimestampTz(DateTime.UtcNow, "Europe/Warsaw"); TimestampTzExpressionRewriter - .LocalTimestampWithoutOffsetProperty - .GetGetMethod() + .LocalTimestampWithoutOffsetProperty.GetGetMethod() .Invoke(timestampTz, null) .Should() .Be(timestampTz.LocalTimestampWithoutOffset); @@ -26,8 +25,7 @@ public void UtcTimestampProperty_accesses_expected_property() var timestampTz = new TimestampTz(DateTime.UtcNow, "Europe/Warsaw"); TimestampTzExpressionRewriter - .UtcTimestampProperty - .GetGetMethod() + .UtcTimestampProperty.GetGetMethod() .Invoke(timestampTz, null) .Should() .Be(timestampTz.UtcTimestamp); @@ -39,8 +37,7 @@ public void TimeZoneIdProperty_accesses_expected_property() var timestampTz = new TimestampTz(DateTime.UtcNow, "Europe/Warsaw"); TimestampTzExpressionRewriter - .TimeZoneIdProperty - .GetGetMethod() + .TimeZoneIdProperty.GetGetMethod() .Invoke(timestampTz, null) .Should() .Be(timestampTz.TimeZoneId); @@ -60,8 +57,7 @@ public void ConvertDateTimeBySystemTimeZoneIdMethod_calls_expected_method() var utcNow = DateTime.UtcNow; TimestampTzExpressionRewriter - .ConvertDateTimeBySystemTimeZoneIdMethod - .Invoke(null, [ utcNow, "Europe/Warsaw" ]) + .ConvertDateTimeBySystemTimeZoneIdMethod.Invoke(null, [utcNow, "Europe/Warsaw"]) .Should() .Be(TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, "Europe/Warsaw")); } @@ -75,8 +71,7 @@ public void Interceptor_rewrites_expression_tree_as_expected() TimeZoneInfo.ConvertTimeBySystemTimeZoneId(tstz.UtcTimestamp.UtcDateTime, tstz.TimeZoneId); TimestampTzExpressionInterceptorDbContextOptionsBuilderExtensions - .Interceptor - .QueryCompilationStarting(input, default) + .Interceptor.QueryCompilationStarting(input, default) .Should() .BeEquivalentTo(expectedOutput); } diff --git a/test/Domain/LeanCode.DomainModels.Tests/Ids/ValidConstructTests.cs b/test/Domain/LeanCode.DomainModels.Tests/Ids/ValidConstructTests.cs index 2b2575028..465fc771d 100644 --- a/test/Domain/LeanCode.DomainModels.Tests/Ids/ValidConstructTests.cs +++ b/test/Domain/LeanCode.DomainModels.Tests/Ids/ValidConstructTests.cs @@ -9,38 +9,38 @@ public void Correct_RawInt() { AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawInt)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawInt)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawInt, CustomPrefix = "ignored")] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawInt, CustomPrefix = "ignored")] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawInt, SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawInt, SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawInt, CustomPrefix = "ignored", SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawInt, CustomPrefix = "ignored", SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); } @@ -49,38 +49,38 @@ public void Correct_RawLong() { AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawLong)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawLong)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawLong, CustomPrefix = "ignored")] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawLong, CustomPrefix = "ignored")] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawLong, SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawLong, SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawLong, CustomPrefix = "ignored", SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawLong, CustomPrefix = "ignored", SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); } @@ -89,38 +89,38 @@ public void Correct_RawGuid() { AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawGuid)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawGuid)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawGuid, CustomPrefix = "ignored")] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawGuid, CustomPrefix = "ignored")] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawGuid, SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawGuid, SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.RawGuid, CustomPrefix = "ignored", SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.RawGuid, CustomPrefix = "ignored", SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); } @@ -129,38 +129,38 @@ public void Correct_PrefixedGuid() { AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.PrefixedGuid)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.PrefixedGuid)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.PrefixedGuid, CustomPrefix = "prefix")] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.PrefixedGuid, CustomPrefix = "prefix")] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.PrefixedGuid, SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.PrefixedGuid, SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); AssertCorrect( """ - using LeanCode.DomainModels.Ids; - namespace Test; - [TypedId(TypedIdFormat.PrefixedGuid, CustomPrefix = "prefix", SkipRandomGenerator = true)] - public readonly partial record struct Id; - """ + using LeanCode.DomainModels.Ids; + namespace Test; + [TypedId(TypedIdFormat.PrefixedGuid, CustomPrefix = "prefix", SkipRandomGenerator = true)] + public readonly partial record struct Id; + """ ); } diff --git a/test/Domain/LeanCode.DomainModels.Tests/Model/TimestampTzTests.cs b/test/Domain/LeanCode.DomainModels.Tests/Model/TimestampTzTests.cs index 8bc7effb0..4cd1fd0d4 100644 --- a/test/Domain/LeanCode.DomainModels.Tests/Model/TimestampTzTests.cs +++ b/test/Domain/LeanCode.DomainModels.Tests/Model/TimestampTzTests.cs @@ -155,8 +155,7 @@ public void Json_serialization_writes_expected_properties() document.RootElement.ValueKind.Should().Be(JsonValueKind.Object); document - .RootElement - .EnumerateObject() + .RootElement.EnumerateObject() .Should() .BeEquivalentTo( [ diff --git a/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs b/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs index aad2fab36..c46df2e2d 100644 --- a/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs +++ b/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsRegistrationTests.cs @@ -31,8 +31,8 @@ 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(UserIdClaim) ); var userIdExtractor = serviceProvider.GetService>(); @@ -43,8 +43,8 @@ public void Raw_typed_IUserIdExtractor_is_correctly_registered() [Fact] public void Prefixed_typed_IUserIdExtractor_is_correctly_registered() { - var serviceProvider = BuildServiceProvider( - services => services.AddPrefixedUserIdExtractor(UserIdClaim) + var serviceProvider = BuildServiceProvider(services => + services.AddPrefixedUserIdExtractor(UserIdClaim) ); var userIdExtractor = serviceProvider.GetService>(); @@ -55,8 +55,8 @@ public void Prefixed_typed_IUserIdExtractor_is_correctly_registered() [Fact] public void Non_generic_IUserIdExtractor_is_registered_for_other_user_id_types() { - var serviceProvider = BuildServiceProvider( - services => services.AddPrefixedUserIdExtractor(UserIdClaim) + var serviceProvider = BuildServiceProvider(services => + services.AddPrefixedUserIdExtractor(UserIdClaim) ); var userIdExtractor = serviceProvider.GetService(); diff --git a/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsTests.cs b/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsTests.cs index 25a51976a..ad037eef3 100644 --- a/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsTests.cs +++ b/test/Helpers/LeanCode.UserIdExtractors.Tests/UserIdExtractorsTests.cs @@ -67,6 +67,6 @@ private static ClaimsPrincipal CreateUser(string userId) { var claim = new Claim(UserIdClaim, userId); - return new ClaimsPrincipal(new ClaimsIdentity([ claim ])); + return new ClaimsPrincipal(new ClaimsIdentity([claim])); } } diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs index 0273c7027..dcd388256 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/AuditLogsIntegrationTests.cs @@ -76,9 +76,10 @@ public AuditLogsIntegrationTests() AuthorizedTestPath, (ctx) => { - Activity - .Current! - .AddBaggage(IdentityTraceBaggageHelpers.CurrentUserIdKey, ActorId); + Activity.Current!.AddBaggage( + IdentityTraceBaggageHelpers.CurrentUserIdKey, + ActorId + ); var dbContext = ctx.RequestServices.GetService()!; dbContext.Add(TestEntity); return Task.CompletedTask; @@ -131,10 +132,7 @@ await server.SendAsync(ctx => messages .Should() .ContainSingle() - .Which - .Context - .Message - .Should() + .Which.Context.Message.Should() .BeEquivalentTo( new { @@ -149,9 +147,7 @@ await server.SendAsync(ctx => }, opt => opt.ComparingByMembers() ) - .And - .Subject - .Should() + .And.Subject.Should() .Match(s => s.As().SpanId != null && s.As().TraceId != null); } @@ -172,14 +168,9 @@ await server.SendAsync(ctx => messages .Should() .ContainSingle() - .Which - .Context - .Message - .Should() + .Which.Context.Message.Should() .BeEquivalentTo(new { ActorId, }, opt => opt.ComparingByMembers()) - .And - .Subject - .Should() + .And.Subject.Should() .Match(s => s.As().SpanId != null && s.As().TraceId != null); } diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs index 1297d9d03..1db99f330 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/ChangedEntititesExtractorTests.cs @@ -35,8 +35,7 @@ public void Check_if_added_entity_is_extracted() changes .Should() .ContainSingle() - .Which - .Should() + .Which.Should() .BeEquivalentTo( new { @@ -65,8 +64,7 @@ public void Check_if_updated_entity_is_extracted() changes .Should() .ContainSingle() - .Which - .Should() + .Which.Should() .BeEquivalentTo( new { @@ -93,8 +91,7 @@ public void Check_if_deleted_entity_is_extracted() changes .Should() .ContainSingle() - .Which - .Should() + .Which.Should() .BeEquivalentTo( new { diff --git a/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs b/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs index 4c99cb09d..0ea7a22c8 100644 --- a/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs +++ b/test/Infrastructure/LeanCode.AuditLogs.Tests/TestDbContext.cs @@ -43,8 +43,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) public class TestEntity : IAggregateRoot { - private readonly List ownedEntities = [ ]; - private readonly List includedEntities = [ ]; + private readonly List ownedEntities = []; + private readonly List includedEntities = []; public string Id { get; set; } = null!; public string SomeString { get; set; } = null!; diff --git a/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs b/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs index 0ba6958d0..0ddebdc37 100644 --- a/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs +++ b/test/Infrastructure/LeanCode.Azure.Tests/AzureStorageAuditLogIntegrationTests.cs @@ -43,7 +43,7 @@ public async Task Ensure_that_log_is_correctly_uploaded_to_storage() await storage.StoreEventAsync( new AuditLogMessage( new( - [ id.ToString() ], + [id.ToString()], type, JsonSerializer.SerializeToDocument(new { Foo = "bar" }), JsonSerializer.SerializeToDocument(new { Shadow = "property" }), @@ -75,7 +75,7 @@ public async Task Ensure_that_multiple_logs_are_correctly_uploaded_to_storage() await storage.StoreEventAsync( new AuditLogMessage( new( - [ id.ToString() ], + [id.ToString()], type, JsonSerializer.SerializeToDocument(new { Foo = "bar" }), JsonSerializer.SerializeToDocument(new { Shadow = "property" }), @@ -112,7 +112,7 @@ public async Task Ensure_that_all_logs_are_correctly_uploaded_to_multiple_files( await storage.StoreEventAsync( new AuditLogMessage( new( - [ id.ToString() ], + [id.ToString()], type, JsonSerializer.SerializeToDocument(new { Foo = "bar" }), JsonSerializer.SerializeToDocument(new { Shadow = "property" }), diff --git a/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs b/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs index fab88b488..e3ce03232 100644 --- a/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs +++ b/test/Infrastructure/LeanCode.Kratos.Tests/KratosWebHookHandlerTests.cs @@ -41,8 +41,8 @@ public async Task Swallows_unhandled_exceptions_thrown_by_inner_handler_and_resp [Fact] public async Task Correctly_serializes_identity_responses() { - var handler = new KratosWebHookTestHandler( - ctx => KratosWebHookHandlerBase.WriteIdentityResponseAsync(ctx, Identity) + var handler = new KratosWebHookTestHandler(ctx => + KratosWebHookHandlerBase.WriteIdentityResponseAsync(ctx, Identity) ); var ctx = await RunAsync(handler, new() { [handler.ApiKeyHeaderName] = ApiKey }); diff --git a/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs b/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs index b5ea669bc..90e12f888 100644 --- a/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs +++ b/test/Infrastructure/LeanCode.SendGrid.Tests/SendGridRazorClientTests.cs @@ -48,14 +48,15 @@ public SendGridRazorClientTests() var localizer = Substitute.For(); - localizer[default, default].ReturnsForAnyArgs(ci => - { - var culture = ci.Arg(); - var cultureName = culture == CultureInfo.InvariantCulture ? "InvariantCulture" : culture.Name; - var keyName = ci.Arg(); + localizer[default, default] + .ReturnsForAnyArgs(ci => + { + var culture = ci.Arg(); + var cultureName = culture == CultureInfo.InvariantCulture ? "InvariantCulture" : culture.Name; + var keyName = ci.Arg(); - return $"[{cultureName}] {keyName}"; - }); + return $"[{cultureName}] {keyName}"; + }); client = new SendGridRazorClient(new SendGridClient(Options), renderer, localizer); } diff --git a/test/LeanCode.IntegrationTests/App/CQRS.cs b/test/LeanCode.IntegrationTests/App/CQRS.cs index 086420c87..8e9a3bc0f 100644 --- a/test/LeanCode.IntegrationTests/App/CQRS.cs +++ b/test/LeanCode.IntegrationTests/App/CQRS.cs @@ -45,8 +45,7 @@ public ListEntitiesQH(TestDbContext dbContext) public Task> ExecuteAsync(HttpContext context, ListEntities query) { return dbContext - .Entities - .Select(e => new EntityDTO { Id = e.Id, Value = e.Value }) + .Entities.Select(e => new EntityDTO { Id = e.Id, Value = e.Value }) .ToListAsync(context.RequestAborted); } } diff --git a/test/LeanCode.IntegrationTests/App/Startup.cs b/test/LeanCode.IntegrationTests/App/Startup.cs index 8835433f3..f67c45728 100644 --- a/test/LeanCode.IntegrationTests/App/Startup.cs +++ b/test/LeanCode.IntegrationTests/App/Startup.cs @@ -61,18 +61,16 @@ protected override void ConfigureApp(IApplicationBuilder app) { app.UseRouting(); app.UseAuthentication(); - app.UseEndpoints( - e => - e.MapRemoteCQRS( - "/api", - cfg => - { - cfg.Commands = cmd => - cmd.Secure().Validate().CommitTransaction().PublishEvents(); - cfg.Queries = cmd => cmd.Secure(); - cfg.Operations = cmd => cmd.Secure(); - } - ) + app.UseEndpoints(e => + e.MapRemoteCQRS( + "/api", + cfg => + { + cfg.Commands = cmd => cmd.Secure().Validate().CommitTransaction().PublishEvents(); + cfg.Queries = cmd => cmd.Secure(); + cfg.Operations = cmd => cmd.Secure(); + } + ) ); } } diff --git a/test/LeanCode.IntegrationTests/CQRSTests.cs b/test/LeanCode.IntegrationTests/CQRSTests.cs index e49fa4145..a18950510 100644 --- a/test/LeanCode.IntegrationTests/CQRSTests.cs +++ b/test/LeanCode.IntegrationTests/CQRSTests.cs @@ -44,12 +44,9 @@ private async Task RunInvalidCommandAsync() using var _ = new AssertionScope(); result.WasSuccessful.Should().BeFalse(); result - .ValidationErrors - .Should() + .ValidationErrors.Should() .ContainSingle() - .Which - .ErrorCode - .Should() + .Which.ErrorCode.Should() .Be(AddEntity.ErrorCodes.ValueRequired); } diff --git a/test/LeanCode.IntegrationTests/TimestampTzTests.cs b/test/LeanCode.IntegrationTests/TimestampTzTests.cs index 9779bb6fe..98de7df30 100644 --- a/test/LeanCode.IntegrationTests/TimestampTzTests.cs +++ b/test/LeanCode.IntegrationTests/TimestampTzTests.cs @@ -43,26 +43,24 @@ public async Task Sorting_by_UtcTimestamp_returns_results_in_expected_order() { var orderedByUtc = await dbContext.Meetings.OrderBy(m => m.StartTime.UtcTimestamp).ToListAsync(); - orderedByUtc.Should().BeEquivalentTo([ meeting1, meeting2 ], options => options.WithStrictOrdering()); + orderedByUtc.Should().BeEquivalentTo([meeting1, meeting2], options => options.WithStrictOrdering()); } [PostgresFact] public async Task Sorting_by_LocalTimestampWithoutOffset_returns_results_in_expected_order() { var orderedByLocal = await dbContext - .Meetings - .OrderBy(m => m.StartTime.LocalTimestampWithoutOffset) + .Meetings.OrderBy(m => m.StartTime.LocalTimestampWithoutOffset) .ToListAsync(); - orderedByLocal.Should().BeEquivalentTo([ meeting2, meeting1 ], options => options.WithStrictOrdering()); + orderedByLocal.Should().BeEquivalentTo([meeting2, meeting1], options => options.WithStrictOrdering()); } [PostgresFact] public void Sorting_by_LocalTimestampWithoutOffset_generates_SQL_with_expected_AT_TIME_ZONE_operator() { dbContext - .Meetings - .OrderBy(m => m.StartTime.LocalTimestampWithoutOffset) + .Meetings.OrderBy(m => m.StartTime.LocalTimestampWithoutOffset) .ToQueryString() .Should() .ContainEquivalentOf( diff --git a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/Tests.cs b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/Tests.cs index 9d656f3a3..48be59066 100644 --- a/test/Testing/LeanCode.IntegrationTestHelpers.Tests/Tests.cs +++ b/test/Testing/LeanCode.IntegrationTestHelpers.Tests/Tests.cs @@ -63,8 +63,7 @@ public async Task Test_authorization_scheme_works() authResult.IsAuthenticated.Should().BeTrue(); authResult - .Claims - .Should() + .Claims.Should() .BeEquivalentTo( new[] { diff --git a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs index 392041018..3c3f198f3 100644 --- a/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs +++ b/test/Tools/LeanCode.CodeAnalysis.Tests/Verifiers/DiagnosticVerifier.cs @@ -92,7 +92,7 @@ private Document[] GetDocuments(string[] sources) protected Document CreateDocument(string source, params string[] additionalSources) { - return CreateProject([ source, ..additionalSources ]).Documents.OrderBy(d => d.Name).First(); + return CreateProject([source, ..additionalSources]).Documents.OrderBy(d => d.Name).First(); } private Project CreateProject(string[] sources) @@ -102,8 +102,7 @@ private Project CreateProject(string[] sources) var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = Workspace - .CurrentSolution - .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) + .CurrentSolution.AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) .AddMetadataReferences(projectId, CommonReferences) .WithProjectCompilationOptions( projectId,