From fd78f4747155a70d80a7e527e955fc42bf88bd67 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Sat, 11 Nov 2023 17:05:49 -0500 Subject: [PATCH] Fix/warnings (#1642) * First wave of warning fixes * Warnings phase2 --- .build/Build.cs | 5 - LaunchPad.sln | 1 + sample/.editorconfig | 1 + sample/Directory.Build.props | 1 + sample/Sample.BlazorServer/Program.cs | 2 +- sample/Sample.BlazorServer/Startup.cs | 9 +- .../Controllers/LaunchRecordController.cs | 1 - .../Controllers/WeatherForecastController.cs | 9 +- sample/Sample.Classic.Restful/Program.cs | 2 +- sample/Sample.Classic.Restful/Startup.cs | 9 +- sample/Sample.Command/Program.cs | 31 ++---- sample/Sample.Core/DataConvention.cs | 2 +- .../Sample.Core/DataGenerationConvention.cs | 11 +- sample/Sample.Core/Domain/LaunchRecord.cs | 9 +- sample/Sample.Core/Domain/ReadyRocket.cs | 4 +- sample/Sample.Core/Domain/RocketDbContext.cs | 12 +- .../LaunchRecords/CreateLaunchRecord.cs | 19 +--- .../LaunchRecords/DeleteLaunchRecord.cs | 15 +-- .../LaunchRecords/EditLaunchRecord.cs | 24 ++-- .../LaunchRecords/GetLaunchRecord.cs | 15 +-- .../LaunchRecords/ListLaunchRecords.cs | 19 +--- .../Operations/Rockets/CreateRocket.cs | 19 +--- .../Operations/Rockets/DeleteRocket.cs | 15 +-- .../Operations/Rockets/EditRocket.cs | 24 ++-- .../Operations/Rockets/GetRocket.cs | 15 +-- .../Rockets/GetRocketLaunchRecord.cs | 17 +-- .../Rockets/GetRocketLaunchRecords.cs | 17 +-- .../Operations/Rockets/ListRockets.cs | 19 +--- sample/Sample.Function/TestFunction.cs | 15 +-- sample/Sample.Graphql/Program.cs | 9 +- sample/Sample.Grpc/Program.cs | 2 +- .../Services/LaunchRecordsService.cs | 43 +++---- sample/Sample.Grpc/Services/RocketsService.cs | 35 ++---- .../Sample.Pages/Pages/Rockets/Edit.cshtml.cs | 11 +- .../Pages/Rockets/Index.cshtml.cs | 11 +- sample/Sample.Pages/Program.cs | 2 +- sample/Sample.Pages/Startup.cs | 9 +- sample/Sample.Restful.Client/Test1.cs | 2 - .../Controllers/LaunchRecordController.cs | 2 + .../Controllers/RocketController.cs | 8 +- .../Controllers/WeatherForecastController.cs | 9 +- sample/Sample.Restful/Program.cs | 22 ++-- sample/Sample.Worker/Program.cs | 4 +- sample/Sample.Worker/Worker.cs | 15 +-- src/Analyzers/Composition/MatcherDefaults.cs | 2 + .../Composition/RestfulApiParameterMatcher.cs | 34 +++--- .../ControllerActionBodyGenerator.cs | 19 +++- .../GraphqlMutationActionBodyGenerator.cs | 52 +++------ ...raphqlOptionalPropertyTrackingGenerator.cs | 2 + src/Analyzers/InheritFromGenerator.cs | 8 +- src/Analyzers/PropertyTrackingGenerator.cs | 2 + src/AspNetCore.Blazor/Validation.cs | 8 +- ...LaunchPad.AspNetCore.NewtonsoftJson.csproj | 1 + ...onProblemDetailsNewtonsoftJsonConverter.cs | 8 +- .../IResettableAlbaExtension.cs | 9 ++ src/AspNetCore.Testing/LaunchPadExtension.cs | 50 +++++++-- .../LaunchPadWebAppFixture.cs | 31 ++++++ .../Composition/IRestfulApiMethodMatcher.cs | 2 + .../IRestfulApiParameterMatcher.cs | 2 + .../RestfulApiActionModelConvention.cs | 8 +- .../RestfulApiApplicationModelProvider.cs | 13 +-- .../Composition/RestfulApiMethodBuilder.cs | 2 + .../Composition/RestfulApiParameterMatcher.cs | 37 +++--- .../Conventions/AspNetCoreConvention.cs | 1 + ...CoreConventionInstrumentationConvention.cs | 7 +- .../AspNetCoreValidationBehaviorConvention.cs | 12 +- .../Conventions/FluentValidationConvention.cs | 2 +- .../Conventions/ProblemDetailsConvention.cs | 1 + .../Conventions/SwashbuckleConvention.cs | 1 + .../Filters/SerilogLoggingActionFilter.cs | 17 +-- .../Filters/SerilogLoggingPageFilter.cs | 11 +- .../OpenApi/StronglyTypedIdSchemaFilter.cs | 4 + .../SwashbuckleAddAllDocumentEndpoints.cs | 15 +-- ...Rocket.Surgery.LaunchPad.AspNetCore.csproj | 1 + .../RocketSurgeryMvcCoreExtensions.cs | 12 +- .../Validation/ValidationExceptionFilter.cs | 1 - ...onsoftJsonCompositeNodaPatternConverter.cs | 6 +- .../NewtonsoftJsonDestructuringPolicy.cs | 5 +- .../Conventions/InstrumentationConvention.cs | 1 - .../Conventions/MediatRConvention.cs | 3 +- src/Foundation/NodaTimeDestructuringPolicy.cs | 11 +- ...emTextJsonCompositeNodaPatternConverter.cs | 2 + .../SystemTextJsonDestructuringPolicy.cs | 2 +- .../Validation/CompositeValidator.cs | 18 +-- .../CompositeValidatorDescriptor.cs | 21 ++-- .../Validation/CustomHealthCheckService.cs | 16 +-- .../Validation/FluentValidationOptions.cs | 26 ++--- .../HealthCheckFluentValidationOptions.cs | 30 +++-- .../Validation/ValidationPipelineBehavior.cs | 28 ++--- .../Conventions/SerilogFunctionsConvention.cs | 10 +- src/Functions/LaunchPadFunctionStartup.cs | 1 + src/Grpc/NotAuthorizedInterceptor.cs | 7 +- src/Grpc/NotFoundInterceptor.cs | 7 +- src/Grpc/ProblemDetailsInterceptor.cs | 1 + src/Grpc/RequestFailedInterceptor.cs | 7 +- src/Grpc/Validation/ValidationInterceptor.cs | 23 ++-- src/Grpc/Validation/ValidationTrailers.cs | 3 + .../EnvironmentLoggingConvention.cs | 8 +- .../Conventions/OpenTelemetryConvention.cs | 4 - .../SerilogConsoleLoggingConvention.cs | 4 +- .../SerilogDebugLoggingConvention.cs | 4 +- .../Conventions/SerilogHostingConvention.cs | 1 + .../OpenTelemetryHostBuilderExtensions.cs | 1 - ...HotChocolateContextDataConfigureOptions.cs | 6 +- .../Conventions/GraphqlConvention.cs | 1 - .../Conventions/InstrumentationConvention.cs | 4 +- .../Extensions/ISchemaBuilderExtensions.cs | 1 - src/HotChocolate/GraphqlExtensions.cs | 17 ++- .../CustomValidationMiddlewareInjector.cs | 7 +- .../Validation/CustomValidatorRegistry.cs | 4 +- .../Validation/ValidationMiddleware.cs | 33 ++---- .../ConverterHelpers.cs | 3 +- .../Profiles/NewtonsoftJsonProfile.cs | 2 + ...ry.LaunchPad.Mapping.NewtonsoftJson.csproj | 1 + src/Mapping/Profiles/SystemJsonTextProfile.cs | 2 + .../Rocket.Surgery.LaunchPad.Mapping.csproj | 1 + src/Metadata/AssemblyMetadataProvider.cs | 8 +- src/Metadata/GitVersion.cs | 1 + src/Metadata/PrefixExtensions.cs | 4 +- .../SerilogReadFromConfigurationConvention.cs | 4 + ...NetTopologySuiteSerializationExtensions.cs | 1 - .../WktGeometryConverter.cs | 12 +- src/Spatial/Conventions/SpatialConvention.cs | 2 +- .../NetTopologySuiteDestructuringPolicy.cs | 105 +----------------- src/Spatial/WktConverterFactory.cs | 7 +- src/Spatial/WktGeometryConverter.cs | 12 +- .../StrawberryShakeSpatialConvention.cs | 8 -- .../CoordinatesSerializer.cs | 7 ++ .../GeometrySerializer.cs | 9 +- .../Conventions/StrawberryShakeConvention.cs | 3 - src/StrawberryShake/DateTimeZoneSerializer.cs | 9 ++ src/StrawberryShake/DurationSerializer.cs | 8 +- src/StrawberryShake/EnumScalarSerializer.cs | 11 ++ src/StrawberryShake/InstantSerializer.cs | 8 +- src/StrawberryShake/IsoDayOfWeekSerializer.cs | 8 +- .../JsonElementScalarSerializer.cs | 21 ++-- src/StrawberryShake/LocalDateSerializer.cs | 8 +- .../LocalDateTimeSerializer.cs | 8 +- src/StrawberryShake/LocalTimeSerializer.cs | 8 +- .../NodaTimeStringScalarSerializer.cs | 14 ++- src/StrawberryShake/OffsetDateSerializer.cs | 8 +- .../OffsetDateTimeSerializer.cs | 8 +- src/StrawberryShake/OffsetSerializer.cs | 8 +- src/StrawberryShake/OffsetTimeSerializer.cs | 8 +- src/StrawberryShake/PeriodSerializer.cs | 8 +- ...t.Surgery.LaunchPad.StrawberryShake.csproj | 1 + .../ZonedDateTimeSerializer.cs | 7 ++ .../IOpenTelemetryMetricsConvention.cs | 1 - .../OpenTelemetryMetricsConvention.cs | 1 - .../RocketSurgeryOpenTelemetryExtensions.cs | 1 - src/Testing/FakeClockConvention.cs | 2 +- test/.editorconfig | 3 + .../Analyzers.Tests.roslyn4.0.csproj | 3 +- .../Analyzers.Tests.roslyn4.4.csproj | 3 +- test/Analyzers.Tests/Analyzers.Tests.csproj | 3 +- .../ControllerActionBodyGeneratorTests.cs | 2 +- ...GraphqlMutationActionBodyGeneratorTests.cs | 2 +- test/Analyzers.Tests/Helpers/GeneratorTest.cs | 6 +- test/Analyzers.Tests/ModuleInitializer.cs | 13 ++- .../Restful/RestfulApiMethodBuilderTests.cs | 38 +++---- test/Directory.Build.props | 13 ++- test/Extensions.Tests/ConventionFakeTest.cs | 8 +- test/Extensions.Tests/Extensions.Tests.csproj | 1 - .../FakeClockConventionTests.cs | 6 +- .../Mapping/AutoMapperProfile.cs | 6 +- .../Extensions.Tests/Mapping/DurationTests.cs | 6 +- test/Extensions.Tests/Mapping/InstantTests.cs | 6 +- .../Mapping/JTokenConverterTests.cs | 6 +- .../Mapping/JsonElementConverterTests.cs | 6 +- .../Mapping/LocalDateTests.cs | 6 +- .../Mapping/LocalDateTimeTests.cs | 6 +- .../Mapping/LocalTimeTests.cs | 6 +- .../Mapping/OffsetDateTimeTests.cs | 6 +- test/Extensions.Tests/Mapping/OffsetTests.cs | 6 +- test/Extensions.Tests/Mapping/PeriodTests.cs | 6 +- .../Mapping/SystemTextJsonTests.cs | 6 +- .../Mapping/TypeConverterTest.cs | 9 +- test/Extensions.Tests/MediatRTests.cs | 22 ++-- ...tonsoftJsonNetTopologySuiteGeoJsonTests.cs | 9 +- ...tJsonNetTopologySuiteWellKnownTextTests.cs | 11 +- .../NewtonsoftJsonNodaTimeTests.cs | 11 +- .../StringInValidatorTests.cs | 15 ++- ...temTextJsonNetTopologySuiteGeoJsonTests.cs | 9 +- ...tJsonNetTopologySuiteWellKnownTextTests.cs | 14 +-- .../SystemTextJsonNodaTimeTests.cs | 9 +- .../HealthCheckOptionsValidationTests.cs | 25 ++--- .../Validation/OptionsValidationTests.cs | 17 +-- .../Validation/ValidatorFactoryTests.cs | 8 +- .../Functions.Tests/RocketHostBuilderTests.cs | 8 +- test/Functions.Tests/TestAssemblyProvider.cs | 2 +- test/Metadata.Tests/GitVersionTests.cs | 6 +- .../FoundationTests.cs | 8 +- .../Helpers/SqliteExtension.cs | 7 +- .../Helpers/TestWebAppFixture.cs | 7 +- .../FoundationTests.cs | 6 +- .../ApiDescriptionData.cs | 12 +- .../ClassicFoundationTests.cs | 9 +- .../Helpers/TestWebAppFixture.cs | 8 +- test/Sample.Core.Tests/FoundationTests.cs | 6 +- test/Sample.Core.Tests/HandleTestHostBase.cs | 2 +- .../LaunchRecords/CreateLaunchRecordTests.cs | 6 +- .../LaunchRecords/GetLaunchRecordTests.cs | 6 +- .../LaunchRecords/ListLaunchRecordsTests.cs | 6 +- .../LaunchRecords/RemoveLaunchRecordsTests.cs | 6 +- .../LaunchRecords/UpdateLaunchRecordTests.cs | 8 +- .../Rockets/CreateRocketTests.cs | 8 +- .../Rockets/GetRocketTests.cs | 6 +- .../Rockets/ListRocketsTests.cs | 6 +- .../Rockets/RemoveRocketsTests.cs | 6 +- .../Rockets/UpdateRocketTests.cs | 8 +- test/Sample.Graphql.Tests/FoundationTests.cs | 9 +- .../Helpers/GraphQlAppFixture.cs | 7 +- .../Helpers/GraphQlExtension.cs | 33 ++---- .../Helpers/SqliteExtension.cs | 4 - .../Helpers/TemporaryGraphQlExtension.cs | 6 +- .../LaunchRecords/CreateLaunchRecordTests.cs | 13 +-- .../LaunchRecords/GetLaunchRecordTests.cs | 11 +- .../LaunchRecords/ListLaunchRecordsTests.cs | 11 +- .../LaunchRecords/RemoveLaunchRecordsTests.cs | 11 +- .../LaunchRecords/UpdateLaunchRecordTests.cs | 11 +- .../Sample.Graphql.Tests/ModuleInitializer.cs | 7 +- test/Sample.Graphql.Tests/NamedSchemaTests.cs | 2 +- .../Rockets/CreateRocketTests.cs | 24 +--- .../Rockets/GetRocketTests.cs | 10 +- .../Rockets/ListRocketsTests.cs | 11 +- .../Rockets/RemoveRocketsTests.cs | 13 +-- .../Rockets/UpdateRocketTests.cs | 15 +-- .../SqliteConnectionService.cs | 11 +- .../StrawberryShakeSerializerTests.cs | 24 ++-- test/Sample.Grpc.Tests/FoundationTests.cs | 8 +- .../Helpers/TestWebAppFixture.cs | 7 +- .../LaunchRecords/CreateLaunchRecordTests.cs | 10 +- .../LaunchRecords/GetLaunchRecordTests.cs | 7 +- .../LaunchRecords/ListLaunchRecordsTests.cs | 10 +- .../LaunchRecords/RemoveLaunchRecordsTests.cs | 7 +- .../LaunchRecords/UpdateLaunchRecordTests.cs | 14 +-- .../Rockets/CreateRocketTests.cs | 10 +- .../Rockets/GetRocketTests.cs | 9 +- .../Rockets/ListRocketsTests.cs | 10 +- .../Rockets/RemoveRocketsTests.cs | 12 +- .../Rockets/UpdateRocketTests.cs | 9 +- .../SqliteConnectionService.cs | 11 +- .../CustomMessageHandlerIntegrationTest.cs | 14 +-- .../CustomValidatorIntegrationTest.cs | 6 +- .../Validation/WebApplicationFactoryHelper.cs | 4 +- test/Sample.Pages.Tests/FoundationTests.cs | 6 +- .../Helpers/TestWebAppFixture.cs | 7 +- .../SqliteConnectionService.cs | 11 +- .../ApiDescriptionData.cs | 12 +- test/Sample.Restful.Tests/FoundationTests.cs | 11 +- .../Helpers/SqliteExtension.cs | 4 +- .../Helpers/TestWebAppFixture.cs | 8 +- .../Helpers/WebAppFixtureTest.cs | 2 +- .../RestfulConventionTests.cs | 1 + .../SqliteConnectionService.cs | 11 +- 255 files changed, 921 insertions(+), 1584 deletions(-) diff --git a/.build/Build.cs b/.build/Build.cs index 8238cbd87..e09416e3f 100644 --- a/.build/Build.cs +++ b/.build/Build.cs @@ -1,19 +1,14 @@ -using System.Diagnostics; using System.Net; using System.Net.Sockets; -using System.Reflection; using Nuke.Common; using Nuke.Common.CI; using Nuke.Common.Execution; using Nuke.Common.Git; using Nuke.Common.ProjectModel; -using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.MSBuild; -using Polly; using Rocket.Surgery.Nuke.DotNetCore; -using Serilog; [PublicAPI] [UnsetVisualStudioEnvironmentVariables] diff --git a/LaunchPad.sln b/LaunchPad.sln index 49b1ac27b..d20b12890 100644 --- a/LaunchPad.sln +++ b/LaunchPad.sln @@ -13,6 +13,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{DF33E0FB-9 ProjectSection(SolutionItems) = preProject test\Directory.Build.props = test\Directory.Build.props test\Directory.Build.targets = test\Directory.Build.targets + test\.editorconfig = test\.editorconfig EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = ".build", ".build\.build.csproj", "{166F1873-4CAE-4F54-88B6-5FE79678846B}" diff --git a/sample/.editorconfig b/sample/.editorconfig index b2d2dbd7c..f6b41fc2f 100644 --- a/sample/.editorconfig +++ b/sample/.editorconfig @@ -8,3 +8,4 @@ dotnet_diagnostic.CA1822.severity = none dotnet_diagnostic.CA5394.severity = none dotnet_diagnostic.CA1707.severity = none resharper_virtual_member_call_in_constructor_highlighting = none +resharper_nullable_warning_suppression_is_used_highlighting = none diff --git a/sample/Directory.Build.props b/sample/Directory.Build.props index 29c5d869f..9bd3e9d28 100644 --- a/sample/Directory.Build.props +++ b/sample/Directory.Build.props @@ -4,6 +4,7 @@ true false $(NoWarn);1591 + false diff --git a/sample/Sample.BlazorServer/Program.cs b/sample/Sample.BlazorServer/Program.cs index 31350c3e3..8ae40cc9a 100644 --- a/sample/Sample.BlazorServer/Program.cs +++ b/sample/Sample.BlazorServer/Program.cs @@ -15,7 +15,7 @@ public static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default), z => z.WithConventionsFrom(GetConventions)) + .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)) .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); } } diff --git a/sample/Sample.BlazorServer/Startup.cs b/sample/Sample.BlazorServer/Startup.cs index 29688215c..f201ea493 100644 --- a/sample/Sample.BlazorServer/Startup.cs +++ b/sample/Sample.BlazorServer/Startup.cs @@ -3,14 +3,9 @@ namespace Sample.BlazorServer; -public class Startup +public class Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 diff --git a/sample/Sample.Classic.Restful/Controllers/LaunchRecordController.cs b/sample/Sample.Classic.Restful/Controllers/LaunchRecordController.cs index 91a436039..9ea993492 100644 --- a/sample/Sample.Classic.Restful/Controllers/LaunchRecordController.cs +++ b/sample/Sample.Classic.Restful/Controllers/LaunchRecordController.cs @@ -57,7 +57,6 @@ public partial class LaunchRecordController : RestfulApiController /// /// Remove a launch record /// - /// /// /// [HttpDelete("{id:guid}")] diff --git a/sample/Sample.Classic.Restful/Controllers/WeatherForecastController.cs b/sample/Sample.Classic.Restful/Controllers/WeatherForecastController.cs index f912e06d9..5bf7499ba 100644 --- a/sample/Sample.Classic.Restful/Controllers/WeatherForecastController.cs +++ b/sample/Sample.Classic.Restful/Controllers/WeatherForecastController.cs @@ -4,20 +4,13 @@ namespace Sample.Classic.Restful.Controllers; [Route("[controller]")] -public class WeatherForecastController : RestfulApiController +public class WeatherForecastController(ILogger logger) : RestfulApiController { private static readonly string[] Summaries = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; - private readonly ILogger _logger; - - public WeatherForecastController(ILogger logger) - { - _logger = logger; - } - [HttpGet] public IEnumerable Get() { diff --git a/sample/Sample.Classic.Restful/Program.cs b/sample/Sample.Classic.Restful/Program.cs index 1cfe5b78b..d8e3a450b 100644 --- a/sample/Sample.Classic.Restful/Program.cs +++ b/sample/Sample.Classic.Restful/Program.cs @@ -17,6 +17,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default), z => z.WithConventionsFrom(Imports.GetConventions)); + .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(Imports.GetConventions)); } } diff --git a/sample/Sample.Classic.Restful/Startup.cs b/sample/Sample.Classic.Restful/Startup.cs index 0b238313b..eea22f851 100644 --- a/sample/Sample.Classic.Restful/Startup.cs +++ b/sample/Sample.Classic.Restful/Startup.cs @@ -9,14 +9,9 @@ namespace Sample.Classic.Restful; /// /// Startup interop (here for testing only or for 3.1 support) /// -public class Startup +public class Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) diff --git a/sample/Sample.Command/Program.cs b/sample/Sample.Command/Program.cs index 59558ec4f..452ae4b3e 100644 --- a/sample/Sample.Command/Program.cs +++ b/sample/Sample.Command/Program.cs @@ -33,45 +33,28 @@ public class InstanceThing } -public class Dump : Command +public class Dump(IConfiguration configuration, ILogger logger, InstanceThing instanceThing) + : Command { - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - private readonly InstanceThing _instanceThing; - - public Dump(IConfiguration configuration, ILogger logger, InstanceThing instanceThing) - { - _configuration = configuration; - _logger = logger; - _instanceThing = instanceThing; - } - public override int Execute([NotNull] CommandContext context, [NotNull] AppSettings settings) { // ReSharper disable once TemplateIsNotCompileTimeConstantProblem - _logger.LogInformation(_instanceThing.From); - foreach (var item in _configuration.AsEnumerable().Reverse()) + logger.LogInformation(instanceThing.From); + foreach (var item in configuration.AsEnumerable().Reverse()) { - _logger.LogInformation("{Key}: {Value}", item.Key, item.Value ?? string.Empty); + logger.LogInformation("{Key}: {Value}", item.Key, item.Value ?? string.Empty); } return 1; } } -public class DefaultCommand : Command +public class DefaultCommand(ILogger logger) : Command { - private readonly ILogger _logger; - - public DefaultCommand(ILogger logger) - { - _logger = logger; - } - public override int Execute([NotNull] CommandContext context, [NotNull] AppSettings settings) { Console.WriteLine("Hello World!"); - _logger.LogInformation("Test"); + logger.LogInformation("Test"); return 1; } } diff --git a/sample/Sample.Core/DataConvention.cs b/sample/Sample.Core/DataConvention.cs index 69857bafe..96d8fb3e9 100644 --- a/sample/Sample.Core/DataConvention.cs +++ b/sample/Sample.Core/DataConvention.cs @@ -34,7 +34,7 @@ public void Register(IConventionContext context, IConfiguration configuration, I ); #if NET // temp? - services.TryAddScoped(_ => _.GetRequiredService>().CreateDbContext()); + services.TryAddScoped(provider => provider.GetRequiredService>().CreateDbContext()); #endif } } diff --git a/sample/Sample.Core/DataGenerationConvention.cs b/sample/Sample.Core/DataGenerationConvention.cs index af70a431c..aacf58625 100644 --- a/sample/Sample.Core/DataGenerationConvention.cs +++ b/sample/Sample.Core/DataGenerationConvention.cs @@ -18,18 +18,11 @@ public void Register(IConventionContext context, IConfiguration configuration, I services.Insert(0, ServiceDescriptor.Singleton()); } - private class HostedService : IHostedService + private class HostedService(IServiceProvider serviceProvider) : IHostedService { - private readonly IServiceProvider _serviceProvider; - - public HostedService(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public async Task StartAsync(CancellationToken cancellationToken) { - await _serviceProvider.WithScoped().Invoke( + await serviceProvider.WithScoped().Invoke( async dbContext => { await dbContext.Database.EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); diff --git a/sample/Sample.Core/Domain/LaunchRecord.cs b/sample/Sample.Core/Domain/LaunchRecord.cs index 5733223d3..f6fef9ff9 100644 --- a/sample/Sample.Core/Domain/LaunchRecord.cs +++ b/sample/Sample.Core/Domain/LaunchRecord.cs @@ -1,4 +1,5 @@ -using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Rocket.Surgery.LaunchPad.EntityFramework; using Sample.Core.Models; @@ -8,8 +9,10 @@ namespace Sample.Core.Domain; public class LaunchRecord // : ILaunchRecord { public LaunchRecordId Id { get; set; } - public string? Partner { get; set; } = null!; - public string? Payload { get; set; } = null!; + [StringLength(1000)] + public string? Partner { get; set; } + [StringLength(1000)] + public string? Payload { get; set; } public long PayloadWeightKg { get; set; } public DateTimeOffset? ActualLaunchDate { get; set; } public DateTimeOffset ScheduledLaunchDate { get; set; } diff --git a/sample/Sample.Core/Domain/ReadyRocket.cs b/sample/Sample.Core/Domain/ReadyRocket.cs index 19baeadc3..793661f40 100644 --- a/sample/Sample.Core/Domain/ReadyRocket.cs +++ b/sample/Sample.Core/Domain/ReadyRocket.cs @@ -1,4 +1,5 @@ -using Microsoft.EntityFrameworkCore; +using System.ComponentModel.DataAnnotations; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Rocket.Surgery.LaunchPad.EntityFramework; using Sample.Core.Models; @@ -11,6 +12,7 @@ namespace Sample.Core.Domain; public class ReadyRocket // : IReadyRocket { public RocketId Id { get; set; } + [StringLength(30)] public string SerialNumber { get; set; } = null!; public RocketType Type { get; set; } diff --git a/sample/Sample.Core/Domain/RocketDbContext.cs b/sample/Sample.Core/Domain/RocketDbContext.cs index fca1a493f..662ce13d5 100644 --- a/sample/Sample.Core/Domain/RocketDbContext.cs +++ b/sample/Sample.Core/Domain/RocketDbContext.cs @@ -6,12 +6,8 @@ namespace Sample.Core.Domain; -public class RocketDbContext : LpContext +public class RocketDbContext(DbContextOptions? options = null) : LpContext(options ?? new DbContextOptions()) { - public RocketDbContext(DbContextOptions? options = null) : base(options ?? new DbContextOptions()) - { - } - public DbSet Rockets { get; set; } = null!; public DbSet LaunchRecords { get; set; } = null!; @@ -28,7 +24,7 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura #endif } -public class StronglyTypedIdValueConverterSelector : ValueConverterSelector +public class StronglyTypedIdValueConverterSelector(ValueConverterSelectorDependencies dependencies) : ValueConverterSelector(dependencies) { [return: NotNullIfNotNull("type")] private static Type? UnwrapNullableType(Type? type) @@ -45,10 +41,6 @@ public class StronglyTypedIdValueConverterSelector : ValueConverterSelector private readonly ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo> _converters = new ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo>(); - public StronglyTypedIdValueConverterSelector(ValueConverterSelectorDependencies dependencies) : base(dependencies) - { - } - public override IEnumerable Select(Type modelClrType, Type? providerClrType = null) { var baseConverters = base.Select(modelClrType, providerClrType); diff --git a/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs index 560e04569..4e56a79ee 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs @@ -91,22 +91,13 @@ public Validator() } } - private class Handler : IRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public async Task Handle(Request request, CancellationToken cancellationToken) { - var record = _mapper.Map(request); + var record = mapper.Map(request); - var rocket = await _dbContext.Rockets.FindAsync(new object[] { request.RocketId }, cancellationToken); + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.RocketId }, cancellationToken); if (rocket == null) { throw new RequestFailedException("Rocket not found!"); @@ -114,8 +105,8 @@ public async Task Handle(Request request, CancellationToken cancellati record.Rocket = rocket; - await _dbContext.AddAsync(record, cancellationToken).ConfigureAwait(false); - await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + await dbContext.AddAsync(record, cancellationToken).ConfigureAwait(false); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return new Response { diff --git a/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs index 520fca8a4..00497661d 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs @@ -32,18 +32,11 @@ public Validator() } [UsedImplicitly] - private class Handler : IRequestHandler + private class Handler(RocketDbContext dbContext) : IRequestHandler { - private readonly RocketDbContext _dbContext; - - public Handler(RocketDbContext dbContext) - { - _dbContext = dbContext; - } - public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await _dbContext.LaunchRecords.FindAsync(new object[] { request.Id }, cancellationToken); + var rocket = await dbContext.LaunchRecords.FindAsync(new object[] { request.Id }, cancellationToken); if (rocket == null) { throw new NotFoundException(); @@ -55,8 +48,8 @@ public async Task Handle(Request request, CancellationToken cancellationToken) throw new NotAuthorizedException("Unable to operate on given record"); } - _dbContext.Remove(rocket); - await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + dbContext.Remove(rocket); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } } } diff --git a/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs index 185317406..fe1e41d50 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs @@ -102,20 +102,12 @@ public Validator() } } - private class Handler : PatchRequestHandler, IRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper, IMediator mediator) + : PatchRequestHandler(mediator), IRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper, IMediator mediator) : base(mediator) - { - _dbContext = dbContext; - _mapper = mapper; - } - private async Task GetLaunchRecord(LaunchRecordId id, CancellationToken cancellationToken) { - var rocket = await _dbContext.LaunchRecords + var rocket = await dbContext.LaunchRecords .Include(z => z.Rocket) .FirstOrDefaultAsync(z => z.Id == id, cancellationToken) .ConfigureAwait(false); @@ -130,18 +122,18 @@ private async Task GetLaunchRecord(LaunchRecordId id, Cancellation protected override async Task GetRequest(PatchRequest patchRequest, CancellationToken cancellationToken) { var rocket = await GetLaunchRecord(patchRequest.Id, cancellationToken); - return _mapper.Map(_mapper.Map(rocket)); + return mapper.Map(mapper.Map(rocket)); } public async Task Handle(Request request, CancellationToken cancellationToken) { var rocket = await GetLaunchRecord(request.Id, cancellationToken); - _mapper.Map(request, rocket); - _dbContext.Update(rocket); - await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + mapper.Map(request, rocket); + dbContext.Update(rocket); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return _mapper.Map(rocket); + return mapper.Map(rocket); } } } diff --git a/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs index 62c9b2514..7c51216e4 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs @@ -32,20 +32,11 @@ public Validator() } } - private class Handler : IRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await _dbContext.LaunchRecords + var rocket = await dbContext.LaunchRecords .Include(x => x.Rocket) .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken); if (rocket == null) @@ -53,7 +44,7 @@ public async Task Handle(Request request, CancellationToken c throw new NotFoundException(); } - return _mapper.Map(rocket); + return mapper.Map(rocket); } } } diff --git a/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs b/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs index 3d434cf18..f89c8a043 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs @@ -18,24 +18,13 @@ public static class ListLaunchRecords // TODO: Paging model! public record Request(RocketType? RocketType) : IStreamRequest; - private class Validator : AbstractValidator - { - } + private class Validator : AbstractValidator; - private class Handler : IStreamRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IStreamRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public IAsyncEnumerable Handle(Request request, CancellationToken cancellationToken) { - var query = _dbContext.LaunchRecords + var query = dbContext.LaunchRecords .Include(x => x.Rocket) .AsQueryable(); if (request.RocketType.HasValue) @@ -44,7 +33,7 @@ public IAsyncEnumerable Handle(Request request, CancellationT } return query - .ProjectTo(_mapper.ConfigurationProvider) + .ProjectTo(mapper.ConfigurationProvider) .ToAsyncEnumerable(); } } diff --git a/sample/Sample.Core/Operations/Rockets/CreateRocket.cs b/sample/Sample.Core/Operations/Rockets/CreateRocket.cs index 63833a024..0b979c1a1 100644 --- a/sample/Sample.Core/Operations/Rockets/CreateRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/CreateRocket.cs @@ -63,20 +63,11 @@ public Validator() } } - private class Handler : IRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public async Task Handle(Request request, CancellationToken cancellationToken) { - var existingRocket = await _dbContext.Rockets.AsQueryable() + var existingRocket = await dbContext.Rockets.AsQueryable() .FirstOrDefaultAsync(z => z.SerialNumber == request.SerialNumber, cancellationToken); if (existingRocket != null) { @@ -95,9 +86,9 @@ public async Task Handle(Request request, CancellationToken cancellati }; } - var rocket = _mapper.Map(request); - await _dbContext.AddAsync(rocket, cancellationToken).ConfigureAwait(false); - await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + var rocket = mapper.Map(request); + await dbContext.AddAsync(rocket, cancellationToken).ConfigureAwait(false); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return new Response { diff --git a/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs b/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs index 5d81c2fa9..756bda824 100644 --- a/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs @@ -30,25 +30,18 @@ public Validator() } } - private class Handler : IRequestHandler + private class Handler(RocketDbContext dbContext) : IRequestHandler { - private readonly RocketDbContext _dbContext; - - public Handler(RocketDbContext dbContext) - { - _dbContext = dbContext; - } - public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await _dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); if (rocket == null) { throw new NotFoundException(); } - _dbContext.Remove(rocket); - await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + dbContext.Remove(rocket); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } } } diff --git a/sample/Sample.Core/Operations/Rockets/EditRocket.cs b/sample/Sample.Core/Operations/Rockets/EditRocket.cs index fb236a7c1..3c2290be1 100644 --- a/sample/Sample.Core/Operations/Rockets/EditRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/EditRocket.cs @@ -72,20 +72,12 @@ public RequestValidator() } } - private class RequestHandler : PatchRequestHandler, IRequestHandler + private class RequestHandler(RocketDbContext dbContext, IMapper mapper, IMediator mediator) + : PatchRequestHandler(mediator), IRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public RequestHandler(RocketDbContext dbContext, IMapper mapper, IMediator mediator) : base(mediator) - { - _dbContext = dbContext; - _mapper = mapper; - } - private async Task GetRocket(RocketId id, CancellationToken cancellationToken) { - var rocket = await _dbContext.Rockets.FindAsync(new object[] { id }, cancellationToken) + var rocket = await dbContext.Rockets.FindAsync(new object[] { id }, cancellationToken) .ConfigureAwait(false); if (rocket == null) { @@ -98,7 +90,7 @@ public RequestHandler(RocketDbContext dbContext, IMapper mapper, IMediator media protected override async Task GetRequest(PatchRequest patchRequest, CancellationToken cancellationToken) { var rocket = await GetRocket(patchRequest.Id, cancellationToken); - return _mapper.Map(_mapper.Map(rocket)); + return mapper.Map(mapper.Map(rocket)); } public async Task Handle(Request request, CancellationToken cancellationToken) @@ -109,11 +101,11 @@ public async Task Handle(Request request, CancellationToken cancell throw new NotFoundException(); } - _mapper.Map(request, rocket); - _dbContext.Update(rocket); - await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + mapper.Map(request, rocket); + dbContext.Update(rocket); + await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return _mapper.Map(rocket); + return mapper.Map(rocket); } } } diff --git a/sample/Sample.Core/Operations/Rockets/GetRocket.cs b/sample/Sample.Core/Operations/Rockets/GetRocket.cs index bf5ac0813..c2e40291f 100644 --- a/sample/Sample.Core/Operations/Rockets/GetRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/GetRocket.cs @@ -31,26 +31,17 @@ public Validator() } } - private class Handler : IRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await _dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken).ConfigureAwait(false); + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken).ConfigureAwait(false); if (rocket == null) { throw new NotFoundException(); } - return _mapper.Map(rocket); + return mapper.Map(rocket); } } } diff --git a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs index 094ce6479..6c6cf7bae 100644 --- a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs +++ b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs @@ -36,32 +36,23 @@ public Validator() } } - private class Handler : IRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await _dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); if (rocket == null) { throw new NotFoundException(); } - var launchRecord = await _dbContext.LaunchRecords.FindAsync(new object[] { request.LaunchRecordId }, cancellationToken); + var launchRecord = await dbContext.LaunchRecords.FindAsync(new object[] { request.LaunchRecordId }, cancellationToken); if (launchRecord == null) { throw new NotFoundException(); } - return _mapper.Map(launchRecord); + return mapper.Map(launchRecord); } } } diff --git a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs index 1042123fe..64426958b 100644 --- a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs +++ b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs @@ -31,28 +31,19 @@ public Validator() } } - private class Handler : IStreamRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IStreamRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public async IAsyncEnumerable Handle(Request request, [EnumeratorCancellation] CancellationToken cancellationToken) { - var rocket = await _dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); if (rocket == null) { throw new NotFoundException(); } - var query = _dbContext.LaunchRecords.AsQueryable() + var query = dbContext.LaunchRecords.AsQueryable() .Where(z => z.RocketId == rocket.Id) - .ProjectTo(_mapper.ConfigurationProvider); + .ProjectTo(mapper.ConfigurationProvider); await foreach (var item in query.AsAsyncEnumerable().WithCancellation(cancellationToken)) { yield return item; diff --git a/sample/Sample.Core/Operations/Rockets/ListRockets.cs b/sample/Sample.Core/Operations/Rockets/ListRockets.cs index 05d638b60..3e1a2ba93 100644 --- a/sample/Sample.Core/Operations/Rockets/ListRockets.cs +++ b/sample/Sample.Core/Operations/Rockets/ListRockets.cs @@ -18,30 +18,19 @@ public static class ListRockets /// The type of the rocket public record Request(RocketType? RocketType) : IStreamRequest; - private class Validator : AbstractValidator - { - } + private class Validator : AbstractValidator; - private class Handler : IStreamRequestHandler + private class Handler(RocketDbContext dbContext, IMapper mapper) : IStreamRequestHandler { - private readonly RocketDbContext _dbContext; - private readonly IMapper _mapper; - - public Handler(RocketDbContext dbContext, IMapper mapper) - { - _dbContext = dbContext; - _mapper = mapper; - } - public IAsyncEnumerable Handle(Request request, CancellationToken cancellationToken) { - var query = _dbContext.Rockets.AsQueryable(); + var query = dbContext.Rockets.AsQueryable(); if (request.RocketType.HasValue) { query = query.Where(z => z.Type == request.RocketType); } - return query.ProjectTo(_mapper.ConfigurationProvider).AsAsyncEnumerable(); + return query.ProjectTo(mapper.ConfigurationProvider).AsAsyncEnumerable(); } } } diff --git a/sample/Sample.Function/TestFunction.cs b/sample/Sample.Function/TestFunction.cs index e16038f06..f38c6de78 100644 --- a/sample/Sample.Function/TestFunction.cs +++ b/sample/Sample.Function/TestFunction.cs @@ -7,15 +7,8 @@ namespace Sample_Function; -public class TestFunction +public class TestFunction(Service service) { - private readonly Service _service; - - public TestFunction(Service service) - { - _service = service; - } - [FunctionName("TestFunction")] public async Task Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] @@ -29,16 +22,18 @@ ILogger log using var reader = new StreamReader(req.Body); var requestBody = await reader.ReadToEndAsync(); - dynamic data = JsonConvert.DeserializeObject(requestBody); +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. #pragma warning disable CA1508 + dynamic data = JsonConvert.DeserializeObject(requestBody); name ??= data?.name; +#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. #pragma warning restore CA1508 var responseMessage = string.IsNullOrEmpty(name) ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." : $"Hello, {name}. This HTTP triggered function executed successfully."; - responseMessage += " " + _service.Value; + responseMessage += " " + service.Value; return new OkObjectResult(responseMessage); } diff --git a/sample/Sample.Graphql/Program.cs b/sample/Sample.Graphql/Program.cs index bd8422f27..d440e6804 100644 --- a/sample/Sample.Graphql/Program.cs +++ b/sample/Sample.Graphql/Program.cs @@ -1,5 +1,4 @@ using HotChocolate.Types.Spatial; -using HotChocolate.Types.Spatial.Configuration; using Microsoft.Extensions.DependencyModel; using Rocket.Surgery.LaunchPad.AspNetCore; using Rocket.Surgery.LaunchPad.HotChocolate; @@ -9,7 +8,7 @@ var builder = WebApplication.CreateBuilder(args) .LaunchWith( - RocketBooster.ForDependencyContext(DependencyContext.Default), + RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(Imports.GetConventions) ); @@ -39,10 +38,8 @@ app.UseRouting(); -app.UseEndpoints(endpoints => endpoints.MapGraphQL()); +app.MapGraphQL(); app.Run(); -public partial class Program -{ -} +public partial class Program; diff --git a/sample/Sample.Grpc/Program.cs b/sample/Sample.Grpc/Program.cs index 03171fc93..98b3701a9 100644 --- a/sample/Sample.Grpc/Program.cs +++ b/sample/Sample.Grpc/Program.cs @@ -17,7 +17,7 @@ public static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default), z => z.WithConventionsFrom(GetConventions)) + .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); } } diff --git a/sample/Sample.Grpc/Services/LaunchRecordsService.cs b/sample/Sample.Grpc/Services/LaunchRecordsService.cs index adc57c1d8..316d91300 100644 --- a/sample/Sample.Grpc/Services/LaunchRecordsService.cs +++ b/sample/Sample.Grpc/Services/LaunchRecordsService.cs @@ -7,53 +7,44 @@ namespace Sample.Grpc.Services; -public class LaunchRecordsService : LaunchRecords.LaunchRecordsBase +public class LaunchRecordsService(IMediator mediator, IMapper mapper) : LaunchRecords.LaunchRecordsBase { - private readonly IMediator _mediator; - private readonly IMapper _mapper; - - public LaunchRecordsService(IMediator mediator, IMapper mapper) - { - _mediator = mediator; - _mapper = mapper; - } - public override async Task CreateLaunchRecord(CreateLaunchRecordRequest request, ServerCallContext context) { - var mRequest = _mapper.Map(request); - var response = await _mediator.Send(mRequest, context.CancellationToken); - return _mapper.Map(response); + var mRequest = mapper.Map(request); + var response = await mediator.Send(mRequest, context.CancellationToken); + return mapper.Map(response); } public override async Task EditLaunchRecord(UpdateLaunchRecordRequest request, ServerCallContext context) { - var mRequest = _mapper.Map(request); - var response = await _mediator.Send(mRequest, context.CancellationToken); - return _mapper.Map(response); + var mRequest = mapper.Map(request); + var response = await mediator.Send(mRequest, context.CancellationToken); + return mapper.Map(response); } public override async Task DeleteLaunchRecord(DeleteLaunchRecordRequest request, ServerCallContext context) { - var mRequest = _mapper.Map(request); - await _mediator.Send(mRequest, context.CancellationToken); + var mRequest = mapper.Map(request); + await mediator.Send(mRequest, context.CancellationToken); return new Empty(); } public override async Task GetLaunchRecords(GetLaunchRecordRequest request, ServerCallContext context) { - var mRequest = _mapper.Map(request); - var response = await _mediator.Send(mRequest, context.CancellationToken); - return _mapper.Map(response); + var mRequest = mapper.Map(request); + var response = await mediator.Send(mRequest, context.CancellationToken); + return mapper.Map(response); } public override async Task ListLaunchRecords( ListLaunchRecordsRequest request, IServerStreamWriter responseStream, ServerCallContext context ) { - var mRequest = _mapper.Map(request); - await foreach (var item in _mediator.CreateStream(mRequest, context.CancellationToken)) + var mRequest = mapper.Map(request); + await foreach (var item in mediator.CreateStream(mRequest, context.CancellationToken)) { - await responseStream.WriteAsync(_mapper.Map(item)); + await responseStream.WriteAsync(mapper.Map(item)); } } @@ -131,9 +122,7 @@ public GetLaunchRecordRequestValidator() } [UsedImplicitly] - private class ListLaunchRecordsRequestValidator : AbstractValidator - { - } + private class ListLaunchRecordsRequestValidator : AbstractValidator; [UsedImplicitly] private class DeleteLaunchRecordRequestValidator : AbstractValidator diff --git a/sample/Sample.Grpc/Services/RocketsService.cs b/sample/Sample.Grpc/Services/RocketsService.cs index c6b91d575..f9480e390 100644 --- a/sample/Sample.Grpc/Services/RocketsService.cs +++ b/sample/Sample.Grpc/Services/RocketsService.cs @@ -8,47 +8,38 @@ namespace Sample.Grpc.Services; -public class RocketsService : Rockets.RocketsBase +public class RocketsService(IMediator mediator, IMapper mapper) : Rockets.RocketsBase { - private readonly IMediator _mediator; - private readonly IMapper _mapper; - - public RocketsService(IMediator mediator, IMapper mapper) - { - _mediator = mediator; - _mapper = mapper; - } - public override async Task CreateRocket(CreateRocketRequest request, ServerCallContext context) { - var response = await _mediator.Send(_mapper.Map(request), context.CancellationToken); - return _mapper.Map(response); + var response = await mediator.Send(mapper.Map(request), context.CancellationToken); + return mapper.Map(response); } public override async Task EditRocket(UpdateRocketRequest request, ServerCallContext context) { - var response = await _mediator.Send(_mapper.Map(request), context.CancellationToken); - return _mapper.Map(response); + var response = await mediator.Send(mapper.Map(request), context.CancellationToken); + return mapper.Map(response); } public override async Task DeleteRocket(DeleteRocketRequest request, ServerCallContext context) { - await _mediator.Send(_mapper.Map(request), context.CancellationToken); + await mediator.Send(mapper.Map(request), context.CancellationToken); return new Empty(); } public override async Task GetRockets(GetRocketRequest request, ServerCallContext context) { - var response = await _mediator.Send(_mapper.Map(request), context.CancellationToken); - return _mapper.Map(response); + var response = await mediator.Send(mapper.Map(request), context.CancellationToken); + return mapper.Map(response); } public override async Task ListRockets(ListRocketsRequest request, IServerStreamWriter responseStream, ServerCallContext context) { - var mRequest = _mapper.Map(request); - await foreach (var item in _mediator.CreateStream(mRequest, context.CancellationToken)) + var mRequest = mapper.Map(request); + await foreach (var item in mediator.CreateStream(mRequest, context.CancellationToken)) { - await responseStream.WriteAsync(_mapper.Map(item)); + await responseStream.WriteAsync(mapper.Map(item)); } } @@ -129,9 +120,7 @@ public UpdateRocketRequestValidator() } [UsedImplicitly] - private class ListRocketsRequestValidator : AbstractValidator - { - } + private class ListRocketsRequestValidator : AbstractValidator; [UsedImplicitly] private class DeleteRocketRequestValidator : AbstractValidator diff --git a/sample/Sample.Pages/Pages/Rockets/Edit.cshtml.cs b/sample/Sample.Pages/Pages/Rockets/Edit.cshtml.cs index dc40c8b95..b71aa9237 100644 --- a/sample/Sample.Pages/Pages/Rockets/Edit.cshtml.cs +++ b/sample/Sample.Pages/Pages/Rockets/Edit.cshtml.cs @@ -4,21 +4,14 @@ namespace Sample.Pages.Pages.Rockets; -public class RocketEditModel : RocketViewModel +public class RocketEditModel(IMapper mapper) : RocketViewModel { - private readonly IMapper _mapper; - - public RocketEditModel(IMapper mapper) - { - _mapper = mapper; - } - [BindProperty] public EditRocket.Request Model { get; set; } = new(); public override async Task OnGet() { await base.OnGet(); - Model = _mapper.Map(Rocket); + Model = mapper.Map(Rocket); } public async Task OnPost() diff --git a/sample/Sample.Pages/Pages/Rockets/Index.cshtml.cs b/sample/Sample.Pages/Pages/Rockets/Index.cshtml.cs index ddfbe9305..51672b55e 100644 --- a/sample/Sample.Pages/Pages/Rockets/Index.cshtml.cs +++ b/sample/Sample.Pages/Pages/Rockets/Index.cshtml.cs @@ -5,21 +5,14 @@ namespace Sample.Pages.Pages.Rockets; -public class RocketIndexModel : PageModel +public class RocketIndexModel(IMediator mediator) : PageModel { - private readonly IMediator _mediator; - - public RocketIndexModel(IMediator mediator) - { - _mediator = mediator; - } - // [BindProperty] // public Movie Movie { get; set; } [UsedImplicitly] public IEnumerable Rockets { get; set; } = null!; public async Task OnGet() { - Rockets = await _mediator.CreateStream(new ListRockets.Request(null)).ToListAsync(HttpContext.RequestAborted); + Rockets = await mediator.CreateStream(new ListRockets.Request(null)).ToListAsync(HttpContext.RequestAborted); } } diff --git a/sample/Sample.Pages/Program.cs b/sample/Sample.Pages/Program.cs index 7ac47be86..c97d1434e 100644 --- a/sample/Sample.Pages/Program.cs +++ b/sample/Sample.Pages/Program.cs @@ -16,6 +16,6 @@ public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default), z => z.WithConventionsFrom(GetConventions)); + .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)); } } diff --git a/sample/Sample.Pages/Startup.cs b/sample/Sample.Pages/Startup.cs index e720de165..a87ddda2f 100644 --- a/sample/Sample.Pages/Startup.cs +++ b/sample/Sample.Pages/Startup.cs @@ -7,7 +7,7 @@ namespace Sample.Pages; -public class Startup +public class Startup(IConfiguration configuration) { private static Task WriteResponse(HttpContext context, HealthReport healthReport) { @@ -84,12 +84,7 @@ private static Task WriteResponse(HttpContext context, HealthReport healthReport ); } - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) diff --git a/sample/Sample.Restful.Client/Test1.cs b/sample/Sample.Restful.Client/Test1.cs index 2c670ba18..c49ed9270 100644 --- a/sample/Sample.Restful.Client/Test1.cs +++ b/sample/Sample.Restful.Client/Test1.cs @@ -1,5 +1,3 @@ -using Newtonsoft.Json; - namespace Sample.Restful.Client; public partial class RocketClient diff --git a/sample/Sample.Restful/Controllers/LaunchRecordController.cs b/sample/Sample.Restful/Controllers/LaunchRecordController.cs index 8cd35a15a..6bd64255f 100644 --- a/sample/Sample.Restful/Controllers/LaunchRecordController.cs +++ b/sample/Sample.Restful/Controllers/LaunchRecordController.cs @@ -20,9 +20,11 @@ public partial class LaunchRecordController : RestfulApiController /// /// Load details of a specific launch record /// + /// The id of the launch record /// The request context /// [HttpGet("{id:guid}")] + // ReSharper disable once RouteTemplates.ParameterTypeAndConstraintsMismatch public partial Task> GetLaunchRecord(LaunchRecordId id, GetLaunchRecord.Request request); /// diff --git a/sample/Sample.Restful/Controllers/RocketController.cs b/sample/Sample.Restful/Controllers/RocketController.cs index ba08c9f37..952cbe913 100644 --- a/sample/Sample.Restful/Controllers/RocketController.cs +++ b/sample/Sample.Restful/Controllers/RocketController.cs @@ -57,7 +57,6 @@ public partial class RocketController : RestfulApiController /// /// Remove a rocket /// - /// /// /// [HttpDelete("{id:guid}")] @@ -76,8 +75,11 @@ public partial class RocketController : RestfulApiController /// /// [HttpGet("{id:guid}/launch-records/{launchRecordId:guid}")] - // ReSharper disable once RouteTemplates.ParameterTypeAndConstraintsMismatch public partial Task> GetRocketLaunchRecord( - RocketId id, LaunchRecordId launchRecordId, GetRocketLaunchRecord.Request request + // ReSharper disable once RouteTemplates.ParameterTypeAndConstraintsMismatch + RocketId id, + // ReSharper disable once RouteTemplates.ParameterTypeAndConstraintsMismatch + LaunchRecordId launchRecordId, + GetRocketLaunchRecord.Request request ); } diff --git a/sample/Sample.Restful/Controllers/WeatherForecastController.cs b/sample/Sample.Restful/Controllers/WeatherForecastController.cs index f17264d4d..5cad6d10b 100644 --- a/sample/Sample.Restful/Controllers/WeatherForecastController.cs +++ b/sample/Sample.Restful/Controllers/WeatherForecastController.cs @@ -4,20 +4,13 @@ namespace Sample.Restful.Controllers; [Route("[controller]")] -public class WeatherForecastController : RestfulApiController +public class WeatherForecastController(ILogger logger) : RestfulApiController { private static readonly string[] Summaries = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; - private readonly ILogger _logger; - - public WeatherForecastController(ILogger logger) - { - _logger = logger; - } - [HttpGet] public IEnumerable Get() { diff --git a/sample/Sample.Restful/Program.cs b/sample/Sample.Restful/Program.cs index 945885daf..c1bd4fde3 100644 --- a/sample/Sample.Restful/Program.cs +++ b/sample/Sample.Restful/Program.cs @@ -147,15 +147,14 @@ static Task WriteResponse(HttpContext context, HealthReport healthReport) ); } -public partial class Program -{ -} +public partial class Program; internal class CustomHostedServiceOptions { public string? A { get; set; } - private class Validator : AbstractValidator + [UsedImplicitly] + private sealed class Validator : AbstractValidator { public Validator() { @@ -164,17 +163,12 @@ public Validator() } } -internal class CustomHostedService : BackgroundService +internal class CustomHostedService(IOptions options) : BackgroundService { - private readonly IOptions _options; - - public CustomHostedService(IOptions options) - { - _options = options; - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + protected override Task ExecuteAsync(CancellationToken stoppingToken) { - var v = _options.Value.A; + // ReSharper disable once UnusedVariable + var v = options.Value.A; + return Task.CompletedTask; } } diff --git a/sample/Sample.Worker/Program.cs b/sample/Sample.Worker/Program.cs index 3cb0221e6..30ab5c265 100644 --- a/sample/Sample.Worker/Program.cs +++ b/sample/Sample.Worker/Program.cs @@ -15,7 +15,7 @@ public static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default), z => z.WithConventionsFrom(GetConventions)) - .ConfigureServices((_, services) => { services.AddHostedService(); }); + .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)) + .ConfigureServices((_, services) => { services.AddHostedService(); }); } } diff --git a/sample/Sample.Worker/Worker.cs b/sample/Sample.Worker/Worker.cs index 1451fe3ca..ecab4a252 100644 --- a/sample/Sample.Worker/Worker.cs +++ b/sample/Sample.Worker/Worker.cs @@ -4,24 +4,15 @@ namespace Sample.Worker; -public class Worker : BackgroundService +public class BackgroundWorker(ILogger logger, IExecuteScoped mediator) : BackgroundService { - private readonly ILogger _logger; - private readonly IExecuteScoped _mediator; - - public Worker(ILogger logger, IExecuteScoped mediator) - { - _logger = logger; - _mediator = mediator; - } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { - var items = await _mediator.Invoke(m => m.CreateStream(new ListRockets.Request(null), stoppingToken)) + var items = await mediator.Invoke(m => m.CreateStream(new ListRockets.Request(null), stoppingToken)) .ToListAsync(stoppingToken); - _logger.LogInformation("Items: {@Items}", items); + logger.LogInformation("Items: {@Items}", items); await Task.Delay(1000, stoppingToken).ConfigureAwait(false); } } diff --git a/src/Analyzers/Composition/MatcherDefaults.cs b/src/Analyzers/Composition/MatcherDefaults.cs index 54b963c3e..d47f51890 100644 --- a/src/Analyzers/Composition/MatcherDefaults.cs +++ b/src/Analyzers/Composition/MatcherDefaults.cs @@ -31,8 +31,10 @@ public static ImmutableArray GetMatchers(Compilation c private static IEnumerable DefaultMatchers(Compilation compilation) { + // ReSharper disable NullableWarningSuppressionIsUsed var IBaseRequest = compilation.GetTypeByMetadataName("MediatR.IBaseRequest")!; var IStreamRequest = compilation.GetTypeByMetadataName("MediatR.IStreamRequest`1")!; + // ReSharper enable NullableWarningSuppressionIsUsed yield return new RestfulApiMethodBuilder(RestfulApiMethod.List) .MatchPrefix("List", SearchMethodPrefixes) .MatchParameterType(^1, IBaseRequest); diff --git a/src/Analyzers/Composition/RestfulApiParameterMatcher.cs b/src/Analyzers/Composition/RestfulApiParameterMatcher.cs index eb92c7082..b8e71a356 100644 --- a/src/Analyzers/Composition/RestfulApiParameterMatcher.cs +++ b/src/Analyzers/Composition/RestfulApiParameterMatcher.cs @@ -5,28 +5,20 @@ namespace Rocket.Surgery.LaunchPad.Analyzers.Composition; -internal class RestfulApiParameterMatcher : IRestfulApiParameterMatcher +internal class RestfulApiParameterMatcher( + Index parameterIndex, + ApiConventionNameMatchBehavior nameMatch, + string[] names, + ApiConventionTypeMatchBehavior typeMatch, + INamedTypeSymbol? type +) + : IRestfulApiParameterMatcher { - public RestfulApiParameterMatcher( - Index parameterIndex, - ApiConventionNameMatchBehavior nameMatch, - string[] names, - ApiConventionTypeMatchBehavior typeMatch, - INamedTypeSymbol? type - ) - { - ParameterIndex = parameterIndex; - NameMatch = nameMatch; - Names = names; - TypeMatch = typeMatch; - Type = type; - } - - public Index ParameterIndex { get; } - public ApiConventionNameMatchBehavior NameMatch { get; } - public string[] Names { get; } - public ApiConventionTypeMatchBehavior TypeMatch { get; } - public INamedTypeSymbol? Type { get; } + public Index ParameterIndex { get; } = parameterIndex; + public ApiConventionNameMatchBehavior NameMatch { get; } = nameMatch; + public string[] Names { get; } = names; + public ApiConventionTypeMatchBehavior TypeMatch { get; } = typeMatch; + public INamedTypeSymbol? Type { get; } = type; public bool IsMatch(ActionModel actionModel) { diff --git a/src/Analyzers/ControllerActionBodyGenerator.cs b/src/Analyzers/ControllerActionBodyGenerator.cs index 4346135a8..1a31019fd 100644 --- a/src/Analyzers/ControllerActionBodyGenerator.cs +++ b/src/Analyzers/ControllerActionBodyGenerator.cs @@ -56,6 +56,7 @@ private static string Pascalize(string input) var isUnitResult = symbol.ReturnType is INamedTypeSymbol { Arity: 1 } nts && nts.TypeArguments[0].MetadataName == "ActionResult"; var isStream = symbol.ReturnType.MetadataName == "IAsyncEnumerable`1"; + // ReSharper disable once NullableWarningSuppressionIsUsed var newSyntax = syntax .WithParameterList( syntax.ParameterList.RemoveNodes( @@ -87,9 +88,9 @@ private static string Pascalize(string input) var controllerAttachedProperties = parameterType .GetMembers() .SelectMany( - parameter => + par => { - return parameter switch + return par switch { IPropertySymbol { Type: not null, IsImplicitlyDeclared: false } ps => controllerBaseProperties.Where( p => SymbolEqualityComparer.Default.Equals(p.Type, ps.Type) @@ -99,7 +100,7 @@ private static string Pascalize(string input) ), _ => Enumerable.Empty() }; - }, (parameter, propertySymbol) => ( propertySymbol, parameter ) + }, static (param, propertySymbol) => ( propertySymbol, parameter: param ) ) .ToArray(); @@ -279,9 +280,11 @@ private static string Pascalize(string input) Key: "StatusCode", Value: { Kind: TypedConstantKind.Primitive, Value: int } } ) + // ReSharper disable once NullableWarningSuppressionIsUsed .Select(c => (int)c.Value.Value!); var constructorArguments = z .ConstructorArguments.Where(c => c is { Kind: TypedConstantKind.Primitive, Value: int }) + // ReSharper disable once NullableWarningSuppressionIsUsed .Select(c => (int)c.Value!); return namedArguments.Concat(constructorArguments); @@ -375,6 +378,7 @@ private static string Pascalize(string input) { if (symbol.GetAttribute("CreatedAttribute") is { ConstructorArguments: { Length: 1 } } created) { + // ReSharper disable once NullableWarningSuppressionIsUsed var actionName = (string)created.ConstructorArguments[0].Value!; var relatedMember = members.Single(z => z.symbol.Name == actionName); var routeValues = getRouteValues(parameterType, resultName, relatedMember); @@ -385,6 +389,7 @@ private static string Pascalize(string input) } else if (symbol.GetAttribute("AcceptedAttribute") is { ConstructorArguments: { Length: 1 } } accepted) { + // ReSharper disable once NullableWarningSuppressionIsUsed var actionName = (string)accepted.ConstructorArguments[0].Value!; var relatedMember = members.Single(z => z.symbol.Name == actionName); var routeValues = getRouteValues(parameterType, resultName, relatedMember); @@ -409,6 +414,7 @@ static ImmutableArray availableRouteParameters( (MethodDeclarationSyntax method, IMethodSymbol symbol, IRestfulApiMethodMatcher? matcher, IParameterSymbol? request) relatedMember ) { + // ReSharper disable once NullableWarningSuppressionIsUsed var parameterNames = relatedMember.symbol.Parameters.Remove(relatedMember.request!).Select(z => z.Name); parameterNames = parameterNames.Concat( relatedMember.request?.Type.GetMembers() @@ -644,8 +650,9 @@ private void GenerateMethods( ) { var (syntax, symbol, semanticModel) = valueTuple.Left; - var claimsPrincipal = semanticModel.Compilation.GetTypeByMetadataName("System.Security.Claims.ClaimsPrincipal")!; + // ReSharper disable NullableWarningSuppressionIsUsed var controllerBase = semanticModel.Compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Mvc.ControllerBase")!; + // ReSharper enable NullableWarningSuppressionIsUsed var controllerBaseProperties = controllerBase.GetMembers().OfType().Where(z => z.DeclaredAccessibility == Accessibility.Public).ToArray(); var compilation = valueTuple.Right; @@ -741,10 +748,10 @@ public void Initialize(IncrementalGeneratorInitializationContext context) && cds.Members.Any( z => z is MethodDeclarationSyntax && z.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword)) ), - (syntaxContext, _) => + (syntaxContext, cancellationToken) => ( syntax: (ClassDeclarationSyntax)syntaxContext.Node, - symbol: syntaxContext.SemanticModel.GetDeclaredSymbol((ClassDeclarationSyntax)syntaxContext.Node, _)!, + symbol: syntaxContext.SemanticModel.GetDeclaredSymbol((ClassDeclarationSyntax)syntaxContext.Node, cancellationToken)!, semanticModel: syntaxContext.SemanticModel ) ) diff --git a/src/Analyzers/GraphqlMutationActionBodyGenerator.cs b/src/Analyzers/GraphqlMutationActionBodyGenerator.cs index e89699cbe..70abc9d5b 100644 --- a/src/Analyzers/GraphqlMutationActionBodyGenerator.cs +++ b/src/Analyzers/GraphqlMutationActionBodyGenerator.cs @@ -1,11 +1,8 @@ using System.Collections.Immutable; -using System.Globalization; using System.Text; -using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Rocket.Surgery.LaunchPad.Analyzers.Composition; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Rocket.Surgery.LaunchPad.Analyzers; @@ -16,29 +13,6 @@ namespace Rocket.Surgery.LaunchPad.Analyzers; [Generator] public class GraphqlMutationActionBodyGenerator : IIncrementalGenerator { - /// - /// Same as Pascalize except that the first character is lower case - /// - /// - /// - private static string Camelize(string input) - { - var word = Pascalize(input); -#pragma warning disable CA1308 - return word.Length > 0 ? string.Concat(word.Substring(0, 1).ToLower(CultureInfo.InvariantCulture), word.Substring(1)) : word; -#pragma warning restore CA1308 - } - - /// - /// By default, pascalize converts strings to UpperCamelCase also removing underscores - /// - /// - /// - private static string Pascalize(string input) - { - return Regex.Replace(input, "(?:^|_| +)(.)", match => match.Groups[1].Value.ToUpper(CultureInfo.InvariantCulture)); - } - private static MethodDeclarationSyntax? GenerateMethod( SourceProductionContext context, INamedTypeSymbol mediator, @@ -52,11 +26,11 @@ IParameterSymbol parameter var otherParams = symbol.Parameters.Remove(parameter); var parameterType = (INamedTypeSymbol)parameter.Type; var isUnit = parameterType.AllInterfaces.Any(z => z.MetadataName == "IRequest"); - var isUnitResult = symbol.ReturnType is INamedTypeSymbol { Arity: 1 } nts && nts.TypeArguments[0].MetadataName == "ActionResult"; var isStream = symbol.ReturnType.MetadataName == "IAsyncEnumerable`1"; var newSyntax = syntax .WithParameterList( + // ReSharper disable once NullableWarningSuppressionIsUsed syntax.ParameterList.RemoveNodes( syntax.ParameterList.Parameters.SelectMany(z => z.AttributeLists), SyntaxRemoveOptions.KeepNoTrivia )! @@ -72,9 +46,9 @@ IParameterSymbol parameter var block = Block(); var resultName = parameter.Name == "result" ? "r" : "result"; - var mediatorParameter = otherParams.FirstOrDefault(parameter => SymbolEqualityComparer.Default.Equals(mediator, parameter.Type)); - var claimsPrincipalParameter = otherParams.FirstOrDefault(parameter => SymbolEqualityComparer.Default.Equals(claimsPrincipal, parameter.Type)); - var cancellationTokenParameter = otherParams.FirstOrDefault(parameter => SymbolEqualityComparer.Default.Equals(cancellationToken, parameter.Type)); + var mediatorParameter = otherParams.FirstOrDefault(param => SymbolEqualityComparer.Default.Equals(mediator, param.Type)); + var claimsPrincipalParameter = otherParams.FirstOrDefault(param => SymbolEqualityComparer.Default.Equals(claimsPrincipal, param.Type)); + var cancellationTokenParameter = otherParams.FirstOrDefault(param => SymbolEqualityComparer.Default.Equals(cancellationToken, param.Type)); if (mediatorParameter is null) { context.ReportDiagnostic( @@ -91,7 +65,7 @@ IParameterSymbol parameter var claimsPrincipalProperty = parameterType .GetMembers() .FirstOrDefault( - parameter => parameter switch + param => param switch { IPropertySymbol { Type: not null, IsImplicitlyDeclared: false } ps => SymbolEqualityComparer.Default.Equals( claimsPrincipal, ps.Type @@ -135,6 +109,7 @@ IParameterSymbol parameter var expressions = new List(); if (hasClaimsPrincipal) { + // ReSharper disable NullableWarningSuppressionIsUsed expressions.Add( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, @@ -142,10 +117,12 @@ IParameterSymbol parameter IdentifierName(claimsPrincipalParameter!.Name) ) ); + // ReSharper enable NullableWarningSuppressionIsUsed } if (cancellationTokenParameter is { }) { + // ReSharper disable NullableWarningSuppressionIsUsed expressions.Add( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, @@ -153,6 +130,7 @@ IParameterSymbol parameter IdentifierName(claimsPrincipalParameter!.Name) ) ); + // ReSharper enable NullableWarningSuppressionIsUsed } if (expressions.Any()) @@ -268,15 +246,13 @@ static ExpressionSyntax streamMediatorRequest(ExpressionSyntax nameSyntax, IPara private void GenerateMethods( SourceProductionContext context, - ((ClassDeclarationSyntax syntax, INamedTypeSymbol symbol, SemanticModel semanticModel) Left, Compilation Right) valueTuple + (ClassDeclarationSyntax syntax, INamedTypeSymbol symbol, SemanticModel semanticModel) valueTuple ) { - var (syntax, symbol, semanticModel) = valueTuple.Left; + var (syntax, symbol, semanticModel) = valueTuple; var claimsPrincipal = semanticModel.Compilation.GetTypeByMetadataName("System.Security.Claims.ClaimsPrincipal")!; var mediator = semanticModel.Compilation.GetTypeByMetadataName("MediatR.IMediator")!; var cancellationToken = semanticModel.Compilation.GetTypeByMetadataName("System.Threading.CancellationToken")!; - var compilation = valueTuple.Right; - var matchers = MatcherDefaults.GetMatchers(compilation); var members = syntax.Members .OfType() .Where(z => z.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword))) @@ -359,16 +335,16 @@ public void Initialize(IncrementalGeneratorInitializationContext context) && cds.Members.Any( z => z is MethodDeclarationSyntax && z.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword)) ), - (syntaxContext, _) => + (syntaxContext, cancellationToken) => ( syntax: (ClassDeclarationSyntax)syntaxContext.Node, - symbol: syntaxContext.SemanticModel.GetDeclaredSymbol((ClassDeclarationSyntax)syntaxContext.Node, _)!, + symbol: syntaxContext.SemanticModel.GetDeclaredSymbol((ClassDeclarationSyntax)syntaxContext.Node, cancellationToken)!, semanticModel: syntaxContext.SemanticModel ) ) .Where(z => z.symbol is { }) ; - context.RegisterSourceOutput(syntaxProvider.Combine(context.CompilationProvider), GenerateMethods); + context.RegisterSourceOutput(syntaxProvider, GenerateMethods); } } diff --git a/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs b/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs index 2edd2c96d..85b9e4f3f 100644 --- a/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs +++ b/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs @@ -301,6 +301,7 @@ node is (ClassDeclarationSyntax or RecordDeclarationSyntax) and TypeDeclarationS ), static (syntaxContext, token) => ( syntax: (TypeDeclarationSyntax)syntaxContext.Node, semanticModel: syntaxContext.SemanticModel, + // ReSharper disable once NullableWarningSuppressionIsUsed symbol: syntaxContext.SemanticModel.GetDeclaredSymbol((TypeDeclarationSyntax)syntaxContext.Node, token)! ) ) @@ -327,6 +328,7 @@ node is (ClassDeclarationSyntax or RecordDeclarationSyntax) and TypeDeclarationS context.RegisterSourceOutput( values, + // ReSharper disable once NullableWarningSuppressionIsUsed static (productionContext, tuple) => GeneratePropertyTracking(productionContext, tuple.syntax, tuple.symbol, tuple.targetSymbol!) ); } diff --git a/src/Analyzers/InheritFromGenerator.cs b/src/Analyzers/InheritFromGenerator.cs index 1150bf14b..a27cfedde 100644 --- a/src/Analyzers/InheritFromGenerator.cs +++ b/src/Analyzers/InheritFromGenerator.cs @@ -80,6 +80,7 @@ AttributeData[] attributes { if (declaration.BaseList?.Types.Any(z => z.IsEquivalentTo(item)) != true) { + // ReSharper disable once NullableWarningSuppressionIsUsed classToInherit = ( classToInherit.AddBaseListTypes(item) as TypeDeclarationSyntax )!; } } @@ -323,15 +324,15 @@ node is (ClassDeclarationSyntax or RecordDeclarationSyntax) and TypeDeclarationS } recordDeclarationSyntax && recordDeclarationSyntax.AttributeLists.ContainsAttribute("InheritFrom"), static (syntaxContext, token) => ( syntax: (TypeDeclarationSyntax)syntaxContext.Node, semanticModel: syntaxContext.SemanticModel, + // ReSharper disable once NullableWarningSuppressionIsUsed symbol: syntaxContext.SemanticModel.GetDeclaredSymbol((TypeDeclarationSyntax)syntaxContext.Node, token)! ) ).Combine( context.CompilationProvider .Select( static (z, _) => ( compilation: z, - inheritFromAttribute: z.GetTypeByMetadataName( - "Rocket.Surgery.LaunchPad.Foundation.InheritFromAttribute" - )! ) + // ReSharper disable once NullableWarningSuppressionIsUsed + inheritFromAttribute: z.GetTypeByMetadataName("Rocket.Surgery.LaunchPad.Foundation.InheritFromAttribute")! ) ) ) .Select( @@ -350,6 +351,7 @@ node is (ClassDeclarationSyntax or RecordDeclarationSyntax) and TypeDeclarationS context.RegisterSourceOutput( values, + // ReSharper disable once NullableWarningSuppressionIsUsed static (productionContext, tuple) => GenerateInheritance(productionContext, tuple.compilation, tuple.syntax, tuple.symbol, tuple.attributes!) ); } diff --git a/src/Analyzers/PropertyTrackingGenerator.cs b/src/Analyzers/PropertyTrackingGenerator.cs index bb7794383..ad1215ad6 100644 --- a/src/Analyzers/PropertyTrackingGenerator.cs +++ b/src/Analyzers/PropertyTrackingGenerator.cs @@ -349,6 +349,7 @@ node is (ClassDeclarationSyntax or RecordDeclarationSyntax) and TypeDeclarationS ), static (syntaxContext, token) => ( syntax: (TypeDeclarationSyntax)syntaxContext.Node, semanticModel: syntaxContext.SemanticModel, + // ReSharper disable once NullableWarningSuppressionIsUsed symbol: syntaxContext.SemanticModel.GetDeclaredSymbol((TypeDeclarationSyntax)syntaxContext.Node, token)! ) ) @@ -375,6 +376,7 @@ node is (ClassDeclarationSyntax or RecordDeclarationSyntax) and TypeDeclarationS context.RegisterSourceOutput( values, + // ReSharper disable once NullableWarningSuppressionIsUsed static (productionContext, tuple) => GeneratePropertyTracking(productionContext, tuple.syntax, tuple.symbol, tuple.targetSymbol!) ); } diff --git a/src/AspNetCore.Blazor/Validation.cs b/src/AspNetCore.Blazor/Validation.cs index 0b6729d06..996b4c442 100644 --- a/src/AspNetCore.Blazor/Validation.cs +++ b/src/AspNetCore.Blazor/Validation.cs @@ -42,8 +42,9 @@ private static FieldIdentifier ToFieldIdentifier(EditContext editContext, string // It's an indexer // This code assumes C# conventions (one indexer named Item with one param) nextToken = nextToken.Substring(0, nextToken.Length - 1); - var prop = obj.GetType().GetProperty("Item"); - var indexerType = prop!.GetIndexParameters()[0].ParameterType; + // ReSharper disable once NullableWarningSuppressionIsUsed + var prop = obj.GetType().GetProperty("Item")!; + var indexerType = prop.GetIndexParameters()[0].ParameterType; var indexerValue = Convert.ChangeType(nextToken, indexerType, CultureInfo.InvariantCulture); newObj = prop.GetValue(obj, new[] { indexerValue }); } @@ -128,10 +129,13 @@ private static async void ValidateField( /// [Parameter] [DisallowNull] + // ReSharper disable once NullableWarningSuppressionIsUsed public IValidator? Validator { get; set; } = null!; + // ReSharper disable once NullableWarningSuppressionIsUsed [Inject] private IServiceProvider Services { get; set; } = null!; + // ReSharper disable once NullableWarningSuppressionIsUsed [CascadingParameter] private EditContext CurrentEditContext { get; set; } = null!; /// diff --git a/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj b/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj index bc703d187..abb40a023 100644 --- a/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj +++ b/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj @@ -5,6 +5,7 @@ $(PackageTags) Rocket.Surgery.LaunchPad.AspNetCore NewtonsoftJsonExports + false diff --git a/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs b/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs index c99881a2f..52e5972d8 100644 --- a/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs +++ b/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs @@ -10,10 +10,10 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore; /// A RFC 7807 compliant for . /// [PublicAPI] -public sealed class ValidationProblemDetailsNewtonsoftJsonConverter : JsonConverter +public sealed class ValidationProblemDetailsNewtonsoftJsonConverter : JsonConverter { /// - public override FluentValidationProblemDetails ReadJson( + public override FluentValidationProblemDetails? ReadJson( JsonReader reader, Type objectType, FluentValidationProblemDetails? existingValue, @@ -29,7 +29,7 @@ [NotNull] JsonSerializer serializer var annotatedProblemDetails = serializer.Deserialize(reader); if (annotatedProblemDetails == null) { - return null!; + return null; } var problemDetails = existingValue ?? new FluentValidationProblemDetails(); @@ -100,7 +100,7 @@ public AnnotatedProblemDetails(FluentValidationProblemDetails problemDetails) public string? Type { get; set; } [JsonProperty(PropertyName = "title", NullValueHandling = NullValueHandling.Ignore)] - public string? Title { get; set; } + public string? Title { get; set; } [JsonProperty(PropertyName = "status", NullValueHandling = NullValueHandling.Ignore)] public int? Status { get; set; } diff --git a/src/AspNetCore.Testing/IResettableAlbaExtension.cs b/src/AspNetCore.Testing/IResettableAlbaExtension.cs index c5d515bf6..2c449b887 100644 --- a/src/AspNetCore.Testing/IResettableAlbaExtension.cs +++ b/src/AspNetCore.Testing/IResettableAlbaExtension.cs @@ -10,6 +10,15 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Testing; /// public interface IResettableAlbaExtension : IAlbaExtension { + /// + /// Reset the provider async + /// + /// + /// Task ResetAsync(IServiceProvider serviceProvider); + /// + /// Reset the provider + /// + /// void Reset(IServiceProvider serviceProvider); } diff --git a/src/AspNetCore.Testing/LaunchPadExtension.cs b/src/AspNetCore.Testing/LaunchPadExtension.cs index 3486c8950..c7c89b1d3 100644 --- a/src/AspNetCore.Testing/LaunchPadExtension.cs +++ b/src/AspNetCore.Testing/LaunchPadExtension.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.HttpLogging; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Rocket.Surgery.Conventions.Testing; @@ -12,51 +11,88 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Testing; +/// +/// An that is used for launchpad is used to get the assembly to test +/// +/// public class LaunchPadExtension : LaunchPadExtension { + /// + /// Create the test extension + /// + /// public LaunchPadExtension(ILoggerFactory loggerFactory) : base(typeof(TTestAssembly), loggerFactory) { } } +#pragma warning disable CA1816 +#pragma warning disable CA1063 +/// +/// An that is used for launchpad +/// public class LaunchPadExtension : IAlbaExtension { private readonly Assembly _testAssemblyReference; private readonly ILoggerFactory _loggerFactory; - public LaunchPadExtension(object testAssemblyReference, ILoggerFactory loggerFactory) : base() + /// + /// Create the extension, with the given object for use as an assembly reference. + /// + /// + /// + public LaunchPadExtension(object testAssemblyReference, ILoggerFactory loggerFactory) { _testAssemblyReference = testAssemblyReference.GetType().Assembly; _loggerFactory = loggerFactory; } + /// + /// Create the extension, with the given type for use as an assembly reference. + /// + /// + /// public LaunchPadExtension(Type testAssemblyReference, ILoggerFactory loggerFactory) { _testAssemblyReference = testAssemblyReference.Assembly; _loggerFactory = loggerFactory; } - public void Dispose() + /// + public virtual void Dispose() { } - public ValueTask DisposeAsync() + /// + public virtual ValueTask DisposeAsync() { return ValueTask.CompletedTask; } - public Task Start(IAlbaHost host) + /// + /// Virtual method that can be overridden to do something before the host is started + /// + /// + /// + public virtual Task Start(IAlbaHost host) { return Task.CompletedTask; } - public IHostBuilder Configure(IHostBuilder builder) + /// + /// Virtual method that can be overridden to do something before the host is configured + /// + /// + /// + public virtual IHostBuilder Configure(IHostBuilder builder) { builder.ConfigureRocketSurgery(z => z.ForTesting(_testAssemblyReference, _loggerFactory)); - builder.ConfigureLogging((context, loggingBuilder) => loggingBuilder.Services.AddSingleton(_loggerFactory)); + builder.ConfigureLogging((_, loggingBuilder) => loggingBuilder.Services.AddSingleton(_loggerFactory)); builder.ConfigureServices(s => s.AddSingleton(z => (TestServer)z.GetRequiredService())); builder.ConfigureServices(s => s.AddHttpLogging(options => options.LoggingFields = HttpLoggingFields.All)); return builder; } } +#pragma warning enable CA1816 +#pragma warning enable CA1063 diff --git a/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs b/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs index 329b918c9..8a984caed 100644 --- a/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs +++ b/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs @@ -27,26 +27,42 @@ protected LaunchPadWebAppFixture(IResettableAlbaExtension? resettableAlbaExtensi _extensions = new IAlbaExtension[] { new LaunchPadExtension(this, _loggerFactory), + // ReSharper disable once NullableWarningSuppressionIsUsed _sqlExtension! } + // ReSharper disable once NullableWarningSuppressionIsUsed .Where(z => z != null!) .Concat(extensions) .ToArray(); } + // ReSharper disable once NullableWarningSuppressionIsUsed + /// + /// The underlying alba host + /// public IAlbaHost AlbaHost => _host!; + /// + /// Set the loggerfactory when initializing the test + /// + /// public void SetLoggerFactory(ILoggerFactory loggerFactory) { _loggerFactory.SetLoggerFactory(loggerFactory); } + /// + /// Method to reset the database if provided + /// public void Reset() { if (_sqlExtension is null || _host is null) return; _sqlExtension.Reset(AlbaHost.Services); } + /// + /// Method to reset the database if provided + /// public async Task ResetAsync() { if (_sqlExtension is null || _host is null) return; @@ -54,11 +70,17 @@ public async Task ResetAsync() await _sqlExtension.ResetAsync(AlbaHost.Services); } + /// + /// Method used to start the alba host + /// public async Task InitializeAsync() { _host = await Alba.AlbaHost.For(_extensions); } + /// + /// Method used to dispose the alba host + /// public async Task DisposeAsync() { await AlbaHost.DisposeAsync(); @@ -70,11 +92,17 @@ public async Task DisposeAsync() } } +#pragma warning disable CA1816 async ValueTask IAsyncDisposable.DisposeAsync() +#pragma warning restore CA1816 { await DisposeAsync().ConfigureAwait(false); } + /// + /// The dispose method + /// + /// protected virtual void Dispose(bool disposing) { if (!disposing) return; @@ -108,6 +136,9 @@ public ILogger CreateLogger(string categoryName) } } + /// + /// The dispose method + /// public void Dispose() { Dispose(true); diff --git a/src/AspNetCore/Composition/IRestfulApiMethodMatcher.cs b/src/AspNetCore/Composition/IRestfulApiMethodMatcher.cs index 383ede25b..0f752e897 100644 --- a/src/AspNetCore/Composition/IRestfulApiMethodMatcher.cs +++ b/src/AspNetCore/Composition/IRestfulApiMethodMatcher.cs @@ -9,5 +9,7 @@ internal interface IRestfulApiMethodMatcher ApiConventionNameMatchBehavior NameMatch { get; } string[] Names { get; } IDictionary Parameters { get; } + + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] bool IsMatch(ActionModel actionModel); } diff --git a/src/AspNetCore/Composition/IRestfulApiParameterMatcher.cs b/src/AspNetCore/Composition/IRestfulApiParameterMatcher.cs index 5c839f17f..bdd2de80d 100644 --- a/src/AspNetCore/Composition/IRestfulApiParameterMatcher.cs +++ b/src/AspNetCore/Composition/IRestfulApiParameterMatcher.cs @@ -10,5 +10,7 @@ internal interface IRestfulApiParameterMatcher string[] Names { get; } ApiConventionTypeMatchBehavior TypeMatch { get; } Type? Type { get; } + + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] bool IsMatch(ActionModel actionModel); } diff --git a/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs b/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs index 1ba62a395..e98126475 100644 --- a/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs +++ b/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs @@ -31,6 +31,7 @@ internal class RestfulApiActionModelConvention : IActionModelConvention, ISchema return httpMethods[0]; } + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] private static void ExtractParameterDetails(ActionModel action) { var requestParameter = action.Parameters.FirstOrDefault( @@ -98,7 +99,10 @@ private static void ExtractParameterDetails(ActionModel action) private readonly ILookup _matchers; private readonly RestfulApiOptions _options; - + /// + /// An action model convention that allows and to be used as parameters to controller actions. + /// + /// public RestfulApiActionModelConvention(IOptions options) { _matchers = options.Value.GetMatchers(); @@ -159,6 +163,8 @@ ActionModel actionModel } } + // TODO: Make a source generator for this to work without generics + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] public void Apply(ActionModel action) { if (!typeof(RestfulApiController).IsAssignableFrom(action.Controller.ControllerType)) diff --git a/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs b/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs index d81fc6352..de1c4c71b 100644 --- a/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs +++ b/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs @@ -3,17 +3,12 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Composition; -internal class RestfulApiApplicationModelProvider : IApplicationModelProvider +internal class RestfulApiApplicationModelProvider(IOptions options) : IApplicationModelProvider { - public RestfulApiApplicationModelProvider(IOptions options) + public List ActionModelConventions { get; } = new() { - ActionModelConventions = new List - { - new RestfulApiActionModelConvention(options) - }; - } - - public List ActionModelConventions { get; } + new RestfulApiActionModelConvention(options) + }; public void OnProvidersExecuted(ApplicationModelProviderContext context) { diff --git a/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs b/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs index c882cf2e7..7a44f2fb3 100644 --- a/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs +++ b/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs @@ -232,6 +232,7 @@ internal bool IsValid() return _names.Length > 0; } + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] internal bool IsMatch(ActionModel actionModel) { var nameMatch = _nameMatchBehavior switch @@ -264,6 +265,7 @@ internal bool IsMatch(ActionModel actionModel) string[] IRestfulApiMethodMatcher.Names => _names; IDictionary IRestfulApiMethodMatcher.Parameters => _parameters; + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] bool IRestfulApiMethodMatcher.IsMatch(ActionModel actionModel) { return IsMatch(actionModel); diff --git a/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs b/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs index 13b17ca6b..4eb2e602b 100644 --- a/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs +++ b/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs @@ -6,29 +6,22 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Composition; -internal class RestfulApiParameterMatcher : IRestfulApiParameterMatcher +internal class RestfulApiParameterMatcher( + Index parameterIndex, + ApiConventionNameMatchBehavior nameMatch, + string[] names, + ApiConventionTypeMatchBehavior typeMatch, + Type? type +) + : IRestfulApiParameterMatcher { - public RestfulApiParameterMatcher( - Index parameterIndex, - ApiConventionNameMatchBehavior nameMatch, - string[] names, - ApiConventionTypeMatchBehavior typeMatch, - Type? type - ) - { - ParameterIndex = parameterIndex; - NameMatch = nameMatch; - Names = names; - TypeMatch = typeMatch; - Type = type; - } - - public Index ParameterIndex { get; } - public ApiConventionNameMatchBehavior NameMatch { get; } - public string[] Names { get; } - public ApiConventionTypeMatchBehavior TypeMatch { get; } - public Type? Type { get; } + public Index ParameterIndex { get; } = parameterIndex; + public ApiConventionNameMatchBehavior NameMatch { get; } = nameMatch; + public string[] Names { get; } = names; + public ApiConventionTypeMatchBehavior TypeMatch { get; } = typeMatch; + public Type? Type { get; } = type; + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] public bool IsMatch(ActionModel actionModel) { var parameters = actionModel.ActionMethod.GetParameters(); @@ -54,6 +47,7 @@ public bool IsMatch(ActionModel actionModel) } } + // ReSharper disable NullableWarningSuppressionIsUsed return NameMatch switch { ApiConventionNameMatchBehavior.Exact => Names.Any(name => parameter.Name!.Equals(name, StringComparison.OrdinalIgnoreCase)), @@ -61,6 +55,7 @@ public bool IsMatch(ActionModel actionModel) ApiConventionNameMatchBehavior.Suffix => Names.Any(name => parameter.Name!.EndsWith(name, StringComparison.OrdinalIgnoreCase)), _ => true }; + // ReSharper enable NullableWarningSuppressionIsUsed } return false; diff --git a/src/AspNetCore/Conventions/AspNetCoreConvention.cs b/src/AspNetCore/Conventions/AspNetCoreConvention.cs index 4198f0153..abf828815 100644 --- a/src/AspNetCore/Conventions/AspNetCoreConvention.cs +++ b/src/AspNetCore/Conventions/AspNetCoreConvention.cs @@ -110,6 +110,7 @@ public void Register(IConventionContext context, IConfiguration configuration, I .AddMvcCore() .AddApiExplorer(); PopulateDefaultParts( + // ReSharper disable once NullableWarningSuppressionIsUsed GetServiceFromCollection(services)!, context.AssemblyCandidateFinder .GetCandidateAssemblies("Rocket.Surgery.LaunchPad.AspNetCore") diff --git a/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs b/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs index 7e5139214..d8b642a7c 100644 --- a/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs +++ b/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs @@ -1,13 +1,8 @@ -using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Composition; using Rocket.Surgery.LaunchPad.Telemetry; namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions; @@ -23,11 +18,13 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions; [AfterConvention(typeof(AspNetCoreConvention))] public class AspNetCoreConventionInstrumentationConvention : IOpenTelemetryMetricsConvention, IOpenTelemetryTracingConvention { + /// public void Register(IConventionContext conventionContext, IConfiguration configuration, MeterProviderBuilder builder) { builder.AddAspNetCoreInstrumentation(); } + /// public void Register(IConventionContext conventionContext, IConfiguration configuration, TracerProviderBuilder builder) { builder.AddAspNetCoreInstrumentation(options => options.RecordException = true); diff --git a/src/AspNetCore/Conventions/AspNetCoreValidationBehaviorConvention.cs b/src/AspNetCore/Conventions/AspNetCoreValidationBehaviorConvention.cs index fc1eda0dd..ba798704a 100644 --- a/src/AspNetCore/Conventions/AspNetCoreValidationBehaviorConvention.cs +++ b/src/AspNetCore/Conventions/AspNetCoreValidationBehaviorConvention.cs @@ -1,17 +1,6 @@ -using Microsoft.AspNetCore.Mvc.ApplicationModels; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using OpenTelemetry; -using OpenTelemetry.Metrics; -using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; using Rocket.Surgery.Conventions.Setup; -using Rocket.Surgery.Hosting; -using Rocket.Surgery.LaunchPad.AspNetCore.Composition; -using Rocket.Surgery.LaunchPad.Foundation; -using Rocket.Surgery.LaunchPad.Telemetry; namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions; @@ -26,6 +15,7 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions; [BeforeConvention(typeof(Foundation.Conventions.FluentValidationConvention))] public class AspNetCoreValidationBehaviorConvention : ISetupConvention { + /// public void Register(IConventionContext context) { context.Set("RegisterValidationOptionsAsHealthChecks", true); diff --git a/src/AspNetCore/Conventions/FluentValidationConvention.cs b/src/AspNetCore/Conventions/FluentValidationConvention.cs index 4ae3667e5..be518f5a2 100644 --- a/src/AspNetCore/Conventions/FluentValidationConvention.cs +++ b/src/AspNetCore/Conventions/FluentValidationConvention.cs @@ -2,7 +2,6 @@ using FluentValidation.AspNetCore; using FluentValidation.Validators; using MicroElements.Swashbuckle.FluentValidation; -using MicroElements.Swashbuckle.FluentValidation.AspNetCore; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -94,6 +93,7 @@ static bool getNullableValue(Nullability nullability, Type propertyType) { var validator = context.PropertyValidator as IStringInValidator; context.Schema.Properties[context.PropertyKey].Enum = + // ReSharper disable once NullableWarningSuppressionIsUsed validator!.Values.Select(x => new OpenApiString(x)).Cast().ToList(); } ) diff --git a/src/AspNetCore/Conventions/ProblemDetailsConvention.cs b/src/AspNetCore/Conventions/ProblemDetailsConvention.cs index 2e954706c..c1282a3d3 100644 --- a/src/AspNetCore/Conventions/ProblemDetailsConvention.cs +++ b/src/AspNetCore/Conventions/ProblemDetailsConvention.cs @@ -68,6 +68,7 @@ public void Register(IConventionContext context, IConfiguration configuration, I static (ctx, _) => { var result = ctx.Items[typeof(ValidationResult)] as ValidationResult; + // ReSharper disable once NullableWarningSuppressionIsUsed return new FluentValidationProblemDetails(result!.Errors) { Status = StatusCodes.Status422UnprocessableEntity diff --git a/src/AspNetCore/Conventions/SwashbuckleConvention.cs b/src/AspNetCore/Conventions/SwashbuckleConvention.cs index 0cf6ce810..c83656934 100644 --- a/src/AspNetCore/Conventions/SwashbuckleConvention.cs +++ b/src/AspNetCore/Conventions/SwashbuckleConvention.cs @@ -98,6 +98,7 @@ public void Register(IConventionContext context, IConfiguration configuration, I string nestedTypeName(Type type) { + // ReSharper disable once NullableWarningSuppressionIsUsed return type.IsNested ? schemaIdSelector(type.DeclaringType!) + type.Name : type.Name; } diff --git a/src/AspNetCore/Filters/SerilogLoggingActionFilter.cs b/src/AspNetCore/Filters/SerilogLoggingActionFilter.cs index e635849ee..938e16dd3 100644 --- a/src/AspNetCore/Filters/SerilogLoggingActionFilter.cs +++ b/src/AspNetCore/Filters/SerilogLoggingActionFilter.cs @@ -3,21 +3,14 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Filters; -internal class SerilogLoggingActionFilter : IActionFilter +internal class SerilogLoggingActionFilter(IDiagnosticContext diagnosticContext) : IActionFilter { - private readonly IDiagnosticContext _diagnosticContext; - - public SerilogLoggingActionFilter(IDiagnosticContext diagnosticContext) - { - _diagnosticContext = diagnosticContext; - } - public void OnActionExecuting(ActionExecutingContext context) { - _diagnosticContext.Set("RouteData", context.ActionDescriptor.RouteValues); - _diagnosticContext.Set("ActionName", context.ActionDescriptor.DisplayName); - _diagnosticContext.Set("ActionId", context.ActionDescriptor.Id); - _diagnosticContext.Set("ValidationState", context.ModelState.IsValid); + diagnosticContext.Set("RouteData", context.ActionDescriptor.RouteValues); + diagnosticContext.Set("ActionName", context.ActionDescriptor.DisplayName); + diagnosticContext.Set("ActionId", context.ActionDescriptor.Id); + diagnosticContext.Set("ValidationState", context.ModelState.IsValid); } // Required by the interface diff --git a/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs b/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs index 7442caeee..9ae38e860 100644 --- a/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs +++ b/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs @@ -3,21 +3,14 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Filters; -internal class SerilogLoggingPageFilter : IPageFilter +internal class SerilogLoggingPageFilter(IDiagnosticContext diagnosticContext) : IPageFilter { - private readonly IDiagnosticContext _diagnosticContext; - - public SerilogLoggingPageFilter(IDiagnosticContext diagnosticContext) - { - _diagnosticContext = diagnosticContext; - } - public void OnPageHandlerSelected(PageHandlerSelectedContext context) { var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name; if (name != null) { - _diagnosticContext.Set("RazorPageHandler", name); + diagnosticContext.Set("RazorPageHandler", name); } } diff --git a/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs b/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs index 60e606712..159c4100f 100644 --- a/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs +++ b/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs @@ -6,11 +6,13 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.OpenApi; internal static class StronglyTypedIdHelpers { + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] public static bool IsStronglyTypedId(Type? type) { return GetStronglyTypedIdType(type) is { }; } + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] public static Type? GetStronglyTypedIdType(Type? type) { if (type?.GetMember("New", BindingFlags.Static | BindingFlags.Public).FirstOrDefault() is MethodInfo @@ -26,6 +28,8 @@ public static bool IsStronglyTypedId(Type? type) internal class StronglyTypedIdSchemaFilter : ISchemaFilter { + // TODO: Make a source generator for this to work without generics + [RequiresUnreferencedCode("DynamicBehavior is incompatible with trimming.")] public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if (StronglyTypedIdHelpers.GetStronglyTypedIdType(context.Type) is not { } type) return; diff --git a/src/AspNetCore/OpenApi/SwashbuckleAddAllDocumentEndpoints.cs b/src/AspNetCore/OpenApi/SwashbuckleAddAllDocumentEndpoints.cs index 225ac171d..44eaf3e50 100644 --- a/src/AspNetCore/OpenApi/SwashbuckleAddAllDocumentEndpoints.cs +++ b/src/AspNetCore/OpenApi/SwashbuckleAddAllDocumentEndpoints.cs @@ -5,20 +5,13 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.OpenApi; -internal class SwashbuckleAddAllDocumentEndpoints : IConfigureOptions +internal class SwashbuckleAddAllDocumentEndpoints(IOptions options) : IConfigureOptions { - private readonly IOptions _options; - - public SwashbuckleAddAllDocumentEndpoints(IOptions options) - { - _options = options; - } - - public void Configure(SwaggerUIOptions options) + public void Configure(SwaggerUIOptions options1) { - foreach (var item in _options.Value.SwaggerGeneratorOptions.SwaggerDocs) + foreach (var item in options.Value.SwaggerGeneratorOptions.SwaggerDocs) { - options.SwaggerEndpoint($"/swagger/{item.Key}/swagger.json", item.Value.Title); + options1.SwaggerEndpoint($"/swagger/{item.Key}/swagger.json", item.Value.Title); } } } diff --git a/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj b/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj index 4fac5b720..e60877ee6 100644 --- a/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj +++ b/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj @@ -4,6 +4,7 @@ $(PackageTags) false + false diff --git a/src/AspNetCore/RocketSurgeryMvcCoreExtensions.cs b/src/AspNetCore/RocketSurgeryMvcCoreExtensions.cs index 3c5685087..68ba5cf53 100644 --- a/src/AspNetCore/RocketSurgeryMvcCoreExtensions.cs +++ b/src/AspNetCore/RocketSurgeryMvcCoreExtensions.cs @@ -50,7 +50,7 @@ public static IApplicationBuilder UseLaunchPadRequestLogging(this IApplicationBu /// AddMvc or AddMvcCore can cause breaking changes if called multiple times over the application lifespan. /// This allows us to ensure that we don't upset that state, but get back the expected mvc builder. /// - private class ImmutableMvcBuilder : IMvcBuilder, IMvcCoreBuilder + private class ImmutableMvcBuilder(IServiceCollection services, bool core) : IMvcBuilder, IMvcCoreBuilder { private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services, bool core) { @@ -63,15 +63,9 @@ private static ApplicationPartManager GetApplicationPartManager(IServiceCollecti return (T?)services.LastOrDefault(d => d.ServiceType == typeof(T))?.ImplementationInstance; } - private readonly Lazy _partsManager; - - public ImmutableMvcBuilder(IServiceCollection services, bool core) - { - Services = services; - _partsManager = new Lazy(() => GetApplicationPartManager(services, core)); - } + private readonly Lazy _partsManager = new(() => GetApplicationPartManager(services, core)); public ApplicationPartManager PartManager => _partsManager.Value; - public IServiceCollection Services { get; } + public IServiceCollection Services { get; } = services; } } diff --git a/src/AspNetCore/Validation/ValidationExceptionFilter.cs b/src/AspNetCore/Validation/ValidationExceptionFilter.cs index 533f91dcb..5998e0fe6 100644 --- a/src/AspNetCore/Validation/ValidationExceptionFilter.cs +++ b/src/AspNetCore/Validation/ValidationExceptionFilter.cs @@ -1,5 +1,4 @@ using FluentValidation; -using FluentValidation.Results; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; diff --git a/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs b/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs index 3406fe2e2..b069e8cd1 100644 --- a/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs +++ b/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs @@ -51,12 +51,14 @@ protected override T ReadJsonImpl(JsonReader reader, JsonSerializer serializer) ); } - var text = reader.Value!.ToString()!; + var text = reader.Value?.ToString(); + // ReSharper disable once NullableWarningSuppressionIsUsed ParseResult result = null!; foreach (var patter in _patterns) { - result = patter.Parse(text); + // ReSharper disable once NullableWarningSuppressionIsUsed + result = patter.Parse(text!); if (result.Success) break; } diff --git a/src/Foundation.NewtonsoftJson/NewtonsoftJsonDestructuringPolicy.cs b/src/Foundation.NewtonsoftJson/NewtonsoftJsonDestructuringPolicy.cs index fb42ee80e..ba2d5d96a 100644 --- a/src/Foundation.NewtonsoftJson/NewtonsoftJsonDestructuringPolicy.cs +++ b/src/Foundation.NewtonsoftJson/NewtonsoftJsonDestructuringPolicy.cs @@ -8,7 +8,8 @@ internal class NewtonsoftJsonDestructuringPolicy : IDestructuringPolicy { private static LogEventPropertyValue Destructure(JValue jv, ILogEventPropertyValueFactory propertyValueFactory) { - return propertyValueFactory.CreatePropertyValue(jv.Value, true); + // ReSharper disable once NullableWarningSuppressionIsUsed + return propertyValueFactory.CreatePropertyValue(jv.Value!, true); } private static LogEventPropertyValue Destructure(JArray ja, ILogEventPropertyValueFactory propertyValueFactory) @@ -55,7 +56,7 @@ private static LogEventPropertyValue DestructureToDictionaryValue(JObject jo, IL return new DictionaryValue(elements); } - public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue? result) + public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result) { switch (value) { diff --git a/src/Foundation/Conventions/InstrumentationConvention.cs b/src/Foundation/Conventions/InstrumentationConvention.cs index d87739689..1145af12d 100644 --- a/src/Foundation/Conventions/InstrumentationConvention.cs +++ b/src/Foundation/Conventions/InstrumentationConvention.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Configuration; -using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; diff --git a/src/Foundation/Conventions/MediatRConvention.cs b/src/Foundation/Conventions/MediatRConvention.cs index 497ae03d4..0427952e9 100644 --- a/src/Foundation/Conventions/MediatRConvention.cs +++ b/src/Foundation/Conventions/MediatRConvention.cs @@ -1,5 +1,4 @@ -using MediatR; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; diff --git a/src/Foundation/NodaTimeDestructuringPolicy.cs b/src/Foundation/NodaTimeDestructuringPolicy.cs index d76c29ee4..e7cd5c7e9 100644 --- a/src/Foundation/NodaTimeDestructuringPolicy.cs +++ b/src/Foundation/NodaTimeDestructuringPolicy.cs @@ -5,16 +5,11 @@ namespace Rocket.Surgery.LaunchPad.Foundation; -internal class NodaTimeDestructuringPolicy : IDestructuringPolicy +internal class NodaTimeDestructuringPolicy(IDateTimeZoneProvider provider) : IDestructuringPolicy { - private readonly ZonedDateTimePattern _zonedDateTimePattern; + private readonly ZonedDateTimePattern _zonedDateTimePattern = ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo z", provider); - public NodaTimeDestructuringPolicy(IDateTimeZoneProvider provider) - { - _zonedDateTimePattern = ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo z", provider); - } - - public bool TryDestructure(object value, ILogEventPropertyValueFactory _, out LogEventPropertyValue? result) + public bool TryDestructure(object value, ILogEventPropertyValueFactory _, [NotNullWhen(true)] out LogEventPropertyValue? result) { if (value is Instant instant1) { diff --git a/src/Foundation/SystemTextJsonCompositeNodaPatternConverter.cs b/src/Foundation/SystemTextJsonCompositeNodaPatternConverter.cs index 5faa2539b..1c6a0f421 100644 --- a/src/Foundation/SystemTextJsonCompositeNodaPatternConverter.cs +++ b/src/Foundation/SystemTextJsonCompositeNodaPatternConverter.cs @@ -37,8 +37,10 @@ public SystemTextJsonCompositeNodaPatternConverter(Action? validator, params /// protected override T ReadJsonImpl(ref Utf8JsonReader reader, JsonSerializerOptions options) { + // ReSharper disable once NullableWarningSuppressionIsUsed var text = reader.GetString()!; + // ReSharper disable once NullableWarningSuppressionIsUsed ParseResult result = null!; foreach (var patter in _patterns) { diff --git a/src/Foundation/SystemTextJsonDestructuringPolicy.cs b/src/Foundation/SystemTextJsonDestructuringPolicy.cs index cc581eda7..a273e3e11 100644 --- a/src/Foundation/SystemTextJsonDestructuringPolicy.cs +++ b/src/Foundation/SystemTextJsonDestructuringPolicy.cs @@ -22,7 +22,7 @@ private static LogEventPropertyValue Destructure(in JsonElement jel) }; } - public bool TryDestructure(object value, ILogEventPropertyValueFactory _, out LogEventPropertyValue? result) + public bool TryDestructure(object value, ILogEventPropertyValueFactory _, [NotNullWhen(true)] out LogEventPropertyValue? result) { switch (value) { diff --git a/src/Foundation/Validation/CompositeValidator.cs b/src/Foundation/Validation/CompositeValidator.cs index 2b30f5d25..084980b57 100644 --- a/src/Foundation/Validation/CompositeValidator.cs +++ b/src/Foundation/Validation/CompositeValidator.cs @@ -7,18 +7,12 @@ namespace Rocket.Surgery.LaunchPad.Foundation.Validation; internal class CompositeValidator { protected static readonly PropertyInfo RuleSetsExecutedProperty = typeof(ValidationResult) + // ReSharper disable once NullableWarningSuppressionIsUsed .GetProperty(nameof(ValidationResult.RuleSetsExecuted), BindingFlags.Instance | BindingFlags.Public)!; } -internal class CompositeValidator : CompositeValidator, IValidator +internal class CompositeValidator(IEnumerable validators) : CompositeValidator, IValidator { - private readonly IEnumerable _validators; - - public CompositeValidator(IEnumerable validators) - { - _validators = validators; - } - public CascadeMode CascadeMode { get; set; } = CascadeMode.Continue; public ValidationResult Validate(T instance) @@ -33,7 +27,7 @@ public ValidationResult Validate(T instance) public ValidationResult Validate(IValidationContext context) { - return _validators + return validators .Select(z => z.Validate(context)) .Aggregate( new ValidationResult(), @@ -49,7 +43,7 @@ public ValidationResult Validate(IValidationContext context) public async Task ValidateAsync(IValidationContext context, CancellationToken cancellation = default) { var tasks = new List>(); - foreach (var validator in _validators) + foreach (var validator in validators) { tasks.Add(validator.ValidateAsync(context, cancellation)); } @@ -68,11 +62,11 @@ public async Task ValidateAsync(IValidationContext context, Ca public IValidatorDescriptor CreateDescriptor() { - return new CompositeValidatorDescriptor(_validators); + return new CompositeValidatorDescriptor(validators); } public bool CanValidateInstancesOfType(Type type) { - return _validators.Any(z => z.CanValidateInstancesOfType(type)); + return validators.Any(z => z.CanValidateInstancesOfType(type)); } } diff --git a/src/Foundation/Validation/CompositeValidatorDescriptor.cs b/src/Foundation/Validation/CompositeValidatorDescriptor.cs index fed741d28..9bc652bd5 100644 --- a/src/Foundation/Validation/CompositeValidatorDescriptor.cs +++ b/src/Foundation/Validation/CompositeValidatorDescriptor.cs @@ -4,25 +4,18 @@ namespace Rocket.Surgery.LaunchPad.Foundation.Validation; -internal class CompositeValidatorDescriptor : IValidatorDescriptor +internal class CompositeValidatorDescriptor(IEnumerable validators) : IValidatorDescriptor { - private readonly IEnumerable _validators; - - public CompositeValidatorDescriptor(IEnumerable validators) - { - _validators = validators; - } - public string GetName(string property) { - return _validators + return validators .Select(z => z.CreateDescriptor().GetName(property)) - .FirstOrDefault()!; + .First(); } public ILookup GetMembersWithValidators() { - return _validators + return validators .SelectMany(z => z.CreateDescriptor().GetMembersWithValidators()) .SelectMany(outer => outer.Select(item => ( outer.Key, item ))) .ToLookup(z => z.Key, z => z.item); @@ -30,15 +23,15 @@ public string GetName(string property) public IEnumerable<(IPropertyValidator Validator, IRuleComponent Options)> GetValidatorsForMember(string name) { - return _validators + return validators .SelectMany(z => z.CreateDescriptor().GetValidatorsForMember(name)); } public IEnumerable GetRulesForMember(string name) { - return _validators + return validators .SelectMany(z => z.CreateDescriptor().GetRulesForMember(name)); } - public IEnumerable Rules => _validators.SelectMany(z => z.CreateDescriptor().Rules); + public IEnumerable Rules => validators.SelectMany(z => z.CreateDescriptor().Rules); } diff --git a/src/Foundation/Validation/CustomHealthCheckService.cs b/src/Foundation/Validation/CustomHealthCheckService.cs index d834d21d5..36a3e73c1 100644 --- a/src/Foundation/Validation/CustomHealthCheckService.cs +++ b/src/Foundation/Validation/CustomHealthCheckService.cs @@ -2,24 +2,16 @@ namespace Rocket.Surgery.LaunchPad.Foundation.Validation; -internal class CustomHealthCheckService : HealthCheckService +internal class CustomHealthCheckService(HealthCheckService wrappedService, ValidationHealthCheckResults healthCheckResults) + : HealthCheckService { - private readonly HealthCheckService _wrappedService; - private readonly ValidationHealthCheckResults _healthCheckResults; - - public CustomHealthCheckService(HealthCheckService wrappedService, ValidationHealthCheckResults healthCheckResults) - { - _wrappedService = wrappedService; - _healthCheckResults = healthCheckResults; - } - public override async Task CheckHealthAsync( Func? predicate, CancellationToken cancellationToken = new CancellationToken() ) { - var results = await _wrappedService.CheckHealthAsync(predicate, cancellationToken); + var results = await wrappedService.CheckHealthAsync(predicate, cancellationToken); return new HealthReport( - results.Entries.Concat(_healthCheckResults.Results).ToDictionary(z => z.Key, z => z.Value), + results.Entries.Concat(healthCheckResults.Results).ToDictionary(z => z.Key, z => z.Value), results.TotalDuration ); } diff --git a/src/Foundation/Validation/FluentValidationOptions.cs b/src/Foundation/Validation/FluentValidationOptions.cs index 6c4b8c7c2..9bee2a4dc 100644 --- a/src/Foundation/Validation/FluentValidationOptions.cs +++ b/src/Foundation/Validation/FluentValidationOptions.cs @@ -8,27 +8,19 @@ namespace Rocket.Surgery.LaunchPad.Foundation.Validation; /// This class enables fluent validators to be used for options validations! /// /// -internal class FluentValidationOptions : IValidateOptions +internal class FluentValidationOptions( + ValidationHealthCheckResults? healthCheckResults = null, + IValidator? validator = null +) + : IValidateOptions where T : class { - private readonly ValidationHealthCheckResults? _healthCheckResults; - private readonly IValidator? _validator; - - public FluentValidationOptions( - ValidationHealthCheckResults? healthCheckResults = null, - IValidator? validator = null - ) - { - _healthCheckResults = healthCheckResults; - _validator = validator; - } - - public virtual ValidateOptionsResult Validate(string name, T options) + public virtual ValidateOptionsResult Validate(string? name, T options) { - if (_validator == null) return ValidateOptionsResult.Skip; + if (validator == null) return ValidateOptionsResult.Skip; - var result = _validator.Validate(options); - _healthCheckResults?.AddResult(typeof(T).GetNestedTypeName(), name, result); + var result = validator.Validate(options); + healthCheckResults?.AddResult(typeof(T).GetNestedTypeName(), name ?? Options.DefaultName, result); if (result.IsValid) return ValidateOptionsResult.Success; return ValidateOptionsResult.Fail( diff --git a/src/Foundation/Validation/HealthCheckFluentValidationOptions.cs b/src/Foundation/Validation/HealthCheckFluentValidationOptions.cs index 0c863b879..59a6ee0cf 100644 --- a/src/Foundation/Validation/HealthCheckFluentValidationOptions.cs +++ b/src/Foundation/Validation/HealthCheckFluentValidationOptions.cs @@ -8,27 +8,23 @@ namespace Rocket.Surgery.LaunchPad.Foundation.Validation; /// This class enables fluent validators to be used for options validations! /// /// -internal class HealthCheckFluentValidationOptions : FluentValidationOptions +internal class HealthCheckFluentValidationOptions( + ValidationHealthCheckResults healthCheckResults, + IValidator? validator = null +) +#pragma warning disable CS9107 // Parameter is captured into the state of the enclosing type and its value is also passed to the base constructor. The value might be captured by the base class as well. + : FluentValidationOptions(null, validator) +#pragma warning restore CS9107 // Parameter is captured into the state of the enclosing type and its value is also passed to the base constructor. The value might be captured by the base class as well. where T : class { - private readonly ValidationHealthCheckResults _healthCheckResults; - private readonly IValidator? _validator; + /* null because we're adding results during the validate call here */ - public HealthCheckFluentValidationOptions( - ValidationHealthCheckResults healthCheckResults, - IValidator? validator = null - ) : base(null /* null because we're adding results during the validate call here */, validator) + public override ValidateOptionsResult Validate(string? name, T options) { - _healthCheckResults = healthCheckResults; - _validator = validator; - } - - public override ValidateOptionsResult Validate(string name, T options) - { - if (_validator == null) return ValidateOptionsResult.Skip; + if (validator == null) return ValidateOptionsResult.Skip; - var result = _validator.Validate(options); - _healthCheckResults.AddResult(typeof(T).GetNestedTypeName(), name, result); - return _healthCheckResults.ApplicationHasStarted ? base.Validate(name, options) : ValidateOptionsResult.Skip; + var result = validator.Validate(options); + healthCheckResults.AddResult(typeof(T).GetNestedTypeName(), name ?? Options.DefaultName, result); + return healthCheckResults.ApplicationHasStarted ? base.Validate(name, options) : ValidateOptionsResult.Skip; } } diff --git a/src/Foundation/Validation/ValidationPipelineBehavior.cs b/src/Foundation/Validation/ValidationPipelineBehavior.cs index 5b87cef7e..f0aa13e52 100644 --- a/src/Foundation/Validation/ValidationPipelineBehavior.cs +++ b/src/Foundation/Validation/ValidationPipelineBehavior.cs @@ -4,22 +4,16 @@ namespace Rocket.Surgery.LaunchPad.Foundation.Validation; -internal class ValidationPipelineBehavior : IPipelineBehavior where T : notnull +internal class ValidationPipelineBehavior(IValidator? validator = null) : IPipelineBehavior + where T : notnull { - private readonly IValidator? _validator; - - public ValidationPipelineBehavior(IValidator? validator = null) - { - _validator = validator; - } - public async Task Handle(T request, RequestHandlerDelegate next, CancellationToken cancellationToken) { - if (_validator is not null) + if (validator is not null) { var context = new ValidationContext(request); - var response = await _validator.ValidateAsync(context, cancellationToken).ConfigureAwait(false); + var response = await validator.ValidateAsync(context, cancellationToken).ConfigureAwait(false); if (!response.IsValid) { throw new ValidationException(response.Errors); @@ -30,22 +24,16 @@ public async Task Handle(T request, RequestHandlerDelegate next, Cancellat } } -internal class ValidationStreamPipelineBehavior : IStreamPipelineBehavior where T : IStreamRequest +internal class ValidationStreamPipelineBehavior(IValidator? validator = null) : IStreamPipelineBehavior + where T : IStreamRequest { - private readonly IValidator? _validator; - - public ValidationStreamPipelineBehavior(IValidator? validator = null) - { - _validator = validator; - } - public async IAsyncEnumerable Handle(T request, StreamHandlerDelegate next, [EnumeratorCancellation] CancellationToken cancellationToken) { - if (_validator is not null) + if (validator is not null) { var context = new ValidationContext(request); - var response = await _validator.ValidateAsync(context, cancellationToken).ConfigureAwait(false); + var response = await validator.ValidateAsync(context, cancellationToken).ConfigureAwait(false); if (!response.IsValid) { throw new ValidationException(response.Errors); diff --git a/src/Functions/Conventions/SerilogFunctionsConvention.cs b/src/Functions/Conventions/SerilogFunctionsConvention.cs index d56787f7d..08115e632 100644 --- a/src/Functions/Conventions/SerilogFunctionsConvention.cs +++ b/src/Functions/Conventions/SerilogFunctionsConvention.cs @@ -60,9 +60,9 @@ public void Register(IConventionContext context, IConfiguration configuration, I } services.AddSingleton( - _ => + serviceProvider => { - var log = _.GetRequiredService(); + var log = serviceProvider.GetRequiredService(); ILogger? registeredLogger = null; if (_options.PreserveStaticLogger) { @@ -79,7 +79,7 @@ public void Register(IConventionContext context, IConfiguration configuration, I if (_options.WriteToProviders) { - foreach (var provider in _.GetServices()) + foreach (var provider in serviceProvider.GetServices()) factory.AddProvider(provider); } @@ -94,14 +94,14 @@ public void Register(IConventionContext context, IConfiguration configuration, I else { services.AddSingleton( - _ => + serviceProvider => { var loggerConfiguration = new LoggerConfiguration(); if (loggerProviders != null) loggerConfiguration.WriteTo.Providers(loggerProviders); - loggerConfiguration.ApplyConventions(context, _); + loggerConfiguration.ApplyConventions(context, serviceProvider); return loggerConfiguration.CreateLogger(); } diff --git a/src/Functions/LaunchPadFunctionStartup.cs b/src/Functions/LaunchPadFunctionStartup.cs index b54191191..9ea91da6d 100644 --- a/src/Functions/LaunchPadFunctionStartup.cs +++ b/src/Functions/LaunchPadFunctionStartup.cs @@ -13,6 +13,7 @@ namespace Rocket.Surgery.LaunchPad.Functions; public abstract class LaunchPadFunctionStartup : FunctionsStartup { internal ConventionContextBuilder _builder; + // ReSharper disable once NullableWarningSuppressionIsUsed internal IConventionContext _context = null!; /// diff --git a/src/Grpc/NotAuthorizedInterceptor.cs b/src/Grpc/NotAuthorizedInterceptor.cs index 1dcbed828..c762c9b1a 100644 --- a/src/Grpc/NotAuthorizedInterceptor.cs +++ b/src/Grpc/NotAuthorizedInterceptor.cs @@ -3,9 +3,4 @@ namespace Rocket.Surgery.LaunchPad.Grpc; -internal class NotAuthorizedInterceptor : ProblemDetailsInterceptor -{ - public NotAuthorizedInterceptor() : base(StatusCode.PermissionDenied) - { - } -} +internal class NotAuthorizedInterceptor() : ProblemDetailsInterceptor(StatusCode.PermissionDenied); diff --git a/src/Grpc/NotFoundInterceptor.cs b/src/Grpc/NotFoundInterceptor.cs index 8dd53afd2..4fe7745d2 100644 --- a/src/Grpc/NotFoundInterceptor.cs +++ b/src/Grpc/NotFoundInterceptor.cs @@ -3,9 +3,4 @@ namespace Rocket.Surgery.LaunchPad.Grpc; -internal class NotFoundInterceptor : ProblemDetailsInterceptor -{ - public NotFoundInterceptor() : base(StatusCode.NotFound) - { - } -} +internal class NotFoundInterceptor() : ProblemDetailsInterceptor(StatusCode.NotFound); diff --git a/src/Grpc/ProblemDetailsInterceptor.cs b/src/Grpc/ProblemDetailsInterceptor.cs index 12c6bd5a1..2d1f68f56 100644 --- a/src/Grpc/ProblemDetailsInterceptor.cs +++ b/src/Grpc/ProblemDetailsInterceptor.cs @@ -13,6 +13,7 @@ namespace Rocket.Surgery.LaunchPad.Grpc; public abstract class ProblemDetailsInterceptor : Interceptor where T : Exception, IProblemDetailsData { + [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "")] private static Metadata CreateMetadata(T exception) { var metadata = new Metadata(); diff --git a/src/Grpc/RequestFailedInterceptor.cs b/src/Grpc/RequestFailedInterceptor.cs index 287fe979e..182a1dc99 100644 --- a/src/Grpc/RequestFailedInterceptor.cs +++ b/src/Grpc/RequestFailedInterceptor.cs @@ -3,9 +3,4 @@ namespace Rocket.Surgery.LaunchPad.Grpc; -internal class RequestFailedInterceptor : ProblemDetailsInterceptor -{ - public RequestFailedInterceptor() : base(StatusCode.FailedPrecondition) - { - } -} +internal class RequestFailedInterceptor() : ProblemDetailsInterceptor(StatusCode.FailedPrecondition); diff --git a/src/Grpc/Validation/ValidationInterceptor.cs b/src/Grpc/Validation/ValidationInterceptor.cs index b8a6022a0..ab6ba3d7d 100644 --- a/src/Grpc/Validation/ValidationInterceptor.cs +++ b/src/Grpc/Validation/ValidationInterceptor.cs @@ -5,7 +5,7 @@ namespace Rocket.Surgery.LaunchPad.Grpc.Validation; -internal class ValidationInterceptor : Interceptor +internal class ValidationInterceptor(IValidatorErrorMessageHandler handler, IServiceProvider serviceProvider) : Interceptor { private static RpcException CreateException(ValidationResult results, string? message) { @@ -16,22 +16,13 @@ private static RpcException CreateException(ValidationResult results, string? me throw new RpcException(new Status(StatusCode.InvalidArgument, message ?? ""), validationMetadata, message ?? ""); } - private readonly IValidatorErrorMessageHandler _handler; - private readonly IServiceProvider _serviceProvider; - - public ValidationInterceptor(IValidatorErrorMessageHandler handler, IServiceProvider serviceProvider) - { - _handler = handler; - _serviceProvider = serviceProvider; - } - public override async Task UnaryServerHandler( TRequest request, ServerCallContext context, UnaryServerMethod continuation ) { - if (_serviceProvider.GetValidator() is { } validator) + if (serviceProvider.GetValidator() is { } validator) { var results = await validator.ValidateAsync(request, context.CancellationToken).ConfigureAwait(false); @@ -40,7 +31,7 @@ UnaryServerMethod continuation return await continuation(request, context); } - var message = await _handler.HandleAsync(results.Errors); + var message = await handler.HandleAsync(results.Errors); throw CreateException(results, message); } @@ -53,7 +44,7 @@ public override AsyncUnaryCall AsyncUnaryCall( AsyncUnaryCallContinuation continuation ) { - if (_serviceProvider.GetValidator() is { } validator) + if (serviceProvider.GetValidator() is { } validator) { var results = validator.Validate(request); @@ -62,7 +53,7 @@ AsyncUnaryCallContinuation continuation return continuation(request, context); } - var message = _handler.Handle(results.Errors); + var message = handler.Handle(results.Errors); throw CreateException(results, message); } @@ -75,7 +66,7 @@ public override TResponse BlockingUnaryCall( BlockingUnaryCallContinuation continuation ) { - if (_serviceProvider.GetValidator() is { } validator) + if (serviceProvider.GetValidator() is { } validator) { var results = validator.Validate(request); @@ -84,7 +75,7 @@ BlockingUnaryCallContinuation continuation return continuation(request, context); } - var message = _handler.Handle(results.Errors); + var message = handler.Handle(results.Errors); throw CreateException(results, message); } diff --git a/src/Grpc/Validation/ValidationTrailers.cs b/src/Grpc/Validation/ValidationTrailers.cs index 7766e47ed..12cb4f3eb 100644 --- a/src/Grpc/Validation/ValidationTrailers.cs +++ b/src/Grpc/Validation/ValidationTrailers.cs @@ -6,16 +6,19 @@ namespace Rocket.Surgery.LaunchPad.Grpc.Validation; [Serializable] public class ValidationTrailers { + // ReSharper disable once NullableWarningSuppressionIsUsed /// /// The property name /// public string PropertyName { get; set; } = null!; + // ReSharper disable once NullableWarningSuppressionIsUsed /// /// The error message /// public string ErrorMessage { get; set; } = null!; + // ReSharper disable once NullableWarningSuppressionIsUsed /// /// The given value /// diff --git a/src/Hosting/Conventions/EnvironmentLoggingConvention.cs b/src/Hosting/Conventions/EnvironmentLoggingConvention.cs index 832bf7203..18f2ed5b5 100644 --- a/src/Hosting/Conventions/EnvironmentLoggingConvention.cs +++ b/src/Hosting/Conventions/EnvironmentLoggingConvention.cs @@ -29,12 +29,8 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - var environment = context.Get()!; + if (context == null) throw new ArgumentNullException(nameof(context)); + if (context.Get() is not { } environment) return; loggerConfiguration.Enrich.WithProperty(nameof(environment.EnvironmentName), environment.EnvironmentName); loggerConfiguration.Enrich.WithProperty(nameof(environment.ApplicationName), environment.ApplicationName); } diff --git a/src/Hosting/Conventions/OpenTelemetryConvention.cs b/src/Hosting/Conventions/OpenTelemetryConvention.cs index bf3f3132e..13e981af1 100644 --- a/src/Hosting/Conventions/OpenTelemetryConvention.cs +++ b/src/Hosting/Conventions/OpenTelemetryConvention.cs @@ -1,13 +1,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using OpenTelemetry; -using OpenTelemetry.Resources; -using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; using Rocket.Surgery.LaunchPad.Hosting.Telemetry; using Rocket.Surgery.LaunchPad.Serilog; -using Rocket.Surgery.LaunchPad.Telemetry; namespace Rocket.Surgery.LaunchPad.Hosting.Conventions; diff --git a/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs b/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs index bf414ecad..9acc650e6 100644 --- a/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs +++ b/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Microsoft.Extensions.Configuration; using Rocket.Surgery.Conventions; using Rocket.Surgery.LaunchPad.Serilog; @@ -46,7 +47,8 @@ LoggerConfiguration loggerConfiguration c => c.Console( LogEventLevel.Verbose, _options.ConsoleMessageTemplate, - theme: AnsiConsoleTheme.Literate + theme: AnsiConsoleTheme.Literate, + formatProvider: CultureInfo.InvariantCulture ) ); } diff --git a/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs b/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs index f9171b9a3..68c93dbec 100644 --- a/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs +++ b/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Microsoft.Extensions.Configuration; using Rocket.Surgery.Conventions; using Rocket.Surgery.LaunchPad.Serilog; @@ -44,7 +45,8 @@ LoggerConfiguration loggerConfiguration loggerConfiguration.WriteTo.Async( c => c.Debug( LogEventLevel.Verbose, - _options.DebugMessageTemplate + _options.DebugMessageTemplate, + formatProvider: CultureInfo.InvariantCulture ) ); } diff --git a/src/Hosting/Conventions/SerilogHostingConvention.cs b/src/Hosting/Conventions/SerilogHostingConvention.cs index 12038b04e..a4befa3a5 100644 --- a/src/Hosting/Conventions/SerilogHostingConvention.cs +++ b/src/Hosting/Conventions/SerilogHostingConvention.cs @@ -69,6 +69,7 @@ public void Register(IConventionContext context, IHostBuilder builder) if (context.Get() != null) { + // ReSharper disable once NullableWarningSuppressionIsUsed builder.ConfigureServices((_, services) => services.AddSingleton(context.Get()!)); } } diff --git a/src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs b/src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs index e3d3836f8..1444eb7f1 100644 --- a/src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs +++ b/src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs @@ -1,7 +1,6 @@ // ReSharper disable once CheckNamespace using Rocket.Surgery.LaunchPad.Hosting.Telemetry; -using Rocket.Surgery.LaunchPad.Telemetry; // ReSharper disable once CheckNamespace namespace Rocket.Surgery.Conventions; diff --git a/src/HotChocolate/Configuration/HotChocolateContextDataConfigureOptions.cs b/src/HotChocolate/Configuration/HotChocolateContextDataConfigureOptions.cs index 8b249ebde..f3faa153d 100644 --- a/src/HotChocolate/Configuration/HotChocolateContextDataConfigureOptions.cs +++ b/src/HotChocolate/Configuration/HotChocolateContextDataConfigureOptions.cs @@ -10,13 +10,13 @@ public void Configure(RequestExecutorSetup options) Configure(Options.DefaultName, options); } - public void Configure(string name, RequestExecutorSetup options) + public void Configure(string? name, RequestExecutorSetup options) { options.OnConfigureSchemaBuilderHooks.Add( - new OnConfigureSchemaBuilderAction((context, services) => context.SchemaBuilder.SetContextData("SchemaName", name)) + new OnConfigureSchemaBuilderAction((context, _) => context.SchemaBuilder.SetContextData("SchemaName", name)) ); options.OnConfigureSchemaBuilderHooks.Add( - new OnConfigureSchemaBuilderAction((context, services) => context.SchemaBuilder.TryAddTypeInterceptor(typeof(NestedTypeNameTypeInterceptor))) + new OnConfigureSchemaBuilderAction((context, _) => context.SchemaBuilder.TryAddTypeInterceptor(typeof(NestedTypeNameTypeInterceptor))) ); } } diff --git a/src/HotChocolate/Conventions/GraphqlConvention.cs b/src/HotChocolate/Conventions/GraphqlConvention.cs index 7364fbabc..32ba61f6f 100644 --- a/src/HotChocolate/Conventions/GraphqlConvention.cs +++ b/src/HotChocolate/Conventions/GraphqlConvention.cs @@ -1,5 +1,4 @@ using FairyBread; -using FluentValidation; using MediatR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; diff --git a/src/HotChocolate/Conventions/InstrumentationConvention.cs b/src/HotChocolate/Conventions/InstrumentationConvention.cs index 2aa7be1f4..0755e9fa2 100644 --- a/src/HotChocolate/Conventions/InstrumentationConvention.cs +++ b/src/HotChocolate/Conventions/InstrumentationConvention.cs @@ -1,12 +1,10 @@ using Microsoft.Extensions.Configuration; -using OpenTelemetry; -using OpenTelemetry.Metrics; using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; using Rocket.Surgery.LaunchPad.Telemetry; -namespace Rocket.Surgery.LaunchPad.Foundation.Conventions; +namespace Rocket.Surgery.LaunchPad.HotChocolate.Conventions; /// /// InstrumentationConvention. diff --git a/src/HotChocolate/Extensions/ISchemaBuilderExtensions.cs b/src/HotChocolate/Extensions/ISchemaBuilderExtensions.cs index 305cbafca..2193c3e0c 100644 --- a/src/HotChocolate/Extensions/ISchemaBuilderExtensions.cs +++ b/src/HotChocolate/Extensions/ISchemaBuilderExtensions.cs @@ -1,5 +1,4 @@ using HotChocolate; -using HotChocolate.Data; using HotChocolate.Data.Filters; using HotChocolate.Types.NodaTime; using NodaTime; diff --git a/src/HotChocolate/GraphqlExtensions.cs b/src/HotChocolate/GraphqlExtensions.cs index 654494611..812240ea8 100644 --- a/src/HotChocolate/GraphqlExtensions.cs +++ b/src/HotChocolate/GraphqlExtensions.cs @@ -52,7 +52,9 @@ public static IErrorBuilder WithProblemDetails(this IErrorBuilder error, IProble /// /// /// - public static IRequestExecutorBuilder ConfigureStronglyTypedId(this IRequestExecutorBuilder builder) + public static IRequestExecutorBuilder ConfigureStronglyTypedId< + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] TStrongType, + TSchemaType>(this IRequestExecutorBuilder builder) where TSchemaType : INamedType { AddTypeConversion(builder); @@ -62,6 +64,7 @@ public static IRequestExecutorBuilder ConfigureStronglyTypedId(IRequestExecutorBuilder builder) + [UnconditionalSuppressMessage( + "Trimming", + "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", + Justification = "only working with public properties and constructors" + )] + private static void AddTypeConversion< + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] TStrongType>( + IRequestExecutorBuilder builder + ) { + // ReSharper disable once NullableWarningSuppressionIsUsed var underlyingType = typeof(TStrongType).GetProperty("Value")!.PropertyType; { @@ -91,6 +103,7 @@ private static void AddTypeConversion(IRequestExecutorBuilder build var value = Expression.Parameter(underlyingType, "value"); var delegateType = typeof(ChangeType<,>).MakeGenericType(underlyingType, typeof(TStrongType)); + // ReSharper disable once NullableWarningSuppressionIsUsed var constructor = typeof(TStrongType).GetConstructor(new[] { underlyingType })!; AddTypeConverterMethod.MakeGenericMethod(underlyingType, typeof(TStrongType)) .Invoke( diff --git a/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs b/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs index b2e805819..4b85c5d0a 100644 --- a/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs +++ b/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs @@ -1,5 +1,4 @@ using FairyBread; -using HotChocolate; using HotChocolate.Configuration; using HotChocolate.Internal; using HotChocolate.Resolvers; @@ -134,7 +133,7 @@ ArgumentDefinition argDef return null; } - return currBaseType!.GenericTypeArguments[0]; + return currBaseType.GenericTypeArguments[0]; } // Singular scalar @@ -199,17 +198,19 @@ DefinitionBase definition } catch (Exception ex) { +#pragma warning disable CA2201 throw new Exception( $"Problem getting runtime type for argument '{argDef.Name}' " + $"in field '{fieldDef.Name}' on object type '{objTypeDef.Name}'.", ex ); +#pragma warning restore CA2201 } // Cleanup context now we're done with these foreach (var key in argDef.ContextData.Keys) { - if (key.StartsWith(WellKnownContextData.Prefix)) + if (key.StartsWith(WellKnownContextData.Prefix, StringComparison.OrdinalIgnoreCase)) { argDef.ContextData.Remove(key); } diff --git a/src/HotChocolate/Validation/CustomValidatorRegistry.cs b/src/HotChocolate/Validation/CustomValidatorRegistry.cs index 95c0f7455..b93ab904c 100644 --- a/src/HotChocolate/Validation/CustomValidatorRegistry.cs +++ b/src/HotChocolate/Validation/CustomValidatorRegistry.cs @@ -3,7 +3,7 @@ namespace Rocket.Surgery.LaunchPad.HotChocolate.Validation; -public class CustomValidatorRegistry : ICustomValidatorRegistry, IValidatorRegistry +class CustomValidatorRegistry : ICustomValidatorRegistry, IValidatorRegistry { private readonly IServiceProvider _serviceProvider; @@ -23,7 +23,7 @@ public bool TryGetValidator(Type type, [NotNullWhen(true)] out ValidatorDescript } var validatorType = typeof(IValidator<>).MakeGenericType(type); - if (_serviceProvider.GetService(typeof(IValidator<>).MakeGenericType(type)) is { } service) + if (_serviceProvider.GetService(typeof(IValidator<>).MakeGenericType(type)) is { }) { descriptor = _cache[type] = new ValidatorDescriptor(validatorType); return true; diff --git a/src/HotChocolate/Validation/ValidationMiddleware.cs b/src/HotChocolate/Validation/ValidationMiddleware.cs index c463de3a9..6e6381b44 100644 --- a/src/HotChocolate/Validation/ValidationMiddleware.cs +++ b/src/HotChocolate/Validation/ValidationMiddleware.cs @@ -4,23 +4,13 @@ namespace Rocket.Surgery.LaunchPad.HotChocolate.Validation; -internal class ValidationMiddleware +[UsedImplicitly] +internal class ValidationMiddleware( + FieldDelegate next, + IValidatorProvider validatorProvider, + IValidationErrorsHandler validationErrorsHandler +) { - private readonly FieldDelegate _next; - private readonly IValidatorProvider _validatorProvider; - private readonly IValidationErrorsHandler _validationErrorsHandler; - - public ValidationMiddleware( - FieldDelegate next, - IValidatorProvider validatorProvider, - IValidationErrorsHandler validationErrorsHandler - ) - { - _next = next; - _validatorProvider = validatorProvider; - _validationErrorsHandler = validationErrorsHandler; - } - public async Task InvokeAsync(IMiddlewareContext context) { var arguments = context.Selection.Field.Arguments; @@ -29,12 +19,7 @@ public async Task InvokeAsync(IMiddlewareContext context) foreach (var argument in arguments) { - if (argument == null) - { - continue; - } - - var resolvedValidators = _validatorProvider + var resolvedValidators = validatorProvider .GetValidators(context, argument) .ToArray(); if (resolvedValidators.Length > 0) @@ -78,10 +63,10 @@ public async Task InvokeAsync(IMiddlewareContext context) if (invalidResults.Any()) { - _validationErrorsHandler.Handle(context, invalidResults); + validationErrorsHandler.Handle(context, invalidResults); return; } - await _next(context); + await next(context); } } diff --git a/src/Mapping.NewtonsoftJson/ConverterHelpers.cs b/src/Mapping.NewtonsoftJson/ConverterHelpers.cs index dc7a9d526..b7ffe6dd6 100644 --- a/src/Mapping.NewtonsoftJson/ConverterHelpers.cs +++ b/src/Mapping.NewtonsoftJson/ConverterHelpers.cs @@ -9,7 +9,8 @@ internal static byte[] WriteToBytes(JToken source) { using var memory = new MemoryStream(); using var sw = new StreamWriter(memory); - using var jw = new JsonTextWriter(sw) { Formatting = Formatting.None }; + using var jw = new JsonTextWriter(sw); + jw.Formatting = Formatting.None; source.WriteTo(jw); jw.Flush(); memory.Position = 0; diff --git a/src/Mapping.NewtonsoftJson/Profiles/NewtonsoftJsonProfile.cs b/src/Mapping.NewtonsoftJson/Profiles/NewtonsoftJsonProfile.cs index 5ba1eabb1..448c9007b 100644 --- a/src/Mapping.NewtonsoftJson/Profiles/NewtonsoftJsonProfile.cs +++ b/src/Mapping.NewtonsoftJson/Profiles/NewtonsoftJsonProfile.cs @@ -16,6 +16,7 @@ public class NewtonsoftJsonProfile : Profile /// /// The default constructor /// +#pragma warning disable IL2026 public NewtonsoftJsonProfile() { { @@ -86,6 +87,7 @@ public NewtonsoftJsonProfile() ); } } +#pragma warning restore IL2026 /// /// Gets the name of the profile. diff --git a/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj b/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj index 224aed4f4..c144e6c8f 100644 --- a/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj +++ b/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj @@ -5,6 +5,7 @@ $(PackageTags) Rocket.Surgery.LaunchPad.Mapping NewtonsoftJsonExports + false diff --git a/src/Mapping/Profiles/SystemJsonTextProfile.cs b/src/Mapping/Profiles/SystemJsonTextProfile.cs index 5bb42a5cf..48469e962 100644 --- a/src/Mapping/Profiles/SystemJsonTextProfile.cs +++ b/src/Mapping/Profiles/SystemJsonTextProfile.cs @@ -11,6 +11,7 @@ public class SystemJsonTextProfile : Profile /// /// The default constructor /// +#pragma warning disable IL2026 public SystemJsonTextProfile() { CreateMap().ConvertUsing( @@ -65,6 +66,7 @@ public SystemJsonTextProfile() : source.Value ); } +#pragma warning restore IL2026 /// /// Gets the name of the profile. diff --git a/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj b/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj index b131c7fa7..5958fc2c7 100644 --- a/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj +++ b/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj @@ -3,6 +3,7 @@ netstandard2.1;net6.0;net7.0 $(PackageTags) + false diff --git a/src/Metadata/AssemblyMetadataProvider.cs b/src/Metadata/AssemblyMetadataProvider.cs index bcb2a09dd..6a65cf2f8 100644 --- a/src/Metadata/AssemblyMetadataProvider.cs +++ b/src/Metadata/AssemblyMetadataProvider.cs @@ -23,14 +23,18 @@ public static AssemblyMetadataProvider Create(Assembly assembly) /// The assembly. public AssemblyMetadataProvider(Assembly assembly) { - // ReSharper disable once RedundantSuppressNullableWarningExpression Data = assembly .GetCustomAttributes() .ToLookup( x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase - )!; + ) +#if NETSTANDARD + // ReSharper disable once NullableWarningSuppressionIsUsed + ! +#endif + ; } /// diff --git a/src/Metadata/GitVersion.cs b/src/Metadata/GitVersion.cs index ff60471eb..72e8a4bd7 100644 --- a/src/Metadata/GitVersion.cs +++ b/src/Metadata/GitVersion.cs @@ -367,6 +367,7 @@ public override int GetHashCode() /// true if the current object is equal to the parameter; otherwise, false. public bool Equals(GitVersion? other) { + // ReSharper disable NullableWarningSuppressionIsUsed return other! != null! && Major == other.Major && Minor == other.Minor diff --git a/src/Metadata/PrefixExtensions.cs b/src/Metadata/PrefixExtensions.cs index 9e3ff8462..538c4df0a 100644 --- a/src/Metadata/PrefixExtensions.cs +++ b/src/Metadata/PrefixExtensions.cs @@ -14,9 +14,9 @@ internal static class PrefixExtensions /// /// The provider. /// The instance. - internal static void Infer(this AssemblyMetadataProvider provider, T instance) + internal static void Infer(this AssemblyMetadataProvider provider, T instance) where T : notnull { - foreach (var property in instance!.GetType().GetTypeInfo().DeclaredProperties) + foreach (var property in instance.GetType().GetTypeInfo().DeclaredProperties) { // simple props only if ( diff --git a/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs b/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs index 3e6acbca5..6df67917c 100644 --- a/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs +++ b/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs @@ -18,6 +18,10 @@ namespace Rocket.Surgery.LaunchPad.Serilog.Conventions; public class SerilogReadFromConfigurationConvention : ISerilogConvention, IConfigurationConvention { /// +#if NET6_0_OR_GREATER + [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification + = "The type is an enum value")] +#endif public void Register(IConventionContext context, IConfiguration configuration, IConfigurationBuilder builder) { if (context == null) diff --git a/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs b/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs index 266df9036..0bd891db9 100644 --- a/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs +++ b/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs @@ -2,7 +2,6 @@ using NetTopologySuite.Geometries; using NetTopologySuite.IO.Converters; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace Rocket.Surgery.LaunchPad.Spatial; diff --git a/src/Spatial.NewtonsoftJson/WktGeometryConverter.cs b/src/Spatial.NewtonsoftJson/WktGeometryConverter.cs index 5c09918f3..c153e79ea 100644 --- a/src/Spatial.NewtonsoftJson/WktGeometryConverter.cs +++ b/src/Spatial.NewtonsoftJson/WktGeometryConverter.cs @@ -13,10 +13,8 @@ public class WktGeometryConverter : GeometryConverter /// /// Gets a default GeometryFactory /// - internal static GeometryFactory Wgs84Factory { get; } = new GeometryFactory(new PrecisionModel(), 4326); + internal static GeometryFactory Wgs84Factory { get; } = new (new PrecisionModel(), 4326); - private readonly GeometryFactory _geometryFactory; - private readonly int _dimension; private readonly WKTReader _wktReader; /// @@ -41,21 +39,19 @@ public WktGeometryConverter(GeometryFactory geometryFactory) : this(geometryFact /// The number of dimensions to handle. Must be 2 or 3. public WktGeometryConverter(GeometryFactory geometryFactory, int dimension) : base(geometryFactory, dimension) { - _geometryFactory = geometryFactory; - _dimension = dimension; _wktReader = new WKTReader(geometryFactory.GeometryServices); } /// - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; - return _wktReader.Read(reader.Value!.ToString()); + return _wktReader.Read(reader.Value?.ToString()); } /// - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value is not Geometry geom) { diff --git a/src/Spatial/Conventions/SpatialConvention.cs b/src/Spatial/Conventions/SpatialConvention.cs index f3fee97ca..d926254c5 100644 --- a/src/Spatial/Conventions/SpatialConvention.cs +++ b/src/Spatial/Conventions/SpatialConvention.cs @@ -28,7 +28,7 @@ public void Register(IConventionContext context, IServiceProvider services, ICon public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { services.TryAddSingleton(NtsGeometryServices.Instance); - services.TryAddSingleton(_ => _.GetRequiredService().CreateGeometryFactory(4326)); + services.TryAddSingleton(provider => provider.GetRequiredService().CreateGeometryFactory(4326)); services .AddOptions(null) .Configure( diff --git a/src/Spatial/NetTopologySuiteDestructuringPolicy.cs b/src/Spatial/NetTopologySuiteDestructuringPolicy.cs index 5494d5e4d..6a00a5384 100644 --- a/src/Spatial/NetTopologySuiteDestructuringPolicy.cs +++ b/src/Spatial/NetTopologySuiteDestructuringPolicy.cs @@ -1,4 +1,3 @@ -using NetTopologySuite.Algorithm; using NetTopologySuite.Features; using NetTopologySuite.Geometries; using Serilog.Core; @@ -6,11 +5,11 @@ namespace Rocket.Surgery.LaunchPad.Spatial; -internal class NetTopologySuiteDestructuringPolicy : IDestructuringPolicy +internal class NetTopologySuiteDestructuringPolicy(string? idPropertyName) : IDestructuringPolicy { public const string defaultIdPropertyName = "_NetTopologySuite_id"; - public static LogEventPropertyValue WriteGeometry(ILogEventPropertyValueFactory propertyValueFactory, Geometry value) + public static LogEventPropertyValue WriteGeometry(Geometry value) { return new ScalarValue(value.AsText()); } @@ -69,103 +68,11 @@ private static LogEventPropertyValue WriteFeatureCollection(ILogEventPropertyVal return new StructureValue(props); } - private static SequenceValue WriteGeometrySequence(Geometry value) - { - var values = new LogEventPropertyValue?[value.NumGeometries]; - for (var i = 0; i < value.NumGeometries; i++) - { - values[i] = value switch - { - MultiPoint => WriteCoordinateSequence(( (Point)value.GetGeometryN(i) ).CoordinateSequence, false), - MultiLineString => WriteCoordinateSequence(( (LineString)value.GetGeometryN(i) ).CoordinateSequence, true), - MultiPolygon => WritePolygon((Polygon)value.GetGeometryN(i)), - _ => default - }; - } - - return new SequenceValue(values); - } - - private static LogEventPropertyValue WritePolygon(Polygon value) - { - var values = new List(value.NumInteriorRings + 1); - values.Add(WriteCoordinateSequence(value.ExteriorRing.CoordinateSequence, true, OrientationIndex.Clockwise)); - for (var i = 0; i < value.NumInteriorRings; i++) - values.Add( - WriteCoordinateSequence( - value.GetInteriorRingN(i).CoordinateSequence, true, OrientationIndex.CounterClockwise - ) - ); - return new SequenceValue(values); - } - - private static LogEventPropertyValue WriteCoordinateSequence( - CoordinateSequence? sequence, - bool multiple, - OrientationIndex orientation = OrientationIndex.None - ) - { - if (sequence == null) - { - return new ScalarValue(null); - } - - var values = new List(); - - if (multiple) - { - if (( orientation == OrientationIndex.Clockwise && Orientation.IsCCW(sequence) ) || - ( orientation == OrientationIndex.CounterClockwise && !Orientation.IsCCW(sequence) )) - { - CoordinateSequences.Reverse(sequence); - } - } - - var hasZ = sequence.HasZ; - for (var i = 0; i < sequence.Count; i++) - { - var value = new List(3); - value.Add(new ScalarValue(sequence.GetX(i))); - value.Add(new ScalarValue(sequence.GetY(i))); - - if (hasZ) - { - var z = sequence.GetZ(i); - if (!double.IsNaN(z)) - value.Add(new ScalarValue(z)); - } - - if (multiple) - { - values.Add(new SequenceValue(value)); - } - else - { - values = value; - break; - } - } - - return new SequenceValue(values); - } - - private readonly string _idPropertyName; - private readonly bool _writeGeometryBBox; + private readonly string _idPropertyName = idPropertyName ?? defaultIdPropertyName; public NetTopologySuiteDestructuringPolicy() - : this(false) - { - } - - public NetTopologySuiteDestructuringPolicy(bool writeGeometryBBox) - : this(writeGeometryBBox, defaultIdPropertyName) - { - } - - public NetTopologySuiteDestructuringPolicy(bool writeGeometryBBox, string? idPropertyName) + : this(defaultIdPropertyName) { - _writeGeometryBBox = writeGeometryBBox; - _idPropertyName = idPropertyName ?? defaultIdPropertyName; } private LogEventPropertyValue WriteFeature(ILogEventPropertyValueFactory propertyValueFactory, IFeature value) @@ -213,11 +120,11 @@ private LogEventPropertyValue WriteAttributes(ILogEventPropertyValueFactory prop return new StructureValue(props); } - public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue? result) + public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, [NotNullWhen(true)] out LogEventPropertyValue? result) { if (value is Geometry geometry && GeometryTypes.Contains(value.GetType())) { - result = WriteGeometry(propertyValueFactory, geometry); + result = WriteGeometry(geometry); return true; } diff --git a/src/Spatial/WktConverterFactory.cs b/src/Spatial/WktConverterFactory.cs index 9a4a2e864..869349df0 100644 --- a/src/Spatial/WktConverterFactory.cs +++ b/src/Spatial/WktConverterFactory.cs @@ -25,7 +25,6 @@ public class WktConverterFactory : GeoJsonConverterFactory }; private readonly GeometryFactory _factory; - private readonly bool _writeGeometryBBox; /// /// Creates an instance of this class using the defaults. @@ -70,15 +69,15 @@ public WktConverterFactory(GeometryFactory factory, bool writeGeometryBBox, stri : base(factory, writeGeometryBBox, idPropertyName) { _factory = factory; - _writeGeometryBBox = writeGeometryBBox; } /// public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { return GeometryTypes.Contains(typeToConvert) - ? new WktGeometryConverter(_factory, _writeGeometryBBox) - : base.CreateConverter(typeToConvert, options); + ? new WktGeometryConverter(_factory) + // ReSharper disable once NullableWarningSuppressionIsUsed + : base.CreateConverter(typeToConvert, options)!; } } diff --git a/src/Spatial/WktGeometryConverter.cs b/src/Spatial/WktGeometryConverter.cs index 5c1f1d654..71de6cb84 100644 --- a/src/Spatial/WktGeometryConverter.cs +++ b/src/Spatial/WktGeometryConverter.cs @@ -10,22 +10,18 @@ internal partial class WktGeometryConverter : JsonConverter /// /// Gets the default geometry factory to use with this converter. /// - public static GeometryFactory DefaultGeometryFactory { get; } = new GeometryFactory(new PrecisionModel(), 4326); + public static GeometryFactory DefaultGeometryFactory { get; } = new(new PrecisionModel(), 4326); - private readonly GeometryFactory _geometryFactory; - private readonly bool _writeGeometryBBox; private readonly WKTReader _wktReader; /// /// Creates an instance of this class /// /// The geometry factory to use. - /// Whether or not to write "bbox" with the geometry. - public WktGeometryConverter(GeometryFactory geometryFactory, bool writeGeometryBBox) + public WktGeometryConverter(GeometryFactory? geometryFactory) { - _geometryFactory = geometryFactory ?? DefaultGeometryFactory; - _writeGeometryBBox = writeGeometryBBox; - _wktReader = new WKTReader(_geometryFactory.GeometryServices); + var geometryFactory1 = geometryFactory ?? DefaultGeometryFactory; + _wktReader = new WKTReader(geometryFactory1.GeometryServices); } diff --git a/src/StrawberryShake.Spatial/Conventions/StrawberryShakeSpatialConvention.cs b/src/StrawberryShake.Spatial/Conventions/StrawberryShakeSpatialConvention.cs index 33d5d8abf..ed894d532 100644 --- a/src/StrawberryShake.Spatial/Conventions/StrawberryShakeSpatialConvention.cs +++ b/src/StrawberryShake.Spatial/Conventions/StrawberryShakeSpatialConvention.cs @@ -1,15 +1,7 @@ -using System.Text.Json; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using NetTopologySuite; -using NetTopologySuite.Geometries; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.LaunchPad.Serilog; -using Rocket.Surgery.LaunchPad.Spatial; -using Rocket.Surgery.LaunchPad.StrawberryShake.Conventions; -using Serilog; namespace Rocket.Surgery.LaunchPad.StrawberryShake.Spatial.Conventions; diff --git a/src/StrawberryShake.Spatial/CoordinatesSerializer.cs b/src/StrawberryShake.Spatial/CoordinatesSerializer.cs index 89ad4698c..2976b9826 100644 --- a/src/StrawberryShake.Spatial/CoordinatesSerializer.cs +++ b/src/StrawberryShake.Spatial/CoordinatesSerializer.cs @@ -4,8 +4,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake.Spatial; +/// +/// A general purpose serializer for Coordinates +/// public class CoordinatesSerializer : JsonElementScalarSerializer { + /// + /// Create a new CoordinatesSerializer + /// + /// public CoordinatesSerializer(IOptions options) : base("Coordinates", options) { } diff --git a/src/StrawberryShake.Spatial/GeometrySerializer.cs b/src/StrawberryShake.Spatial/GeometrySerializer.cs index 932d1cea3..e9f20e144 100644 --- a/src/StrawberryShake.Spatial/GeometrySerializer.cs +++ b/src/StrawberryShake.Spatial/GeometrySerializer.cs @@ -4,9 +4,16 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake.Spatial; +/// +/// General purpose Geometry Serializer +/// public class GeometrySerializer : JsonElementScalarSerializer { + /// + /// Construct a new GeometrySerializer + /// + /// public GeometrySerializer(IOptions options) : base("Geometry", options) { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/Conventions/StrawberryShakeConvention.cs b/src/StrawberryShake/Conventions/StrawberryShakeConvention.cs index 131d2c9cf..e022bb992 100644 --- a/src/StrawberryShake/Conventions/StrawberryShakeConvention.cs +++ b/src/StrawberryShake/Conventions/StrawberryShakeConvention.cs @@ -1,10 +1,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.LaunchPad.Serilog; -using Serilog; namespace Rocket.Surgery.LaunchPad.StrawberryShake.Conventions; diff --git a/src/StrawberryShake/DateTimeZoneSerializer.cs b/src/StrawberryShake/DateTimeZoneSerializer.cs index 92beaf94c..027f9d4b3 100644 --- a/src/StrawberryShake/DateTimeZoneSerializer.cs +++ b/src/StrawberryShake/DateTimeZoneSerializer.cs @@ -3,20 +3,29 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// Create a new DateTimeZoneSerializer +/// public class DateTimeZoneSerializer : ScalarSerializer { private readonly IDateTimeZoneProvider _provider; + /// + /// Constructor for a new DateTimeZoneSerializer + /// + /// public DateTimeZoneSerializer(IDateTimeZoneProvider provider) : base("DateTimeZone") { _provider = provider; } + /// public override DateTimeZone Parse(string serializedValue) { return _provider[serializedValue]; } + /// protected override string Format(DateTimeZone runtimeValue) { return runtimeValue.Id; diff --git a/src/StrawberryShake/DurationSerializer.cs b/src/StrawberryShake/DurationSerializer.cs index 0476af37e..3b1322ad3 100644 --- a/src/StrawberryShake/DurationSerializer.cs +++ b/src/StrawberryShake/DurationSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose Duration Serializer +/// public class DurationSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new DurationSerializer + /// public DurationSerializer() : base(DurationPattern.CreateWithInvariantCulture("-H:mm:ss.FFFFFFFFF"), "Duration") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/EnumScalarSerializer.cs b/src/StrawberryShake/EnumScalarSerializer.cs index dad85d6a6..96a40e684 100644 --- a/src/StrawberryShake/EnumScalarSerializer.cs +++ b/src/StrawberryShake/EnumScalarSerializer.cs @@ -2,13 +2,24 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// Base class for enum serializers +/// +/// public abstract class EnumScalarSerializer : ScalarSerializer where TRuntime : struct { + /// + /// Constructor for enum serializers + /// + /// protected EnumScalarSerializer(string typeName) : base(typeName) { } + /// public override TRuntime Parse(int serializedValue) => (TRuntime)Enum.ToObject(typeof(TRuntime), serializedValue); + + /// protected override int Format(TRuntime runtimeValue) => (int)(object)runtimeValue; } diff --git a/src/StrawberryShake/InstantSerializer.cs b/src/StrawberryShake/InstantSerializer.cs index 9980700f9..a3e4ef2a3 100644 --- a/src/StrawberryShake/InstantSerializer.cs +++ b/src/StrawberryShake/InstantSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose Instant Serializer +/// public class InstantSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new InstantSerializer + /// public InstantSerializer() : base(InstantPattern.General, "Instant") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/IsoDayOfWeekSerializer.cs b/src/StrawberryShake/IsoDayOfWeekSerializer.cs index 2922b3df6..a1f9fc5a1 100644 --- a/src/StrawberryShake/IsoDayOfWeekSerializer.cs +++ b/src/StrawberryShake/IsoDayOfWeekSerializer.cs @@ -2,9 +2,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose IsoDayOfWeek Serializer +/// public class IsoDayOfWeekSerializer : EnumScalarSerializer { + /// + /// Create a new IsoDayOfWeekSerializer + /// public IsoDayOfWeekSerializer() : base("IsoDayOfWeek") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/JsonElementScalarSerializer.cs b/src/StrawberryShake/JsonElementScalarSerializer.cs index 2b510993c..0f6c7ebc0 100644 --- a/src/StrawberryShake/JsonElementScalarSerializer.cs +++ b/src/StrawberryShake/JsonElementScalarSerializer.cs @@ -5,24 +5,31 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// Base class for JsonElement Scalar Serializers +/// +/// public abstract class JsonElementScalarSerializer : ScalarSerializer { private readonly IOptions _options; + + /// + /// Constructor for JsonElement Scalar Serializers + /// + /// + /// protected JsonElementScalarSerializer(string typeName, IOptions options) : base(typeName) => _options = options; + /// public override TRuntime Parse(JsonElement serializedValue) { -// Console.WriteLine("=== START ==="); -// foreach (var item in _options.Value.Converters) -// { -// Console.WriteLine(item.GetType()); -// } -// Console.WriteLine("=== END ==="); + // ReSharper disable once NullableWarningSuppressionIsUsed return serializedValue.Deserialize(_options.Value)!; } + /// protected override JsonElement Format(TRuntime runtimeValue) { return JsonSerializer.SerializeToElement(runtimeValue, _options.Value); } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/LocalDateSerializer.cs b/src/StrawberryShake/LocalDateSerializer.cs index 944190c2d..83d880f06 100644 --- a/src/StrawberryShake/LocalDateSerializer.cs +++ b/src/StrawberryShake/LocalDateSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose LocalDate Serializer +/// public class LocalDateSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new LocalDateSerializer + /// public LocalDateSerializer() : base(LocalDatePattern.Iso, "LocalDate") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/LocalDateTimeSerializer.cs b/src/StrawberryShake/LocalDateTimeSerializer.cs index 712b6bead..bff488c93 100644 --- a/src/StrawberryShake/LocalDateTimeSerializer.cs +++ b/src/StrawberryShake/LocalDateTimeSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose LocalDateTime Serializer +/// public class LocalDateTimeSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new LocalDateTimeSerializer + /// public LocalDateTimeSerializer() : base(LocalDateTimePattern.GeneralIso, "LocalDateTime") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/LocalTimeSerializer.cs b/src/StrawberryShake/LocalTimeSerializer.cs index 51cfc56d1..2a3ea04f6 100644 --- a/src/StrawberryShake/LocalTimeSerializer.cs +++ b/src/StrawberryShake/LocalTimeSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose LocalTime Serializer +/// public class LocalTimeSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new LocalTimeSerializer + /// public LocalTimeSerializer() : base(LocalTimePattern.GeneralIso, "LocalTime") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/NodaTimeStringScalarSerializer.cs b/src/StrawberryShake/NodaTimeStringScalarSerializer.cs index fe43990a2..5c1b10b3a 100644 --- a/src/StrawberryShake/NodaTimeStringScalarSerializer.cs +++ b/src/StrawberryShake/NodaTimeStringScalarSerializer.cs @@ -3,15 +3,27 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// Shared base class for NodaTime string serializers +/// +/// public abstract class NodaTimeStringScalarSerializer : ScalarSerializer { private readonly IPattern _pattern; + /// + /// Based consturctor for NodaTime string serializers + /// + /// + /// protected NodaTimeStringScalarSerializer(IPattern pattern, string typeName) : base(typeName) { _pattern = pattern; } + /// public override TRuntime Parse(string serializedValue) => _pattern.Parse(serializedValue).Value; + + /// protected override string Format(TRuntime runtimeValue) => _pattern.Format(runtimeValue); -} \ No newline at end of file +} diff --git a/src/StrawberryShake/OffsetDateSerializer.cs b/src/StrawberryShake/OffsetDateSerializer.cs index c023d8d97..1e14b78ea 100644 --- a/src/StrawberryShake/OffsetDateSerializer.cs +++ b/src/StrawberryShake/OffsetDateSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose OffsetDate Serializer +/// public class OffsetDateSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new OffsetDateSerializer + /// public OffsetDateSerializer() : base(OffsetDatePattern.GeneralIso, "OffsetDate") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/OffsetDateTimeSerializer.cs b/src/StrawberryShake/OffsetDateTimeSerializer.cs index 26a9333ef..5083a06cf 100644 --- a/src/StrawberryShake/OffsetDateTimeSerializer.cs +++ b/src/StrawberryShake/OffsetDateTimeSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// Create a new OffsetDateTimeSerializer +/// public class OffsetDateTimeSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new OffsetDateTimeSerializer + /// public OffsetDateTimeSerializer() : base(OffsetDateTimePattern.GeneralIso, "OffsetDateTime") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/OffsetSerializer.cs b/src/StrawberryShake/OffsetSerializer.cs index dfb74fe59..8fb04c994 100644 --- a/src/StrawberryShake/OffsetSerializer.cs +++ b/src/StrawberryShake/OffsetSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose Offset Serializer +/// public class OffsetSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new OffsetSerializer + /// public OffsetSerializer() : base(OffsetPattern.GeneralInvariant, "Offset") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/OffsetTimeSerializer.cs b/src/StrawberryShake/OffsetTimeSerializer.cs index f9216f5be..347ffc85a 100644 --- a/src/StrawberryShake/OffsetTimeSerializer.cs +++ b/src/StrawberryShake/OffsetTimeSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose OffsetDateTime Serializer +/// public class OffsetTimeSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new OffsetDateTimeSerializer + /// public OffsetTimeSerializer() : base(OffsetTimePattern.GeneralIso, "OffsetTime") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/PeriodSerializer.cs b/src/StrawberryShake/PeriodSerializer.cs index 0f3b837da..5937cae58 100644 --- a/src/StrawberryShake/PeriodSerializer.cs +++ b/src/StrawberryShake/PeriodSerializer.cs @@ -3,9 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose Period Serializer +/// public class PeriodSerializer : NodaTimeStringScalarSerializer { + /// + /// Create a new PeriodSerializer + /// public PeriodSerializer() : base(PeriodPattern.NormalizingIso, "Period") { } -} \ No newline at end of file +} diff --git a/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj b/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj index 04d9d54b4..a0fa7ffe3 100644 --- a/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj +++ b/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj @@ -3,6 +3,7 @@ net6.0;net7.0 $(PackageTags) + false diff --git a/src/StrawberryShake/ZonedDateTimeSerializer.cs b/src/StrawberryShake/ZonedDateTimeSerializer.cs index bab58e209..36f2a8273 100644 --- a/src/StrawberryShake/ZonedDateTimeSerializer.cs +++ b/src/StrawberryShake/ZonedDateTimeSerializer.cs @@ -3,8 +3,15 @@ namespace Rocket.Surgery.LaunchPad.StrawberryShake; +/// +/// General purpose ZonedDateTime Serializer +/// public class ZonedDateTimeSerializer : NodaTimeStringScalarSerializer { + /// + /// Construct a new ZonedDateTimeSerializer + /// + /// public ZonedDateTimeSerializer(IDateTimeZoneProvider provider) : base( ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo z", provider), "ZonedDateTime" ) diff --git a/src/Telemetry/IOpenTelemetryMetricsConvention.cs b/src/Telemetry/IOpenTelemetryMetricsConvention.cs index 3b84491d3..5a27d90bb 100644 --- a/src/Telemetry/IOpenTelemetryMetricsConvention.cs +++ b/src/Telemetry/IOpenTelemetryMetricsConvention.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Configuration; -using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; diff --git a/src/Telemetry/OpenTelemetryMetricsConvention.cs b/src/Telemetry/OpenTelemetryMetricsConvention.cs index 440a6e805..f251beede 100644 --- a/src/Telemetry/OpenTelemetryMetricsConvention.cs +++ b/src/Telemetry/OpenTelemetryMetricsConvention.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Configuration; -using OpenTelemetry; using OpenTelemetry.Metrics; using Rocket.Surgery.Conventions; diff --git a/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs b/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs index 9da11c7f1..7cd74d170 100644 --- a/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs +++ b/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Configuration; -using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; diff --git a/src/Testing/FakeClockConvention.cs b/src/Testing/FakeClockConvention.cs index ecd00215c..1ccb73bff 100644 --- a/src/Testing/FakeClockConvention.cs +++ b/src/Testing/FakeClockConvention.cs @@ -36,6 +36,6 @@ public FakeClockConvention(int? unixTimeSeconds = null, Duration? advanceBy = nu public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { services.TryAddSingleton(new FakeClock(Instant.FromUnixTimeSeconds(_unixTimeSeconds), _advanceBy)); - services.TryAddSingleton(_ => _.GetRequiredService()); + services.TryAddSingleton(provider => provider.GetRequiredService()); } } diff --git a/test/.editorconfig b/test/.editorconfig index 3cbb0a494..8845c9b89 100644 --- a/test/.editorconfig +++ b/test/.editorconfig @@ -1,6 +1,7 @@ [*] dotnet_diagnostic.CA1014.severity = none dotnet_diagnostic.CA1034.severity = none +dotnet_diagnostic.CA1305.severity = none dotnet_diagnostic.CA1040.severity = none dotnet_diagnostic.CA1062.severity = none dotnet_diagnostic.CA1707.severity = none @@ -9,6 +10,7 @@ dotnet_diagnostic.CA1715.severity = none dotnet_diagnostic.CA1720.severity = none dotnet_diagnostic.CA1812.severity = none dotnet_diagnostic.CA1848.severity = none +dotnet_diagnostic.CA1851.severity = none dotnet_diagnostic.CA2000.severity = none dotnet_diagnostic.CA2225.severity = none dotnet_diagnostic.CA2227.severity = none @@ -22,3 +24,4 @@ dotnet_diagnostic.CA1724.severity = none resharper_possible_multiple_enumeration_highlighting = none resharper_template_is_not_compile_time_constant_problem_highlighting = none resharper_inconsistent_naming_highlighting = none +resharper_nullable_warning_suppression_is_used_highlighting = none diff --git a/test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj b/test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj index 6a9baee3f..ee471b48e 100644 --- a/test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj +++ b/test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj @@ -12,8 +12,7 @@ - - + diff --git a/test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj b/test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj index 0194aee12..f75a2b809 100644 --- a/test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj +++ b/test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj @@ -12,8 +12,7 @@ - - + diff --git a/test/Analyzers.Tests/Analyzers.Tests.csproj b/test/Analyzers.Tests/Analyzers.Tests.csproj index 4dfd3fb29..bbcb2c1d5 100644 --- a/test/Analyzers.Tests/Analyzers.Tests.csproj +++ b/test/Analyzers.Tests/Analyzers.Tests.csproj @@ -9,8 +9,7 @@ - - + diff --git a/test/Analyzers.Tests/ControllerActionBodyGeneratorTests.cs b/test/Analyzers.Tests/ControllerActionBodyGeneratorTests.cs index 7f7e6aa0d..210e92760 100644 --- a/test/Analyzers.Tests/ControllerActionBodyGeneratorTests.cs +++ b/test/Analyzers.Tests/ControllerActionBodyGeneratorTests.cs @@ -92,7 +92,7 @@ public async Task Should_Generate_Method_Bodies(string key, string[] sources) await Verify(await GenerateAsync(sources)).UseParameters(key, ""); } - private class MethodBodyData : TheoryData + private sealed class MethodBodyData : TheoryData { private const string defaultString = @" namespace TestNamespace; diff --git a/test/Analyzers.Tests/GraphqlMutationActionBodyGeneratorTests.cs b/test/Analyzers.Tests/GraphqlMutationActionBodyGeneratorTests.cs index 3ce18ba53..0375797ca 100644 --- a/test/Analyzers.Tests/GraphqlMutationActionBodyGeneratorTests.cs +++ b/test/Analyzers.Tests/GraphqlMutationActionBodyGeneratorTests.cs @@ -87,7 +87,7 @@ public async Task Should_Generate_Method_Bodies(string key, string[] sources) await Verify(await GenerateAsync(sources)).UseParameters(key, ""); } - private class MethodBodyData : TheoryData + private sealed class MethodBodyData : TheoryData { private const string defaultString = @" namespace TestNamespace; diff --git a/test/Analyzers.Tests/Helpers/GeneratorTest.cs b/test/Analyzers.Tests/Helpers/GeneratorTest.cs index 5ede8c230..d70e638e8 100644 --- a/test/Analyzers.Tests/Helpers/GeneratorTest.cs +++ b/test/Analyzers.Tests/Helpers/GeneratorTest.cs @@ -44,12 +44,8 @@ public static Assembly EmitInto(this CSharpCompilation compilation, AssemblyLoad // } } -internal class CollectibleTestAssemblyLoadContext : AssemblyLoadContext, IDisposable +internal sealed class CollectibleTestAssemblyLoadContext() : AssemblyLoadContext(true), IDisposable { - public CollectibleTestAssemblyLoadContext() : base(true) - { - } - protected override Assembly? Load(AssemblyName assemblyName) { return null; diff --git a/test/Analyzers.Tests/ModuleInitializer.cs b/test/Analyzers.Tests/ModuleInitializer.cs index 456153c57..515235ab8 100644 --- a/test/Analyzers.Tests/ModuleInitializer.cs +++ b/test/Analyzers.Tests/ModuleInitializer.cs @@ -41,6 +41,7 @@ static string GetTypeName(Type type) var typeName = GetTypeName(type); + // ReSharper disable once RedundantAssignment var path = Path.Combine(Path.GetDirectoryName(sourceFile)!, "snapshots"); #if !ROSLYN_CURRENT path = Path.Combine(Path.GetDirectoryName(sourceFile)!, "../Analyzers.Tests", "snapshots"); @@ -133,7 +134,7 @@ private static ConversionResult Convert(GeneratorDriver target, IReadOnlyDiction return Convert(target.GetRunResult(), context); } - private class LocalizableStringConverter : + private sealed class LocalizableStringConverter : WriteOnlyJsonConverter { public override void Write(VerifyJsonWriter writer, LocalizableString value) @@ -142,7 +143,7 @@ public override void Write(VerifyJsonWriter writer, LocalizableString value) } } - private class DiagnosticConverter : + private sealed class DiagnosticConverter : WriteOnlyJsonConverter { public override void Write(VerifyJsonWriter writer, Diagnostic value) @@ -164,7 +165,7 @@ public override void Write(VerifyJsonWriter writer, Diagnostic value) } } - private class LocationConverter : + private sealed class LocationConverter : WriteOnlyJsonConverter { public override void Write(VerifyJsonWriter writer, Location value) @@ -173,7 +174,7 @@ public override void Write(VerifyJsonWriter writer, Location value) } } - private class GeneratedSourceResultConverter : + private sealed class GeneratedSourceResultConverter : WriteOnlyJsonConverter { public override void Write(VerifyJsonWriter writer, GeneratedSourceResult value) @@ -189,7 +190,7 @@ public override void Write(VerifyJsonWriter writer, GeneratedSourceResult value) } } - private class DiagnosticDescriptorConverter : + private sealed class DiagnosticDescriptorConverter : WriteOnlyJsonConverter { public override void Write(VerifyJsonWriter writer, DiagnosticDescriptor value) @@ -208,7 +209,7 @@ public override void Write(VerifyJsonWriter writer, DiagnosticDescriptor value) } } - private class SourceTextConverter : + private sealed class SourceTextConverter : WriteOnlyJsonConverter { public override void Write(VerifyJsonWriter writer, SourceText value) diff --git a/test/AspNetCore.Tests/Restful/RestfulApiMethodBuilderTests.cs b/test/AspNetCore.Tests/Restful/RestfulApiMethodBuilderTests.cs index 51927c3f7..e53645b8a 100644 --- a/test/AspNetCore.Tests/Restful/RestfulApiMethodBuilderTests.cs +++ b/test/AspNetCore.Tests/Restful/RestfulApiMethodBuilderTests.cs @@ -8,12 +8,8 @@ namespace AspNetCore.Tests.Restful; -public class RestfulApiMethodBuilderTests : LoggerTest +public class RestfulApiMethodBuilderTests(ITestOutputHelper testOutputHelper) : LoggerTest(testOutputHelper) { - public RestfulApiMethodBuilderTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void Should_Have_Method() { @@ -212,15 +208,11 @@ private Task> ThreeParameter(long id, object two, int three throw new NotImplementedException(); } - private class Request : IRequest - { - } + private sealed class Request : IRequest; - private class RequestResponse : IRequest - { - } + private sealed class RequestResponse : IRequest; - private class Matching : TheoryData + private sealed class Matching : TheoryData { public Matching() { @@ -246,7 +238,7 @@ public Matching() } [PublicAPI] - public class ListActions + public sealed class ListActions { public Task> ListPeople(Request listRequest) { @@ -270,7 +262,7 @@ public Task> SearchPeopleIndex(int orgId, Request request) } [PublicAPI] - public class GetActions + public sealed class GetActions { public Task> GetPerson(Request personRequest) { @@ -314,7 +306,7 @@ public Task> ReadPersonIndex(int orgId, int groupId, Reques } [PublicAPI] - public class PostActions + public sealed class PostActions { public Task> PostPerson(Request request) { @@ -348,7 +340,7 @@ public Task> AddPersonIndex(int orgId, int groupId, Request } [PublicAPI] - public class PutActions + public sealed class PutActions { public Task> PutPerson(Guid personId, Request request) { @@ -412,7 +404,7 @@ public Task> UpdateOtherPersonIndex(int orgId, int groupId, } [PublicAPI] - public class DeleteActions + public sealed class DeleteActions { public Task> DeletePerson(Request request) { @@ -456,7 +448,7 @@ public Task> RemoveOtherPersonIndex(int org, Guid personId) } } - private class NonMatching : TheoryData + private sealed class NonMatching : TheoryData { public NonMatching() { @@ -482,7 +474,7 @@ public NonMatching() } [PublicAPI] - public class ListActions + public sealed class ListActions { public Task> PeopleList(Request request) { @@ -496,7 +488,7 @@ public Task> PeopleSearch(Request request) } [PublicAPI] - public class GetActions + public sealed class GetActions { public Task> PeopleGet(Request request) { @@ -520,7 +512,7 @@ public Task> PeopleRead(Request request) } [PublicAPI] - public class PostActions + public sealed class PostActions { public Task> PersonPost(Request request) { @@ -539,7 +531,7 @@ public Task> PersonAdd(Request request) } [PublicAPI] - public class PutActions + public sealed class PutActions { public Task> PersonPut(Guid id, Request request) { @@ -573,7 +565,7 @@ public Task> UpdatePerson(long id, object asdf) } [PublicAPI] - public class DeleteActions + public sealed class DeleteActions { public Task> PersonDelete(Request request) { diff --git a/test/Directory.Build.props b/test/Directory.Build.props index 1b3104a05..2ad7bc165 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -6,6 +6,7 @@ $(NoWarn);CA1812 false false + false @@ -19,7 +20,9 @@ 30023 - Branch.feature-metadata.Sha.247f6f1c46147dd60479462ce2eef81c04b0a056 + Branch.feature-metadata.Sha.247f6f1c46147dd60479462ce2eef81c04b0a056 0.1.0 0.1.0-metadata.23 0.1.0-metadata23 @@ -27,7 +30,9 @@ 0.1.0.0 0.1.0.0 0.1.0-metadata.23 - 0.1.0-metadata.23+Branch.feature-metadata.Sha.247f6f1c46147dd60479462ce2eef81c04b0a056 + 0.1.0-metadata.23+Branch.feature-metadata.Sha.247f6f1c46147dd60479462ce2eef81c04b0a056 feature/metadata feature-metadata 247f6f1c46147dd60479462ce2eef81c04b0a056 @@ -38,7 +43,9 @@ metadata0023 1981f927d7d3702e830e0ce96974ad5692b720f0 23 - 0023 + 0023 2020-07-11 diff --git a/test/Extensions.Tests/ConventionFakeTest.cs b/test/Extensions.Tests/ConventionFakeTest.cs index e6fcdb942..cb3a31321 100644 --- a/test/Extensions.Tests/ConventionFakeTest.cs +++ b/test/Extensions.Tests/ConventionFakeTest.cs @@ -6,16 +6,12 @@ namespace Extensions.Tests; -public abstract class ConventionFakeTest : AutoFakeTest +public abstract class ConventionFakeTest(ITestOutputHelper testOutputHelper) : AutoFakeTest(testOutputHelper) { - protected ConventionFakeTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - protected void Init(Action? action = null) { var conventionContextBuilder = ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly), LoggerFactory) + .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) .WithLogger(Logger); action?.Invoke(conventionContextBuilder); var context = ConventionContext.From(conventionContextBuilder); diff --git a/test/Extensions.Tests/Extensions.Tests.csproj b/test/Extensions.Tests/Extensions.Tests.csproj index 76ea1bdfd..dc90609f7 100644 --- a/test/Extensions.Tests/Extensions.Tests.csproj +++ b/test/Extensions.Tests/Extensions.Tests.csproj @@ -13,7 +13,6 @@ - diff --git a/test/Extensions.Tests/FakeClockConventionTests.cs b/test/Extensions.Tests/FakeClockConventionTests.cs index 59e670fc6..a9d915e44 100644 --- a/test/Extensions.Tests/FakeClockConventionTests.cs +++ b/test/Extensions.Tests/FakeClockConventionTests.cs @@ -6,7 +6,7 @@ namespace Extensions.Tests; -public class FakeClockConventionTests : ConventionFakeTest +public class FakeClockConventionTests(ITestOutputHelper testOutputHelper) : ConventionFakeTest(testOutputHelper) { [Fact] public void Clock_Convention_Default() @@ -32,8 +32,4 @@ public void Clock_Convention_Override() clock.GetCurrentInstant().Should().Be(Instant.FromUnixTimeSeconds(0)); clock.GetCurrentInstant().Should().Be(Instant.FromUnixTimeSeconds(0) + Duration.FromMinutes(1)); } - - public FakeClockConventionTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } } diff --git a/test/Extensions.Tests/Mapping/AutoMapperProfile.cs b/test/Extensions.Tests/Mapping/AutoMapperProfile.cs index 36261d505..b4a8ae9f8 100644 --- a/test/Extensions.Tests/Mapping/AutoMapperProfile.cs +++ b/test/Extensions.Tests/Mapping/AutoMapperProfile.cs @@ -48,12 +48,8 @@ private class ChildDto [UsedImplicitly] public decimal? NullableDecimal { get; set; } } - public class OnlyDefinedPropertiesTests : AutoFakeTest + public class OnlyDefinedPropertiesTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper) { - public OnlyDefinedPropertiesTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - [Fact] public void ConfigurationIsValid() { diff --git a/test/Extensions.Tests/Mapping/DurationTests.cs b/test/Extensions.Tests/Mapping/DurationTests.cs index 35507830c..7d9bba7f9 100644 --- a/test/Extensions.Tests/Mapping/DurationTests.cs +++ b/test/Extensions.Tests/Mapping/DurationTests.cs @@ -6,12 +6,8 @@ namespace Extensions.Tests.Mapping; -public class DurationTests : TypeConverterTest +public class DurationTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public DurationTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/InstantTests.cs b/test/Extensions.Tests/Mapping/InstantTests.cs index 66f1ec991..d52af5c47 100644 --- a/test/Extensions.Tests/Mapping/InstantTests.cs +++ b/test/Extensions.Tests/Mapping/InstantTests.cs @@ -4,12 +4,8 @@ namespace Extensions.Tests.Mapping; -public class InstantTests : TypeConverterTest +public class InstantTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public InstantTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/JTokenConverterTests.cs b/test/Extensions.Tests/Mapping/JTokenConverterTests.cs index 4c7caa570..1577de121 100644 --- a/test/Extensions.Tests/Mapping/JTokenConverterTests.cs +++ b/test/Extensions.Tests/Mapping/JTokenConverterTests.cs @@ -5,12 +5,8 @@ namespace Extensions.Tests.Mapping; -public class JTokenConverterTests : TypeConverterTest +public class JTokenConverterTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public JTokenConverterTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ShouldMap_StringValue_To_JObject() { diff --git a/test/Extensions.Tests/Mapping/JsonElementConverterTests.cs b/test/Extensions.Tests/Mapping/JsonElementConverterTests.cs index 5426cc7ec..24a655c42 100644 --- a/test/Extensions.Tests/Mapping/JsonElementConverterTests.cs +++ b/test/Extensions.Tests/Mapping/JsonElementConverterTests.cs @@ -5,12 +5,8 @@ namespace Extensions.Tests.Mapping; -public class JsonElementConverterTests : TypeConverterTest +public class JsonElementConverterTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public JsonElementConverterTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ShouldMap_StringValue_To_JsonElement_From_Null() { diff --git a/test/Extensions.Tests/Mapping/LocalDateTests.cs b/test/Extensions.Tests/Mapping/LocalDateTests.cs index b00c725ae..3493fbf0a 100644 --- a/test/Extensions.Tests/Mapping/LocalDateTests.cs +++ b/test/Extensions.Tests/Mapping/LocalDateTests.cs @@ -4,12 +4,8 @@ namespace Extensions.Tests.Mapping; -public class LocalDateTests : TypeConverterTest +public class LocalDateTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public LocalDateTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs b/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs index b4189f9d1..b07637d8d 100644 --- a/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs +++ b/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs @@ -6,12 +6,8 @@ namespace Extensions.Tests.Mapping; -public class LocalDateTimeTests : TypeConverterTest +public class LocalDateTimeTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public LocalDateTimeTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/LocalTimeTests.cs b/test/Extensions.Tests/Mapping/LocalTimeTests.cs index 28779ded5..a9cf28dc6 100644 --- a/test/Extensions.Tests/Mapping/LocalTimeTests.cs +++ b/test/Extensions.Tests/Mapping/LocalTimeTests.cs @@ -7,12 +7,8 @@ namespace Extensions.Tests.Mapping; -public class LocalTimeTests : TypeConverterTest +public class LocalTimeTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public LocalTimeTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs b/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs index 2490a4ae0..439155e21 100644 --- a/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs +++ b/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs @@ -4,12 +4,8 @@ namespace Extensions.Tests.Mapping; -public class OffsetDateTimeTests : TypeConverterTest +public class OffsetDateTimeTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public OffsetDateTimeTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/OffsetTests.cs b/test/Extensions.Tests/Mapping/OffsetTests.cs index 7e63cd6e6..8f33dfdc7 100644 --- a/test/Extensions.Tests/Mapping/OffsetTests.cs +++ b/test/Extensions.Tests/Mapping/OffsetTests.cs @@ -3,12 +3,8 @@ namespace Extensions.Tests.Mapping; -public class OffsetTests : TypeConverterTest +public class OffsetTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public OffsetTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/PeriodTests.cs b/test/Extensions.Tests/Mapping/PeriodTests.cs index f59d2a70a..dde22ef02 100644 --- a/test/Extensions.Tests/Mapping/PeriodTests.cs +++ b/test/Extensions.Tests/Mapping/PeriodTests.cs @@ -4,12 +4,8 @@ namespace Extensions.Tests.Mapping; -public class PeriodTests : TypeConverterTest +public class PeriodTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public PeriodTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/SystemTextJsonTests.cs b/test/Extensions.Tests/Mapping/SystemTextJsonTests.cs index 93eed275b..b5b6e273d 100644 --- a/test/Extensions.Tests/Mapping/SystemTextJsonTests.cs +++ b/test/Extensions.Tests/Mapping/SystemTextJsonTests.cs @@ -5,12 +5,8 @@ namespace Extensions.Tests.Mapping; -public class SystemTextJsonWithNewtonsoftJsonTests : TypeConverterTest +public class SystemTextJsonWithNewtonsoftJsonTests(ITestOutputHelper testOutputHelper) : TypeConverterTest(testOutputHelper) { - public SystemTextJsonWithNewtonsoftJsonTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - [Fact] public void ValidateMapping() { diff --git a/test/Extensions.Tests/Mapping/TypeConverterTest.cs b/test/Extensions.Tests/Mapping/TypeConverterTest.cs index 5026f2369..1eb8fc75e 100644 --- a/test/Extensions.Tests/Mapping/TypeConverterTest.cs +++ b/test/Extensions.Tests/Mapping/TypeConverterTest.cs @@ -14,13 +14,8 @@ public abstract class TypeConverterFactory public abstract IEnumerable GetTypeConverters(); } -internal class TypeConverterData : TypeConverterData - where T : TypeConverterFactory, new() -{ - public TypeConverterData() : base(new T().GetTypeConverters) - { - } -} +internal class TypeConverterData() : TypeConverterData(new T().GetTypeConverters) + where T : TypeConverterFactory, new(); internal abstract class TypeConverterData : TheoryData { diff --git a/test/Extensions.Tests/MediatRTests.cs b/test/Extensions.Tests/MediatRTests.cs index c1f30f386..5e94fb707 100644 --- a/test/Extensions.Tests/MediatRTests.cs +++ b/test/Extensions.Tests/MediatRTests.cs @@ -11,12 +11,14 @@ namespace Extensions.Tests; -public class MediatRTests : AutoFakeTest +public class MediatRTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper) { [Fact] public async Task Test1() { - var builder = new ConventionContextBuilder(new Dictionary()) +#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. + var builder = new ConventionContextBuilder(new Dictionary()) +#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. .UseAssemblies(new TestAssemblyProvider().GetAssemblies()); var context = ConventionContext.From(builder); var services = new ServiceCollection(); @@ -31,7 +33,7 @@ public async Task Test1() var r = services.BuildServiceProvider(); var mediator = r.GetRequiredService(); - await mediator.Send(new Request()).ConfigureAwait(false); + await mediator.Send(new Request()); A.CallTo(() => sub.Handle(A._, A>._, A._)) .MustHaveHappenedOnceExactly(); @@ -40,7 +42,9 @@ public async Task Test1() [Fact] public async Task Test2() { - var builder = new ConventionContextBuilder(new Dictionary()) +#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. + var builder = new ConventionContextBuilder(new Dictionary()) +#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. .UseAssemblies(new TestAssemblyProvider().GetAssemblies()); var context = ConventionContext.From(builder); var services = new ServiceCollection(); @@ -63,16 +67,12 @@ public async Task Test2() var mediator = r.GetRequiredService(); - await mediator.Send(new Request()).ConfigureAwait(false); + await mediator.Send(new Request()); A.CallTo(() => sub.Handle(A._, A>._, A._)) .MustHaveHappenedOnceExactly(); } - public MediatRTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - private class TestAssemblyProvider : IAssemblyProvider { public IEnumerable GetAssemblies() @@ -97,9 +97,7 @@ public IEnumerable GetCandidateAssemblies(IEnumerable candidat } } - public class Request : IRequest - { - } + public class Request : IRequest; private class TestHandler : IRequestHandler { diff --git a/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteGeoJsonTests.cs b/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteGeoJsonTests.cs index e6dc9ac87..2d2bd173b 100644 --- a/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteGeoJsonTests.cs +++ b/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteGeoJsonTests.cs @@ -6,14 +6,9 @@ namespace Extensions.Tests; -public class NewtonsoftJsonNetTopologySuiteGeoJsonTests : LoggerTest +public class NewtonsoftJsonNetTopologySuiteGeoJsonTests(ITestOutputHelper outputHelper) : LoggerTest(outputHelper) { - private readonly JsonSerializerSettings _settings; - - public NewtonsoftJsonNetTopologySuiteGeoJsonTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - _settings = new JsonSerializerSettings().ConfigureGeoJsonForLaunchPad(null); - } + private readonly JsonSerializerSettings _settings = new JsonSerializerSettings().ConfigureGeoJsonForLaunchPad(null); // typeof(Geometry), // typeof(MultiPoint), diff --git a/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteWellKnownTextTests.cs b/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteWellKnownTextTests.cs index 456ce813c..8a42a267f 100644 --- a/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteWellKnownTextTests.cs +++ b/test/Extensions.Tests/NewtonsoftJsonNetTopologySuiteWellKnownTextTests.cs @@ -6,7 +6,7 @@ namespace Extensions.Tests; -public class NewtonsoftJsonNetTopologySuiteWellKnownTextTests : LoggerTest +public class NewtonsoftJsonNetTopologySuiteWellKnownTextTests(ITestOutputHelper outputHelper) : LoggerTest(outputHelper) { private static T DeserializeObject(string geom, JsonSerializerSettings settings) { @@ -18,12 +18,7 @@ private static string SerializeObject(T geom, JsonSerializerSettings settings return JsonConvert.SerializeObject(geom, settings).Trim('"'); } - private readonly JsonSerializerSettings _settings; - - public NewtonsoftJsonNetTopologySuiteWellKnownTextTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - _settings = new JsonSerializerSettings().ConfigureWellKnownTextForLaunchPad(null); - } + private readonly JsonSerializerSettings _settings = new JsonSerializerSettings().ConfigureWellKnownTextForLaunchPad(null); // typeof(Geometry), // typeof(MultiPoint), @@ -129,6 +124,6 @@ public void GeometryCollection_Tests(string geom) public class ValueOf { - public T Value { get; set; } + public T Value { get; set; } = default!; } } diff --git a/test/Extensions.Tests/NewtonsoftJsonNodaTimeTests.cs b/test/Extensions.Tests/NewtonsoftJsonNodaTimeTests.cs index 7d2682554..5673629eb 100644 --- a/test/Extensions.Tests/NewtonsoftJsonNodaTimeTests.cs +++ b/test/Extensions.Tests/NewtonsoftJsonNodaTimeTests.cs @@ -5,15 +5,10 @@ namespace Extensions.Tests; -public class NewtonsoftJsonNodaTimeTests : LoggerTest +public class NewtonsoftJsonNodaTimeTests(ITestOutputHelper outputHelper) : LoggerTest(outputHelper) { - private JsonSerializerSettings _settings; - - public NewtonsoftJsonNodaTimeTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - _settings = new JsonSerializerSettings() - .ConfigureNodaTimeForLaunchPad(DateTimeZoneProviders.Tzdb); - } + private JsonSerializerSettings _settings = new JsonSerializerSettings() + .ConfigureNodaTimeForLaunchPad(DateTimeZoneProviders.Tzdb); [Theory] [InlineData("2020-01-01T12:12:12Z")] diff --git a/test/Extensions.Tests/StringInValidatorTests.cs b/test/Extensions.Tests/StringInValidatorTests.cs index 9647e27de..006c6a56f 100644 --- a/test/Extensions.Tests/StringInValidatorTests.cs +++ b/test/Extensions.Tests/StringInValidatorTests.cs @@ -3,7 +3,7 @@ namespace Extensions.Tests; -public class StringInValidatorTests : ConventionFakeTest +public class StringInValidatorTests(ITestOutputHelper testOutputHelper) : ConventionFakeTest(testOutputHelper) { [Fact] public async Task Should_Validate_Invalid() @@ -18,7 +18,10 @@ public async Task Should_Validate_Invalid() var validator = ServiceProvider.GetRequiredService>(); var result = await validator.ValidateAsync(data); +#pragma warning disable CA1849 + // ReSharper disable once MethodHasAsyncOverload var result2 = validator.Validate(data); +#pragma warning restore CA1849 result.Should().BeEquivalentTo(result2); result.IsValid.Should().BeFalse(); @@ -39,7 +42,10 @@ public async Task Should_Validate_CaseSensitive() var validator = ServiceProvider.GetRequiredService>(); var result = await validator.ValidateAsync(data); +#pragma warning disable CA1849 + // ReSharper disable once MethodHasAsyncOverload var result2 = validator.Validate(data); +#pragma warning restore CA1849 result.Should().BeEquivalentTo(result2); result.IsValid.Should().BeFalse(); @@ -59,17 +65,16 @@ public async Task Should_Validate_CaseInsensitive() var validator = ServiceProvider.GetRequiredService>(); var result = await validator.ValidateAsync(data); +#pragma warning disable CA1849 + // ReSharper disable once MethodHasAsyncOverload var result2 = validator.Validate(data); +#pragma warning restore CA1849 result.Should().BeEquivalentTo(result2); result.IsValid.Should().BeFalse(); result.Errors.Should().Contain(z => z.PropertyName == nameof(Target.TypeIgnoreCase)); } - public StringInValidatorTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } - private class Target { [UsedImplicitly] public string Type { get; set; } = null!; diff --git a/test/Extensions.Tests/SystemTextJsonNetTopologySuiteGeoJsonTests.cs b/test/Extensions.Tests/SystemTextJsonNetTopologySuiteGeoJsonTests.cs index 8caa2db38..a01dda36f 100644 --- a/test/Extensions.Tests/SystemTextJsonNetTopologySuiteGeoJsonTests.cs +++ b/test/Extensions.Tests/SystemTextJsonNetTopologySuiteGeoJsonTests.cs @@ -6,14 +6,9 @@ namespace Extensions.Tests; -public class SystemTextJsonNetTopologySuiteGeoJsonTests : LoggerTest +public class SystemTextJsonNetTopologySuiteGeoJsonTests(ITestOutputHelper outputHelper) : LoggerTest(outputHelper) { - private readonly JsonSerializerOptions _settings; - - public SystemTextJsonNetTopologySuiteGeoJsonTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - _settings = new JsonSerializerOptions().ConfigureGeoJsonForLaunchPad(null); - } + private readonly JsonSerializerOptions _settings = new JsonSerializerOptions().ConfigureGeoJsonForLaunchPad(null); // typeof(Geometry), // typeof(MultiPoint), diff --git a/test/Extensions.Tests/SystemTextJsonNetTopologySuiteWellKnownTextTests.cs b/test/Extensions.Tests/SystemTextJsonNetTopologySuiteWellKnownTextTests.cs index 2166bbc58..13aba10e9 100644 --- a/test/Extensions.Tests/SystemTextJsonNetTopologySuiteWellKnownTextTests.cs +++ b/test/Extensions.Tests/SystemTextJsonNetTopologySuiteWellKnownTextTests.cs @@ -1,5 +1,4 @@ using System.Text.Json; -using System.Text.Json.Serialization; using FluentAssertions.Primitives; using NetTopologySuite.Geometries; using Rocket.Surgery.Extensions.Testing; @@ -7,11 +6,11 @@ namespace Extensions.Tests; -public class SystemTextJsonNetTopologySuiteWellKnownTextTests : LoggerTest +public class SystemTextJsonNetTopologySuiteWellKnownTextTests(ITestOutputHelper outputHelper) : LoggerTest(outputHelper) { private static T DeserializeObject(string geom, JsonSerializerOptions settings) { - return JsonSerializer.Deserialize("\"" + geom + "\"", settings); + return JsonSerializer.Deserialize("\"" + geom + "\"", settings)!; } private static string SerializeObject(object geom, JsonSerializerOptions settings) @@ -19,12 +18,7 @@ private static string SerializeObject(object geom, JsonSerializerOptions setting return JsonSerializer.Serialize(geom, settings).Trim('"'); } - private readonly JsonSerializerOptions _settings; - - public SystemTextJsonNetTopologySuiteWellKnownTextTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - _settings = new JsonSerializerOptions().ConfigureWellKnownTextForLaunchPad(null); - } + private readonly JsonSerializerOptions _settings = new JsonSerializerOptions().ConfigureWellKnownTextForLaunchPad(null); // typeof(Geometry), // typeof(MultiPoint), @@ -136,6 +130,6 @@ public void GeometryCollection_Tests(string geom) public class ValueOf { - public T Value { get; set; } + public T Value { get; set; } = default!; } } diff --git a/test/Extensions.Tests/SystemTextJsonNodaTimeTests.cs b/test/Extensions.Tests/SystemTextJsonNodaTimeTests.cs index 9d87348ec..c3483b8e2 100644 --- a/test/Extensions.Tests/SystemTextJsonNodaTimeTests.cs +++ b/test/Extensions.Tests/SystemTextJsonNodaTimeTests.cs @@ -5,14 +5,9 @@ namespace Extensions.Tests; -public class SystemTextJsonNodaTimeTests : LoggerTest +public class SystemTextJsonNodaTimeTests(ITestOutputHelper outputHelper) : LoggerTest(outputHelper) { - private JsonSerializerOptions _settings; - - public SystemTextJsonNodaTimeTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - _settings = new JsonSerializerOptions().ConfigureNodaTimeForLaunchPad(DateTimeZoneProviders.Tzdb); - } + private JsonSerializerOptions _settings = new JsonSerializerOptions().ConfigureNodaTimeForLaunchPad(DateTimeZoneProviders.Tzdb); [Theory] [InlineData("2020-01-01T12:12:12Z")] diff --git a/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs b/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs index 40d70b9b3..8261c0b6e 100644 --- a/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs +++ b/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs @@ -1,6 +1,5 @@ #if NET6_0_OR_GREATER using DryIoc; -using FakeItEasy.Creation; using FluentValidation; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyModel; @@ -10,18 +9,17 @@ using Rocket.Surgery.Extensions.Testing; using Rocket.Surgery.LaunchPad.Foundation; using Rocket.Surgery.LaunchPad.Foundation.Validation; -using Serilog; namespace Extensions.Tests.Validation; [UsesVerify] -public class HealthCheckOptionsValidationTests : AutoFakeTest, IAsyncLifetime +public class HealthCheckOptionsValidationTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper), IAsyncLifetime { [Fact] public async Task Should_Validate_Options_And_Throw() { var a = () => Container.Resolve>().Value; - var failures = a.Should().NotThrow(); + a.Should().NotThrow(); await Verify(Container.Resolve().Results); } @@ -40,7 +38,7 @@ public async Task Should_Validate_Options_And_Pass() ); Populate(services); var a = () => Container.Resolve>().Value; - var failures = a.Should().NotThrow(); + a.Should().NotThrow(); await Verify(Container.Resolve().Results); } @@ -59,7 +57,7 @@ public async Task Should_Validate_Options_And_Throw_If_Out_Of_Bounds() ); Populate(services); var a = () => Container.Resolve>().Value; - var failures = a.Should().NotThrow(); + a.Should().NotThrow(); await Verify(Container.Resolve().Results); } @@ -74,7 +72,7 @@ public async Task Should_Validate_Options_And_Throw_After_Application_Has_Starte } [Fact] - public async Task Should_Validate_Options_And_Pass_After_Application_Has_Started() + public void Should_Validate_Options_And_Pass_After_Application_Has_Started() { Container.Resolve().ApplicationHasStarted = true; var services = new ServiceCollection(); @@ -89,7 +87,7 @@ public async Task Should_Validate_Options_And_Pass_After_Application_Has_Started ); Populate(services); var a = () => Container.Resolve>().Value; - var failures = a.Should().NotThrow(); + a.Should().NotThrow(); } [Fact] @@ -113,18 +111,15 @@ public async Task Should_Validate_Options_And_Throw_If_Out_Of_Bounds_After_Appli await Verify(failures); } - public HealthCheckOptionsValidationTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - private class Options { - public string String { get; set; } + public string? String { get; set; } public int Int { get; set; } public bool Bool { get; set; } public double Double { get; set; } - private class Validator : AbstractValidator + [UsedImplicitly] + private sealed class Validator : AbstractValidator { public Validator() { @@ -139,7 +134,7 @@ public Validator() public Task InitializeAsync() { var conventionContextBuilder = ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly), LoggerFactory) + .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) .Set( new FoundationOptions { diff --git a/test/Extensions.Tests/Validation/OptionsValidationTests.cs b/test/Extensions.Tests/Validation/OptionsValidationTests.cs index 766ec7ea7..39ad8bdf9 100644 --- a/test/Extensions.Tests/Validation/OptionsValidationTests.cs +++ b/test/Extensions.Tests/Validation/OptionsValidationTests.cs @@ -1,6 +1,5 @@ #if NET6_0_OR_GREATER using DryIoc; -using FakeItEasy.Creation; using FluentValidation; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyModel; @@ -9,12 +8,11 @@ using Rocket.Surgery.Conventions.Testing; using Rocket.Surgery.Extensions.Testing; using Rocket.Surgery.LaunchPad.Foundation; -using Serilog; namespace Extensions.Tests.Validation; [UsesVerify] -public class OptionsValidationTests : AutoFakeTest, IAsyncLifetime +public class OptionsValidationTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper), IAsyncLifetime { [Fact] public async Task Should_Validate_Options_And_Throw() @@ -26,7 +24,7 @@ public async Task Should_Validate_Options_And_Throw() } [Fact] - public async Task Should_Validate_Options_And_Pass() + public void Should_Validate_Options_And_Pass() { var services = new ServiceCollection(); services.AddOptions().Configure( @@ -40,7 +38,7 @@ public async Task Should_Validate_Options_And_Pass() ); Populate(services); var a = () => Container.Resolve>().Value; - var failures = a.Should().NotThrow(); + a.Should().NotThrow(); } [Fact] @@ -63,17 +61,14 @@ public async Task Should_Validate_Options_And_Throw_If_Out_Of_Bounds() await Verify(failures); } - public OptionsValidationTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - private class Options { - public string String { get; set; } + public string? String { get; set; } public int Int { get; set; } public bool Bool { get; set; } public double Double { get; set; } + [UsedImplicitly] private class Validator : AbstractValidator { public Validator() @@ -89,7 +84,7 @@ public Validator() public Task InitializeAsync() { var conventionContextBuilder = ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly), LoggerFactory) + .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) .Set( new FoundationOptions { diff --git a/test/Extensions.Tests/Validation/ValidatorFactoryTests.cs b/test/Extensions.Tests/Validation/ValidatorFactoryTests.cs index b2e74759a..b8b1eef1d 100644 --- a/test/Extensions.Tests/Validation/ValidatorFactoryTests.cs +++ b/test/Extensions.Tests/Validation/ValidatorFactoryTests.cs @@ -4,7 +4,7 @@ namespace Extensions.Tests.Validation; -public class ValidatorFactoryTests : AutoFakeTest +public class ValidatorFactoryTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper, LogLevel.Information) { // [Fact] // public void Should_Aggregate_Validators() @@ -20,11 +20,7 @@ public class ValidatorFactoryTests : AutoFakeTest // result.Errors.Should().HaveCount(2); // } - public ValidatorFactoryTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Information) - { - } - - public interface IThing +public interface IThing { public string? Thing { get; set; } } diff --git a/test/Functions.Tests/RocketHostBuilderTests.cs b/test/Functions.Tests/RocketHostBuilderTests.cs index 6c0f1570f..a1e6c1960 100644 --- a/test/Functions.Tests/RocketHostBuilderTests.cs +++ b/test/Functions.Tests/RocketHostBuilderTests.cs @@ -9,7 +9,7 @@ namespace Functions.Tests; -internal class Startup : LaunchPadFunctionStartup, IServiceConvention +internal sealed class Startup : LaunchPadFunctionStartup, IServiceConvention { public Startup() { @@ -29,7 +29,7 @@ public void Register(IConventionContext context, IConfiguration configuration, I } } -public class RocketHostBuilderTests : AutoFakeTest +public class RocketHostBuilderTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper) { [Fact] public void Should_UseAssemblies() @@ -76,10 +76,6 @@ public void Should_Build_The_Host_Correctly() sp.Should().NotBeNull(); } - public RocketHostBuilderTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } - private static IFunctionsConfigurationBuilder ConfigureConfiguration(IConfigurationBuilder configurationBuilder) { var functionsConfigurationBuilder = A.Fake(); diff --git a/test/Functions.Tests/TestAssemblyProvider.cs b/test/Functions.Tests/TestAssemblyProvider.cs index 535bcc69e..b2f178752 100644 --- a/test/Functions.Tests/TestAssemblyProvider.cs +++ b/test/Functions.Tests/TestAssemblyProvider.cs @@ -4,7 +4,7 @@ namespace Functions.Tests; -internal class TestAssemblyProvider : IAssemblyProvider +internal sealed class TestAssemblyProvider : IAssemblyProvider { public IEnumerable GetAssemblies() { diff --git a/test/Metadata.Tests/GitVersionTests.cs b/test/Metadata.Tests/GitVersionTests.cs index e646aa24c..09b3724c6 100644 --- a/test/Metadata.Tests/GitVersionTests.cs +++ b/test/Metadata.Tests/GitVersionTests.cs @@ -4,7 +4,7 @@ namespace Metadata.Tests; -public class GitVersionTests : AutoFakeTest +public class GitVersionTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper) { [Fact(Skip = "Disabled for CI")] public void ReturnsInformationForVersionedAssembly() @@ -102,8 +102,4 @@ public void ForManyAssembliesAndReduceEnumerable() version.Should().NotBeNull(); version.Should().HaveCount(1); } - - public GitVersionTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } } diff --git a/test/Sample.BlazorServer.Tests/FoundationTests.cs b/test/Sample.BlazorServer.Tests/FoundationTests.cs index 2f60f5a02..9316ca142 100644 --- a/test/Sample.BlazorServer.Tests/FoundationTests.cs +++ b/test/Sample.BlazorServer.Tests/FoundationTests.cs @@ -1,13 +1,11 @@ using System.Net; using AutoMapper; using Microsoft.Extensions.DependencyInjection; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.BlazorServer.Tests.Helpers; namespace Sample.BlazorServer.Tests; -public class FoundationTests : WebAppFixtureTest +public class FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : WebAppFixtureTest(testOutputHelper, factory) { [Fact] public void AutoMapper() @@ -22,8 +20,4 @@ public async Task Starts() var response = await AlbaHost.Server.CreateClient().GetAsync("/"); response.StatusCode.Should().Be(HttpStatusCode.OK); } - - public FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : base(testOutputHelper, factory) - { - } } diff --git a/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs b/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs index f089c9799..9ea895f6f 100644 --- a/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs @@ -9,12 +9,7 @@ namespace Sample.BlazorServer.Tests.Helpers; public sealed class SqliteExtension : IResettableAlbaExtension where TDbContext : DbContext { - private readonly SqliteConnection _connection; - - public SqliteExtension() - { - _connection = new SqliteConnection("DataSource=:memory:"); - } + private readonly SqliteConnection _connection = new("DataSource=:memory:"); public void Reset(IServiceProvider serviceProvider) { diff --git a/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs index 4e5ccfc29..8fe8ca992 100644 --- a/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs @@ -3,9 +3,4 @@ namespace Sample.BlazorServer.Tests.Helpers; -public class TestWebAppFixture : LaunchPadWebAppFixture, IAsyncLifetime -{ - public TestWebAppFixture() : base(new SqliteExtension()) - { - } -} +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; diff --git a/test/Sample.BlazorWasm.Tests/FoundationTests.cs b/test/Sample.BlazorWasm.Tests/FoundationTests.cs index d714eae36..018b314eb 100644 --- a/test/Sample.BlazorWasm.Tests/FoundationTests.cs +++ b/test/Sample.BlazorWasm.Tests/FoundationTests.cs @@ -3,7 +3,7 @@ namespace Sample.BlazorWasm.Tests; -public class FoundationTests : HandleTestHostBase +public class FoundationTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper) { [Fact] public void AutoMapper() @@ -11,8 +11,4 @@ public void AutoMapper() ServiceProvider.GetRequiredService() .ConfigurationProvider.AssertConfigurationIsValid(); } - - public FoundationTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } } diff --git a/test/Sample.Classic.Restful.Tests/ApiDescriptionData.cs b/test/Sample.Classic.Restful.Tests/ApiDescriptionData.cs index 6cbc1fe23..1b4f17e96 100644 --- a/test/Sample.Classic.Restful.Tests/ApiDescriptionData.cs +++ b/test/Sample.Classic.Restful.Tests/ApiDescriptionData.cs @@ -1,11 +1,10 @@ using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Classic.Restful.Tests; -internal class ApiDescriptionData : TheoryData +internal sealed class ApiDescriptionData : TheoryData where T : class, ILaunchPadWebAppFixture, IAsyncLifetime, new() { public ApiDescriptionData() @@ -20,14 +19,9 @@ public ApiDescriptionData() } } -public class ApiDescriptionData +public sealed class ApiDescriptionData(ApiDescription description) { - public ApiDescriptionData(ApiDescription description) - { - Description = description; - } - - public ApiDescription Description { get; } + public ApiDescription Description { get; } = description; public override string ToString() { diff --git a/test/Sample.Classic.Restful.Tests/ClassicFoundationTests.cs b/test/Sample.Classic.Restful.Tests/ClassicFoundationTests.cs index df7125857..d74884941 100644 --- a/test/Sample.Classic.Restful.Tests/ClassicFoundationTests.cs +++ b/test/Sample.Classic.Restful.Tests/ClassicFoundationTests.cs @@ -2,20 +2,15 @@ using AutoMapper; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Classic.Restful.Tests.Helpers; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; namespace Sample.Classic.Restful.Tests; -public class ClassicFoundationTests : WebAppFixtureTest +public class ClassicFoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture fixture) + : WebAppFixtureTest(testOutputHelper, fixture) { - public ClassicFoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture fixture) : base(testOutputHelper, fixture) - { - } - [Fact] public void AutoMapper() { diff --git a/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs index 4945a087f..ebadef84d 100644 --- a/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs @@ -3,10 +3,4 @@ namespace Sample.Classic.Restful.Tests.Helpers; -public class TestWebAppFixture : LaunchPadWebAppFixture, IAsyncLifetime -{ - - public TestWebAppFixture() : base(new SqliteExtension()) - { - } -} +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; diff --git a/test/Sample.Core.Tests/FoundationTests.cs b/test/Sample.Core.Tests/FoundationTests.cs index ddb9b288a..af266025b 100644 --- a/test/Sample.Core.Tests/FoundationTests.cs +++ b/test/Sample.Core.Tests/FoundationTests.cs @@ -3,7 +3,7 @@ namespace Sample.Core.Tests; -public class FoundationTests : HandleTestHostBase +public class FoundationTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper) { [Fact] public void AutoMapper() @@ -11,8 +11,4 @@ public void AutoMapper() ServiceProvider.GetRequiredService() .ConfigurationProvider.AssertConfigurationIsValid(); } - - public FoundationTests(ITestOutputHelper outputHelper) : base(outputHelper) - { - } } diff --git a/test/Sample.Core.Tests/HandleTestHostBase.cs b/test/Sample.Core.Tests/HandleTestHostBase.cs index b35123d3f..b3e9c738d 100644 --- a/test/Sample.Core.Tests/HandleTestHostBase.cs +++ b/test/Sample.Core.Tests/HandleTestHostBase.cs @@ -24,7 +24,7 @@ protected HandleTestHostBase(ITestOutputHelper outputHelper, LogLevel logLevel = { _context = ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly), LoggerFactory) + .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) .WithLogger(LoggerFactory.CreateLogger(nameof(AutoFakeTest))); ExcludeSourceContext(nameof(AutoFakeTest)); } diff --git a/test/Sample.Core.Tests/LaunchRecords/CreateLaunchRecordTests.cs b/test/Sample.Core.Tests/LaunchRecords/CreateLaunchRecordTests.cs index 3904607e4..b9e978766 100644 --- a/test/Sample.Core.Tests/LaunchRecords/CreateLaunchRecordTests.cs +++ b/test/Sample.Core.Tests/LaunchRecords/CreateLaunchRecordTests.cs @@ -7,7 +7,7 @@ namespace Sample.Core.Tests.LaunchRecords; -public class CreateLaunchRecordTests : HandleTestHostBase +public class CreateLaunchRecordTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Create_A_LaunchRecord() @@ -45,9 +45,5 @@ public async Task Should_Create_A_LaunchRecord() response.Id.Value.Should().NotBeEmpty(); } - public CreateLaunchRecordTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/LaunchRecords/GetLaunchRecordTests.cs b/test/Sample.Core.Tests/LaunchRecords/GetLaunchRecordTests.cs index 87311bff1..8fb2ed0f0 100644 --- a/test/Sample.Core.Tests/LaunchRecords/GetLaunchRecordTests.cs +++ b/test/Sample.Core.Tests/LaunchRecords/GetLaunchRecordTests.cs @@ -9,7 +9,7 @@ namespace Sample.Core.Tests.LaunchRecords; -public class GetLaunchRecordTests : HandleTestHostBase +public class GetLaunchRecordTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Get_A_LaunchRecord() @@ -62,9 +62,5 @@ public async Task Should_Not_Get_A_Missing_Launch_Record() await action.Should().ThrowAsync(); } - public GetLaunchRecordTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/LaunchRecords/ListLaunchRecordsTests.cs b/test/Sample.Core.Tests/LaunchRecords/ListLaunchRecordsTests.cs index e249f8b60..17e4410cd 100644 --- a/test/Sample.Core.Tests/LaunchRecords/ListLaunchRecordsTests.cs +++ b/test/Sample.Core.Tests/LaunchRecords/ListLaunchRecordsTests.cs @@ -6,7 +6,7 @@ namespace Sample.Core.Tests.LaunchRecords; -public class ListLaunchRecordsTests : HandleTestHostBase +public class ListLaunchRecordsTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_List_LaunchRecords() @@ -31,9 +31,5 @@ await ServiceProvider.WithScoped() response.Should().HaveCount(10); } - public ListLaunchRecordsTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs b/test/Sample.Core.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs index c9629cc56..1dc6ce2ec 100644 --- a/test/Sample.Core.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs +++ b/test/Sample.Core.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs @@ -8,7 +8,7 @@ namespace Sample.Core.Tests.LaunchRecords; -public class RemoveLaunchRecordsTests : HandleTestHostBase +public class RemoveLaunchRecordsTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Remove_LaunchRecord() @@ -61,9 +61,5 @@ await ServiceProvider.WithScoped() await action.Should().ThrowAsync(); } - public RemoveLaunchRecordsTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/LaunchRecords/UpdateLaunchRecordTests.cs b/test/Sample.Core.Tests/LaunchRecords/UpdateLaunchRecordTests.cs index 755e78a87..39de39c07 100644 --- a/test/Sample.Core.Tests/LaunchRecords/UpdateLaunchRecordTests.cs +++ b/test/Sample.Core.Tests/LaunchRecords/UpdateLaunchRecordTests.cs @@ -9,7 +9,7 @@ namespace Sample.Core.Tests.LaunchRecords; -public class UpdateLaunchRecordTests : HandleTestHostBase +public class UpdateLaunchRecordTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Update_A_LaunchRecord() @@ -43,7 +43,7 @@ public async Task Should_Update_A_LaunchRecord() var launchDate = record.ScheduledLaunchDate.ToInstant().Plus(Duration.FromSeconds(1)); var response = await ServiceProvider.WithScoped().Invoke( - (mediator, clock) => mediator.Send( + (mediator, _) => mediator.Send( new EditLaunchRecord.Request { Id = record.Id, @@ -60,9 +60,5 @@ public async Task Should_Update_A_LaunchRecord() response.PayloadWeightKg.Should().Be(200); } - public UpdateLaunchRecordTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/Rockets/CreateRocketTests.cs b/test/Sample.Core.Tests/Rockets/CreateRocketTests.cs index dfbd8c93a..3015f6a13 100644 --- a/test/Sample.Core.Tests/Rockets/CreateRocketTests.cs +++ b/test/Sample.Core.Tests/Rockets/CreateRocketTests.cs @@ -9,7 +9,7 @@ namespace Sample.Core.Tests.Rockets; -public class CreateRocketTests : HandleTestHostBase +public class CreateRocketTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Create_A_Rocket() @@ -59,10 +59,6 @@ await ServiceProvider.WithScoped() .And.Title.Should().Be("Rocket Creation Failed"); } - public CreateRocketTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); [Theory] @@ -77,7 +73,7 @@ public async Task Should_Validate_Required_Fields(CreateRocket.Request request, ( await a.Should().ThrowAsync() ).And.Errors.Select(x => x.PropertyName).Should().Contain(propertyName); } - private class ShouldValidateUsersRequiredFieldData : TheoryData + private sealed class ShouldValidateUsersRequiredFieldData : TheoryData { public ShouldValidateUsersRequiredFieldData() { diff --git a/test/Sample.Core.Tests/Rockets/GetRocketTests.cs b/test/Sample.Core.Tests/Rockets/GetRocketTests.cs index 9f74ea852..0674c2ff7 100644 --- a/test/Sample.Core.Tests/Rockets/GetRocketTests.cs +++ b/test/Sample.Core.Tests/Rockets/GetRocketTests.cs @@ -8,7 +8,7 @@ namespace Sample.Core.Tests.Rockets; -public class GetRocketTests : HandleTestHostBase +public class GetRocketTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Get_A_Rocket() @@ -47,9 +47,5 @@ public async Task Should_Not_Get_A_Missing_Rocket() await action.Should().ThrowAsync(); } - public GetRocketTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/Rockets/ListRocketsTests.cs b/test/Sample.Core.Tests/Rockets/ListRocketsTests.cs index a2d0fe30a..77d6e9ebd 100644 --- a/test/Sample.Core.Tests/Rockets/ListRocketsTests.cs +++ b/test/Sample.Core.Tests/Rockets/ListRocketsTests.cs @@ -6,7 +6,7 @@ namespace Sample.Core.Tests.Rockets; -public class ListRocketsTests : HandleTestHostBase +public class ListRocketsTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_List_Rockets() @@ -29,9 +29,5 @@ await ServiceProvider.WithScoped() response.Should().HaveCount(10); } - public ListRocketsTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/Rockets/RemoveRocketsTests.cs b/test/Sample.Core.Tests/Rockets/RemoveRocketsTests.cs index 6df1b0d2c..549be9711 100644 --- a/test/Sample.Core.Tests/Rockets/RemoveRocketsTests.cs +++ b/test/Sample.Core.Tests/Rockets/RemoveRocketsTests.cs @@ -6,7 +6,7 @@ namespace Sample.Core.Tests.Rockets; -public class RemoveRocketsTests : HandleTestHostBase +public class RemoveRocketsTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Remove_Rocket() @@ -31,9 +31,5 @@ await ServiceProvider.WithScoped().Invoke( ServiceProvider.WithScoped().Invoke(c => c.Rockets.Should().BeEmpty()); } - public RemoveRocketsTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Core.Tests/Rockets/UpdateRocketTests.cs b/test/Sample.Core.Tests/Rockets/UpdateRocketTests.cs index 1eb0814d2..80f0e7719 100644 --- a/test/Sample.Core.Tests/Rockets/UpdateRocketTests.cs +++ b/test/Sample.Core.Tests/Rockets/UpdateRocketTests.cs @@ -9,7 +9,7 @@ namespace Sample.Core.Tests.Rockets; -public class UpdateRocketTests : HandleTestHostBase +public class UpdateRocketTests(ITestOutputHelper outputHelper) : HandleTestHostBase(outputHelper, LogLevel.Trace) { [Fact] public async Task Should_Update_A_Rocket() @@ -81,10 +81,6 @@ public async Task Should_Patch_A_Rocket() response.Sn.Should().Be("12345678901234"); } - public UpdateRocketTests(ITestOutputHelper outputHelper) : base(outputHelper, LogLevel.Trace) - { - } - private static readonly Faker Faker = new(); [Theory] @@ -99,7 +95,7 @@ public async Task Should_Validate_Required_Fields(EditRocket.Request request, st ( await a.Should().ThrowAsync() ).And.Errors.Select(x => x.PropertyName).Should().Contain(propertyName); } - private class ShouldValidateUsersRequiredFieldData : TheoryData + private sealed class ShouldValidateUsersRequiredFieldData : TheoryData { public ShouldValidateUsersRequiredFieldData() { diff --git a/test/Sample.Graphql.Tests/FoundationTests.cs b/test/Sample.Graphql.Tests/FoundationTests.cs index ccb463e3e..51223bd8e 100644 --- a/test/Sample.Graphql.Tests/FoundationTests.cs +++ b/test/Sample.Graphql.Tests/FoundationTests.cs @@ -3,18 +3,15 @@ using AutoMapper; using HotChocolate.Execution; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Rocket.Surgery.DependencyInjection; using Rocket.Surgery.Extensions.Testing; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; -using IRequestExecutorResolver = HotChocolate.Execution.IRequestExecutorResolver; namespace Sample.Graphql.Tests; [UsesVerify] -public class FoundationTests : LoggerTest +public class FoundationTests(ITestOutputHelper testOutputHelper) : LoggerTest(testOutputHelper) { [Fact] public async Task AutoMapper() @@ -39,8 +36,4 @@ public async Task GraphqlSchema() var exeuctor = await host.Services.GetRequestExecutorAsync(); await Verify(exeuctor.Schema.Print(), "graphql"); } - - public FoundationTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } } diff --git a/test/Sample.Graphql.Tests/Helpers/GraphQlAppFixture.cs b/test/Sample.Graphql.Tests/Helpers/GraphQlAppFixture.cs index 55ff00733..442714c5a 100644 --- a/test/Sample.Graphql.Tests/Helpers/GraphQlAppFixture.cs +++ b/test/Sample.Graphql.Tests/Helpers/GraphQlAppFixture.cs @@ -3,9 +3,4 @@ namespace Sample.Graphql.Tests.Helpers; -public class GraphQlAppFixture : LaunchPadWebAppFixture, IAsyncLifetime -{ - public GraphQlAppFixture() : base(new SqliteExtension(), new GraphQlExtension()) - { - } -} +public class GraphQlAppFixture() : LaunchPadWebAppFixture(new SqliteExtension(), new GraphQlExtension()), IAsyncLifetime; diff --git a/test/Sample.Graphql.Tests/Helpers/GraphQlExtension.cs b/test/Sample.Graphql.Tests/Helpers/GraphQlExtension.cs index 2cbc681d5..f197df64d 100644 --- a/test/Sample.Graphql.Tests/Helpers/GraphQlExtension.cs +++ b/test/Sample.Graphql.Tests/Helpers/GraphQlExtension.cs @@ -1,7 +1,6 @@ using Alba; using HotChocolate; using HotChocolate.AspNetCore.Instrumentation; -using HotChocolate.Execution.Instrumentation; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; @@ -33,8 +32,8 @@ public IHostBuilder Configure(IHostBuilder builder) new TemporaryGraphQlExtension().Configure(builder); builder.ConfigureServices( z => z - .AddW3CLogging(z => { }) - .AddHttpLogging(z => { }) + .AddW3CLogging(_ => { }) + .AddHttpLogging(_ => { }) .AddGraphQL() .AddDiagnosticEventListener() .ModifyRequestOptions( @@ -53,44 +52,30 @@ public IHostBuilder Configure(IHostBuilder builder) return builder; } - public class CO : PostConfigureOptions + public class CO(TestServer testServer) : PostConfigureOptions(Options.DefaultName, null) { - private readonly TestServer _testServer; - - public CO(TestServer testServer) : base(Options.DefaultName, null) - { - _testServer = testServer; - } - - public override void PostConfigure(string name, HttpClientFactoryOptions options) + public override void PostConfigure(string? name, HttpClientFactoryOptions options) { options.HttpMessageHandlerBuilderActions.Add( - builder => builder.PrimaryHandler = _testServer.CreateHandler() + builder => builder.PrimaryHandler = testServer.CreateHandler() ); options.HttpClientActions.Add( - client => client.BaseAddress = new Uri(_testServer.BaseAddress + "graphql/") + client => client.BaseAddress = new Uri(testServer.BaseAddress + "graphql/") ); } } } -public class TestServerDiagnosticEventListener : ServerDiagnosticEventListener +public class TestServerDiagnosticEventListener(ILogger logger) : ServerDiagnosticEventListener { - private readonly ILogger _logger; - - public TestServerDiagnosticEventListener(ILogger logger) - { - _logger = logger; - } - public override void HttpRequestError(HttpContext context, Exception exception) { - _logger.LogError(exception, "HttpRequestError"); + logger.LogError(exception, "HttpRequestError"); } public override void HttpRequestError(HttpContext context, IError error) { - _logger.LogError(error.Exception, "HttpRequestError"); + logger.LogError(error.Exception, "HttpRequestError"); } } diff --git a/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs b/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs index 97816b26d..a532658cf 100644 --- a/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs @@ -1,13 +1,9 @@ using Alba; -using Microsoft.AspNetCore.TestHost; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Http; -using Microsoft.Extensions.Options; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; -using Sample.Core.Domain; namespace Sample.Graphql.Tests.Helpers; diff --git a/test/Sample.Graphql.Tests/Helpers/TemporaryGraphQlExtension.cs b/test/Sample.Graphql.Tests/Helpers/TemporaryGraphQlExtension.cs index 8cc294084..9d5472e30 100644 --- a/test/Sample.Graphql.Tests/Helpers/TemporaryGraphQlExtension.cs +++ b/test/Sample.Graphql.Tests/Helpers/TemporaryGraphQlExtension.cs @@ -31,12 +31,8 @@ public IHostBuilder Configure(IHostBuilder builder) } [Obsolete("Remove once https://github.com/ChilliCream/hotchocolate/issues/5684 is fixed!")] - internal class MyHttpResponseFormatter : DefaultHttpResponseFormatter + internal class MyHttpResponseFormatter() : DefaultHttpResponseFormatter(true) { - public MyHttpResponseFormatter() : base(true) - { - } - protected override HttpStatusCode OnDetermineStatusCode(IResponseStream responseStream, FormatInfo format, HttpStatusCode? proposedStatusCode) { var code = base.OnDetermineStatusCode(responseStream, format, proposedStatusCode); diff --git a/test/Sample.Graphql.Tests/LaunchRecords/CreateLaunchRecordTests.cs b/test/Sample.Graphql.Tests/LaunchRecords/CreateLaunchRecordTests.cs index 077802eb5..3bf705205 100644 --- a/test/Sample.Graphql.Tests/LaunchRecords/CreateLaunchRecordTests.cs +++ b/test/Sample.Graphql.Tests/LaunchRecords/CreateLaunchRecordTests.cs @@ -1,24 +1,17 @@ -using Alba; -using DryIoc; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using NodaTime; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; using CoreRocketType = Sample.Core.Domain.RocketType; namespace Sample.Graphql.Tests.LaunchRecords; -public class CreateLaunchRecordTests : GraphQlWebAppFixtureTest +public class CreateLaunchRecordTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebWebAppFixture) { private static readonly Faker Faker = new(); - public CreateLaunchRecordTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebWebAppFixture) - : base(outputHelper, rocketSurgeryWebWebAppFixture) - { - } - [Fact] public async Task Should_Create_A_LaunchRecord() { diff --git a/test/Sample.Graphql.Tests/LaunchRecords/GetLaunchRecordTests.cs b/test/Sample.Graphql.Tests/LaunchRecords/GetLaunchRecordTests.cs index 08dca3a67..f79d94cc0 100644 --- a/test/Sample.Graphql.Tests/LaunchRecords/GetLaunchRecordTests.cs +++ b/test/Sample.Graphql.Tests/LaunchRecords/GetLaunchRecordTests.cs @@ -1,8 +1,6 @@ -using DryIoc; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using NodaTime; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core.Domain; using Sample.Core.Models; using Sample.Graphql.Tests.Helpers; @@ -10,7 +8,8 @@ namespace Sample.Graphql.Tests.LaunchRecords; -public class GetLaunchRecordTests : GraphQlWebAppFixtureTest +public class GetLaunchRecordTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebAppFixture) { [Fact] public async Task Should_Get_A_LaunchRecord() @@ -53,9 +52,5 @@ public async Task Should_Get_A_LaunchRecord() response.Data.LaunchRecords!.Nodes[0].ScheduledLaunchDate.Should().Be(record.ScheduledLaunchDate); } - public GetLaunchRecordTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(outputHelper, rocketSurgeryWebAppFixture) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Graphql.Tests/LaunchRecords/ListLaunchRecordsTests.cs b/test/Sample.Graphql.Tests/LaunchRecords/ListLaunchRecordsTests.cs index b08b2dac2..a0bf3b8dc 100644 --- a/test/Sample.Graphql.Tests/LaunchRecords/ListLaunchRecordsTests.cs +++ b/test/Sample.Graphql.Tests/LaunchRecords/ListLaunchRecordsTests.cs @@ -1,14 +1,13 @@ -using DryIoc; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; namespace Sample.Graphql.Tests.LaunchRecords; -public class ListLaunchRecordsTests : GraphQlWebAppFixtureTest +public class ListLaunchRecordsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebAppFixture) { [Fact] public async Task Should_List_LaunchRecords() @@ -57,9 +56,5 @@ await ServiceProvider.WithScoped() response.Data!.LaunchRecords!.Nodes!.Should().HaveCount(3); } - public ListLaunchRecordsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(outputHelper, rocketSurgeryWebAppFixture) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Graphql.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs b/test/Sample.Graphql.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs index 9100fd3a7..6a68d338b 100644 --- a/test/Sample.Graphql.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs +++ b/test/Sample.Graphql.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs @@ -1,21 +1,16 @@ -using DryIoc; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; namespace Sample.Graphql.Tests.LaunchRecords; -public class RemoveLaunchRecordsTests : GraphQlWebAppFixtureTest +public class RemoveLaunchRecordsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebAppFixture) { private static readonly Faker Faker = new(); - public RemoveLaunchRecordsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(outputHelper, rocketSurgeryWebAppFixture) - { - } - [Fact] public async Task Should_Remove_LaunchRecord() { diff --git a/test/Sample.Graphql.Tests/LaunchRecords/UpdateLaunchRecordTests.cs b/test/Sample.Graphql.Tests/LaunchRecords/UpdateLaunchRecordTests.cs index 1cf110623..f6e6bf76d 100644 --- a/test/Sample.Graphql.Tests/LaunchRecords/UpdateLaunchRecordTests.cs +++ b/test/Sample.Graphql.Tests/LaunchRecords/UpdateLaunchRecordTests.cs @@ -1,9 +1,7 @@ -using DryIoc; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using NodaTime; using NodaTime.Extensions; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core.Domain; using Sample.Core.Models; using Sample.Graphql.Tests.Helpers; @@ -11,7 +9,8 @@ namespace Sample.Graphql.Tests.LaunchRecords; -public class UpdateLaunchRecordTests : GraphQlWebAppFixtureTest +public class UpdateLaunchRecordTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebAppFixture) { [Fact] public async Task Should_Update_A_LaunchRecord() @@ -64,9 +63,5 @@ await client.UpdateLaunchRecord.ExecuteAsync( response.Data.LaunchRecords!.Nodes[0].PayloadWeightKg.Should().Be(200); } - public UpdateLaunchRecordTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(outputHelper, rocketSurgeryWebAppFixture) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Graphql.Tests/ModuleInitializer.cs b/test/Sample.Graphql.Tests/ModuleInitializer.cs index 23b02d31c..b2113d250 100644 --- a/test/Sample.Graphql.Tests/ModuleInitializer.cs +++ b/test/Sample.Graphql.Tests/ModuleInitializer.cs @@ -14,9 +14,9 @@ public static void Init() { DiffRunner.Disabled = true; VerifierSettings.DontScrubDateTimes(); - VerifierSettings.AddExtraSettings(_ => _.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb)); - VerifierSettings.AddExtraSettings(_ => _.Converters.Add(new GeometryConverter())); - + VerifierSettings.AddExtraSettings(settings => settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb)); + VerifierSettings.AddExtraSettings(settings => settings.Converters.Add(new GeometryConverter())); + VerifierSettings.DisableRequireUniquePrefix(); DerivePathInfo( (sourceFile, _, type, method) => @@ -42,6 +42,7 @@ public GeometryConverter() { _writer = new WKTWriter(); } + public override bool CanConvert(Type type) { return typeof(Geometry).IsAssignableFrom(type); diff --git a/test/Sample.Graphql.Tests/NamedSchemaTests.cs b/test/Sample.Graphql.Tests/NamedSchemaTests.cs index 6151a779a..1f2477d47 100644 --- a/test/Sample.Graphql.Tests/NamedSchemaTests.cs +++ b/test/Sample.Graphql.Tests/NamedSchemaTests.cs @@ -14,7 +14,7 @@ public NamedSchemaTests(ITestOutputHelper testOutputHelper) : base(testOutputHel { _context = ConventionContext.From( ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly), LoggerFactory) + .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) .WithLogger(LoggerFactory.CreateLogger(nameof(AutoFakeTest))) .ConfigureServices( (_, collection) => diff --git a/test/Sample.Graphql.Tests/Rockets/CreateRocketTests.cs b/test/Sample.Graphql.Tests/Rockets/CreateRocketTests.cs index 9ba8ea3d3..0787d1717 100644 --- a/test/Sample.Graphql.Tests/Rockets/CreateRocketTests.cs +++ b/test/Sample.Graphql.Tests/Rockets/CreateRocketTests.cs @@ -1,25 +1,11 @@ -using DryIoc; -using Microsoft.AspNetCore.Hosting.Server; -using Microsoft.AspNetCore.Mvc.Testing.Handlers; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Data.Sqlite; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyModel; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Http; -using Microsoft.Extensions.Options; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.Conventions.Testing; -using Rocket.Surgery.Hosting; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; +using Microsoft.Extensions.DependencyInjection; using Sample.Graphql.Tests.Helpers; using Serilog.Events; -using CoreRocketType = Sample.Core.Domain.RocketType; namespace Sample.Graphql.Tests.Rockets; -public class CreateRocketTests : GraphQlWebAppFixtureTest +public class CreateRocketTests(ITestOutputHelper testOutputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(testOutputHelper, rocketSurgeryWebAppFixture, LogEventLevel.Information) { [Fact] public async Task Should_Create_A_Rocket() @@ -60,8 +46,4 @@ public async Task Should_Throw_If_Rocket_Exists() response2.IsErrorResult().Should().BeTrue(); response2.Errors[0].Message.Should().Be("A Rocket already exists with that serial number!"); } - - public CreateRocketTests(ITestOutputHelper testOutputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(testOutputHelper, rocketSurgeryWebAppFixture, LogEventLevel.Information) - { - } } diff --git a/test/Sample.Graphql.Tests/Rockets/GetRocketTests.cs b/test/Sample.Graphql.Tests/Rockets/GetRocketTests.cs index 5b9af993d..99dc55993 100644 --- a/test/Sample.Graphql.Tests/Rockets/GetRocketTests.cs +++ b/test/Sample.Graphql.Tests/Rockets/GetRocketTests.cs @@ -1,13 +1,13 @@ using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; using CoreRocketType = Sample.Core.Domain.RocketType; namespace Sample.Graphql.Tests.Rockets; -public class GetRocketTests : GraphQlWebAppFixtureTest +public class GetRocketTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebAppFixture) { [Fact] public async Task Should_Get_A_Rocket() @@ -32,13 +32,9 @@ public async Task Should_Get_A_Rocket() var response = await client.GetRocket.ExecuteAsync(rocket.Value); response.EnsureNoErrors(); - response.Data!.Rockets!.Nodes[0].Type.Should().Be(RocketType.Falcon9); + response.Data!.Rockets!.Nodes![0].Type.Should().Be(RocketType.Falcon9); response.Data.Rockets!.Nodes[0].SerialNumber.Should().Be("12345678901234"); } - public GetRocketTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(outputHelper, rocketSurgeryWebAppFixture) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Graphql.Tests/Rockets/ListRocketsTests.cs b/test/Sample.Graphql.Tests/Rockets/ListRocketsTests.cs index 4f5d29791..006ac75ac 100644 --- a/test/Sample.Graphql.Tests/Rockets/ListRocketsTests.cs +++ b/test/Sample.Graphql.Tests/Rockets/ListRocketsTests.cs @@ -1,14 +1,13 @@ -using DryIoc; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; namespace Sample.Graphql.Tests.Rockets; -public class ListRocketsTests : GraphQlWebAppFixtureTest +public class ListRocketsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebAppFixture) { [Fact] public async Task Should_List_Rockets() @@ -52,9 +51,5 @@ await ServiceProvider.WithScoped() response.Data!.Rockets!.Nodes!.Should().HaveCount(5); } - public ListRocketsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(outputHelper, rocketSurgeryWebAppFixture) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Graphql.Tests/Rockets/RemoveRocketsTests.cs b/test/Sample.Graphql.Tests/Rockets/RemoveRocketsTests.cs index 15a2b0e0c..f3950e959 100644 --- a/test/Sample.Graphql.Tests/Rockets/RemoveRocketsTests.cs +++ b/test/Sample.Graphql.Tests/Rockets/RemoveRocketsTests.cs @@ -1,21 +1,16 @@ -using DryIoc; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; namespace Sample.Graphql.Tests.Rockets; -public class RemoveRocketsTests : GraphQlWebAppFixtureTest +public class RemoveRocketsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(outputHelper, rocketSurgeryWebAppFixture) { private static readonly Faker Faker = new(); - public RemoveRocketsTests(ITestOutputHelper outputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base(outputHelper, rocketSurgeryWebAppFixture) - { - } - [Fact] public async Task Should_Remove_Rocket() { @@ -28,7 +23,7 @@ public async Task Should_Remove_Rocket() var rocket = faker.Generate(); z.Add(rocket); - await z.SaveChangesAsync().ConfigureAwait(false); + await z.SaveChangesAsync(); return rocket.Id; } ); diff --git a/test/Sample.Graphql.Tests/Rockets/UpdateRocketTests.cs b/test/Sample.Graphql.Tests/Rockets/UpdateRocketTests.cs index 07b38a5aa..504eddd6c 100644 --- a/test/Sample.Graphql.Tests/Rockets/UpdateRocketTests.cs +++ b/test/Sample.Graphql.Tests/Rockets/UpdateRocketTests.cs @@ -1,15 +1,14 @@ -using DryIoc; -using Humanizer; +using Humanizer; using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core.Domain; using Sample.Graphql.Tests.Helpers; using CoreRocketType = Sample.Core.Domain.RocketType; namespace Sample.Graphql.Tests.Rockets; -public class UpdateRocketTests : GraphQlWebAppFixtureTest +public class UpdateRocketTests(ITestOutputHelper testOutputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) + : GraphQlWebAppFixtureTest(testOutputHelper, rocketSurgeryWebAppFixture) { [Fact] public async Task Should_Update_A_Rocket() @@ -144,12 +143,6 @@ public async Task Should_Patch_A_Rocket_Type() u.Data!.PatchRocket.SerialNumber.Should().Be("12345678901234"); } - public UpdateRocketTests(ITestOutputHelper testOutputHelper, GraphQlAppFixture rocketSurgeryWebAppFixture) : base( - testOutputHelper, rocketSurgeryWebAppFixture - ) - { - } - private static readonly Faker Faker = new(); [Theory] @@ -161,7 +154,7 @@ public async Task Should_Validate_Required_Fields(EditRocketRequest request, str var response = await client.UpdateRocket.ExecuteAsync(request); response.IsErrorResult().Should().BeTrue(); - var extensionKey = response.Errors[0].Extensions.ContainsKey("propertyName") ? "propertyName" : "field"; + var extensionKey = response.Errors[0].Extensions!.ContainsKey("propertyName") ? "propertyName" : "field"; response.Errors[0].Extensions![extensionKey] .As().Split('.').Last() diff --git a/test/Sample.Graphql.Tests/SqliteConnectionService.cs b/test/Sample.Graphql.Tests/SqliteConnectionService.cs index bad155993..97986ac04 100644 --- a/test/Sample.Graphql.Tests/SqliteConnectionService.cs +++ b/test/Sample.Graphql.Tests/SqliteConnectionService.cs @@ -4,18 +4,11 @@ namespace Sample.Graphql.Tests; -internal class SqliteConnectionService : IHostedService +internal class SqliteConnectionService(IServiceProvider serviceProvider) : IHostedService { - private readonly IServiceProvider _serviceProvider; - - public SqliteConnectionService(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public async Task StartAsync(CancellationToken cancellationToken) { - await _serviceProvider.WithScoped() + await serviceProvider.WithScoped() .Invoke(z => z.Database.EnsureCreatedAsync(cancellationToken)) .ConfigureAwait(false); } diff --git a/test/Sample.Graphql.Tests/StrawberryShakeSerializerTests.cs b/test/Sample.Graphql.Tests/StrawberryShakeSerializerTests.cs index d6ce794c8..4e16b4b2e 100644 --- a/test/Sample.Graphql.Tests/StrawberryShakeSerializerTests.cs +++ b/test/Sample.Graphql.Tests/StrawberryShakeSerializerTests.cs @@ -1,6 +1,5 @@ using Alba; using Microsoft.Extensions.DependencyInjection; -using NetTopologySuite.Geometries; using NetTopologySuite.IO; using NodaTime; using Rocket.Surgery.Extensions.Testing; @@ -11,7 +10,7 @@ namespace Sample.Graphql.Tests; [UsesVerify] -public class StrawberryShakeSerializerTests : LoggerTest +public class StrawberryShakeSerializerTests(ITestOutputHelper testOutputHelper) : LoggerTest(testOutputHelper) { [Fact] public async Task Should_Roundtrip_Instant() @@ -172,7 +171,6 @@ public async Task Should_Roundtrip_Period() await using var host = await AlbaHost.For( new LaunchPadExtension(LoggerFactory), new GraphQlExtension(), new SqliteExtension() ); - var clock = host.Services.GetRequiredService(); var client = host.Services.GetRequiredService(); @@ -194,7 +192,6 @@ public async Task Should_Roundtrip_Duration() await using var host = await AlbaHost.For( new LaunchPadExtension(LoggerFactory), new GraphQlExtension(), new SqliteExtension() ); - var clock = host.Services.GetRequiredService(); var client = host.Services.GetRequiredService(); @@ -216,7 +213,6 @@ public async Task Should_Roundtrip_Offset() await using var host = await AlbaHost.For( new LaunchPadExtension(LoggerFactory), new GraphQlExtension(), new SqliteExtension() ); - var clock = host.Services.GetRequiredService(); var client = host.Services.GetRequiredService(); @@ -250,7 +246,7 @@ public async Task Should_Roundtrip_IsoDayOfWeek() await Verify(result); } - + [Theory] [InlineData("POINT(3 4)")] [InlineData("LINESTRING(5 6, 7 8)")] @@ -263,22 +259,21 @@ public async Task Should_Roundtrip_Geometry(string wkt) await using var host = await AlbaHost.For( new LaunchPadExtension(LoggerFactory), new GraphQlExtension(), new SqliteExtension() ); - + var client = host.Services.GetRequiredService(); var reader = new WKTReader(); var result = await client.GetGeometryTypes.ExecuteAsync( - new () + new() { - Geometry = reader.Read(wkt) + Geometry = reader.Read(wkt) } ); await Verify(result).UseTextForParameters(wkt); } - - - + + // [Fact] // public async Task Should_Roundtrip_Point() // { @@ -293,7 +288,7 @@ public async Task Should_Roundtrip_Geometry(string wkt) // var result = await client.GetGeometryTypes.ExecuteAsync( // new () // { -// Point = reader.Read(wkt) +// Point = reader.Read(wkt) // } // ); // @@ -309,7 +304,4 @@ public async Task Should_Roundtrip_Geometry(string wkt) multiLineString: "MULTILINESTRING((19 20, 21 22), (23 24, 25 26))" multiPolygon: "MULTIPOLYGON(((27 28, 29 30, 31 32, 27 28)), ((33 34, 35 36, 37 38, 33 34)))" */ - public StrawberryShakeSerializerTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - } } diff --git a/test/Sample.Grpc.Tests/FoundationTests.cs b/test/Sample.Grpc.Tests/FoundationTests.cs index 605023541..51ea4753c 100644 --- a/test/Sample.Grpc.Tests/FoundationTests.cs +++ b/test/Sample.Grpc.Tests/FoundationTests.cs @@ -1,13 +1,11 @@ using System.Net; using AutoMapper; using Microsoft.Extensions.DependencyInjection; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Grpc.Tests.Helpers; namespace Sample.Grpc.Tests; -public class FoundationTests : WebAppFixtureTest +public class FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : WebAppFixtureTest(testOutputHelper, factory) { [Fact] public void AutoMapper() @@ -22,8 +20,4 @@ public async Task Starts() var response = await AlbaHost.Server.CreateClient().GetAsync("/"); response.StatusCode.Should().Be(HttpStatusCode.OK); } - - public FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : base(testOutputHelper, factory) - { - } } diff --git a/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs index 67eae7016..faa222d1e 100644 --- a/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs @@ -3,9 +3,4 @@ namespace Sample.Grpc.Tests.Helpers; -public class TestWebAppFixture : LaunchPadWebAppFixture, IAsyncLifetime -{ - public TestWebAppFixture() : base(new SqliteExtension()) - { - } -} +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; diff --git a/test/Sample.Grpc.Tests/LaunchRecords/CreateLaunchRecordTests.cs b/test/Sample.Grpc.Tests/LaunchRecords/CreateLaunchRecordTests.cs index e9e90c9ce..51fe72714 100644 --- a/test/Sample.Grpc.Tests/LaunchRecords/CreateLaunchRecordTests.cs +++ b/test/Sample.Grpc.Tests/LaunchRecords/CreateLaunchRecordTests.cs @@ -1,5 +1,4 @@ -using DryIoc; -using Google.Protobuf.WellKnownTypes; +using Google.Protobuf.WellKnownTypes; using Microsoft.Extensions.DependencyInjection; using NodaTime; using Rocket.Surgery.DependencyInjection; @@ -10,14 +9,11 @@ namespace Sample.Grpc.Tests.LaunchRecords; -public class CreateLaunchRecordTests : WebAppFixtureTest +public class CreateLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppFixture testWebAppFixture) + : WebAppFixtureTest(outputHelper, testWebAppFixture) { private static readonly Faker Faker = new(); - public CreateLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppFixture testWebAppFixture) : base(outputHelper, testWebAppFixture) - { - } - [Fact] public async Task Should_Create_A_LaunchRecord() { diff --git a/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs b/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs index a5b1928a4..94a695f3d 100644 --- a/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs +++ b/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs @@ -9,14 +9,11 @@ namespace Sample.Grpc.Tests.LaunchRecords; -public class GetLaunchRecordTests : WebAppFixtureTest +public class GetLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppFixture testWebAppFixture) + : WebAppFixtureTest(outputHelper, testWebAppFixture) { private static readonly Faker Faker = new(); - public GetLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppFixture testWebAppFixture) : base(outputHelper, testWebAppFixture) - { - } - [Fact] public async Task Should_Get_A_LaunchRecord() { diff --git a/test/Sample.Grpc.Tests/LaunchRecords/ListLaunchRecordsTests.cs b/test/Sample.Grpc.Tests/LaunchRecords/ListLaunchRecordsTests.cs index 7288537b1..0e2bb744f 100644 --- a/test/Sample.Grpc.Tests/LaunchRecords/ListLaunchRecordsTests.cs +++ b/test/Sample.Grpc.Tests/LaunchRecords/ListLaunchRecordsTests.cs @@ -1,5 +1,4 @@ -using DryIoc; -using Grpc.Core; +using Grpc.Core; using Rocket.Surgery.DependencyInjection; using Sample.Core; using Sample.Core.Domain; @@ -9,14 +8,11 @@ namespace Sample.Grpc.Tests.LaunchRecords; -public class ListLaunchRecordsTests : WebAppFixtureTest +public class ListLaunchRecordsTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) + : WebAppFixtureTest(outputHelper, webAppFixture) { private static readonly Faker Faker = new(); - public ListLaunchRecordsTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) : base(outputHelper, webAppFixture) - { - } - [Fact] public async Task Should_List_LaunchRecords() { diff --git a/test/Sample.Grpc.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs b/test/Sample.Grpc.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs index 2d2cc3f31..949742871 100644 --- a/test/Sample.Grpc.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs +++ b/test/Sample.Grpc.Tests/LaunchRecords/RemoveLaunchRecordsTests.cs @@ -7,14 +7,11 @@ namespace Sample.Grpc.Tests.LaunchRecords; -public class RemoveLaunchRecordsTests : WebAppFixtureTest +public class RemoveLaunchRecordsTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) + : WebAppFixtureTest(outputHelper, webAppFixture) { private static readonly Faker Faker = new(); - public RemoveLaunchRecordsTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) : base(outputHelper, webAppFixture) - { - } - [Fact] public async Task Should_Remove_LaunchRecord() { diff --git a/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs b/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs index 306c3d1f4..ea2428397 100644 --- a/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs +++ b/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs @@ -1,25 +1,21 @@ -using DryIoc; -using Google.Protobuf.WellKnownTypes; -using Microsoft.Extensions.DependencyInjection; +using Google.Protobuf.WellKnownTypes; using NodaTime; -using NodaTime.Extensions; using Rocket.Surgery.DependencyInjection; using Sample.Core.Domain; using Sample.Core.Models; using Sample.Grpc.Tests.Helpers; using Sample.Grpc.Tests.Validation; -using Duration = NodaTime.Duration; using LR = Sample.Grpc.LaunchRecords; namespace Sample.Grpc.Tests.LaunchRecords; -public class UpdateLaunchRecordTests : WebAppFixtureTest +public class UpdateLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) + : WebAppFixtureTest(outputHelper, webAppFixture) { [Fact] public async Task Should_Update_A_LaunchRecord() { var client = new LR.LaunchRecordsClient(AlbaHost.CreateGrpcChannel()); - var clock = ServiceProvider.GetRequiredService(); var record = await ServiceProvider.WithScoped() .Invoke( async (context, clk) => @@ -67,9 +63,5 @@ await client.EditLaunchRecordAsync( response.PayloadWeightKg.Should().Be(200); } - public UpdateLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) : base(outputHelper, webAppFixture) - { - } - private static readonly Faker Faker = new(); } diff --git a/test/Sample.Grpc.Tests/Rockets/CreateRocketTests.cs b/test/Sample.Grpc.Tests/Rockets/CreateRocketTests.cs index 64978ff79..1fc446b6b 100644 --- a/test/Sample.Grpc.Tests/Rockets/CreateRocketTests.cs +++ b/test/Sample.Grpc.Tests/Rockets/CreateRocketTests.cs @@ -1,17 +1,13 @@ -using DryIoc; -using Grpc.Core; +using Grpc.Core; using Sample.Grpc.Tests.Helpers; using Sample.Grpc.Tests.Validation; using R = Sample.Grpc.Rockets; namespace Sample.Grpc.Tests.Rockets; -public class CreateRocketTests : WebAppFixtureTest +public class CreateRocketTests(ITestOutputHelper testOutputHelper, TestWebAppFixture webAppFixture) + : WebAppFixtureTest(testOutputHelper, webAppFixture) { - public CreateRocketTests(ITestOutputHelper testOutputHelper, TestWebAppFixture webAppFixture) : base(testOutputHelper, webAppFixture) - { - } - [Fact] public async Task Should_Create_A_Rocket() { diff --git a/test/Sample.Grpc.Tests/Rockets/GetRocketTests.cs b/test/Sample.Grpc.Tests/Rockets/GetRocketTests.cs index 1476d5af0..e7bac28ca 100644 --- a/test/Sample.Grpc.Tests/Rockets/GetRocketTests.cs +++ b/test/Sample.Grpc.Tests/Rockets/GetRocketTests.cs @@ -1,5 +1,4 @@ -using DryIoc; -using Rocket.Surgery.DependencyInjection; +using Rocket.Surgery.DependencyInjection; using Sample.Core.Domain; using Sample.Grpc.Tests.Helpers; using Sample.Grpc.Tests.Validation; @@ -7,14 +6,10 @@ namespace Sample.Grpc.Tests.Rockets; -public class GetRocketTests : WebAppFixtureTest +public class GetRocketTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) : WebAppFixtureTest(outputHelper, webAppFixture) { private static readonly Faker Faker = new(); - public GetRocketTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) : base(outputHelper, webAppFixture) - { - } - [Fact] public async Task Should_Get_A_Rocket() { diff --git a/test/Sample.Grpc.Tests/Rockets/ListRocketsTests.cs b/test/Sample.Grpc.Tests/Rockets/ListRocketsTests.cs index 85993e66a..ed1974753 100644 --- a/test/Sample.Grpc.Tests/Rockets/ListRocketsTests.cs +++ b/test/Sample.Grpc.Tests/Rockets/ListRocketsTests.cs @@ -1,5 +1,4 @@ -using DryIoc; -using Grpc.Core; +using Grpc.Core; using Rocket.Surgery.DependencyInjection; using Sample.Core; using Sample.Core.Domain; @@ -9,14 +8,11 @@ namespace Sample.Grpc.Tests.Rockets; -public class ListRocketsTests : WebAppFixtureTest +public class ListRocketsTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) + : WebAppFixtureTest(outputHelper, webAppFixture) { private static readonly Faker Faker = new(); - public ListRocketsTests(ITestOutputHelper outputHelper, TestWebAppFixture webAppFixture) : base(outputHelper, webAppFixture) - { - } - [Fact] public async Task Should_List_Rockets() { diff --git a/test/Sample.Grpc.Tests/Rockets/RemoveRocketsTests.cs b/test/Sample.Grpc.Tests/Rockets/RemoveRocketsTests.cs index ba0f3754b..611ee064b 100644 --- a/test/Sample.Grpc.Tests/Rockets/RemoveRocketsTests.cs +++ b/test/Sample.Grpc.Tests/Rockets/RemoveRocketsTests.cs @@ -1,5 +1,4 @@ -using DryIoc; -using Rocket.Surgery.DependencyInjection; +using Rocket.Surgery.DependencyInjection; using Sample.Core; using Sample.Core.Domain; using Sample.Grpc.Tests.Helpers; @@ -8,14 +7,11 @@ namespace Sample.Grpc.Tests.Rockets; -public class RemoveRocketsTests : WebAppFixtureTest +public class RemoveRocketsTests(ITestOutputHelper outputHelper, TestWebAppFixture testWebAppFixture) + : WebAppFixtureTest(outputHelper, testWebAppFixture) { private static readonly Faker Faker = new(); - public RemoveRocketsTests(ITestOutputHelper outputHelper, TestWebAppFixture testWebAppFixture) : base(outputHelper, testWebAppFixture) - { - } - [Fact] public async Task Should_Remove_Rocket() { @@ -28,7 +24,7 @@ public async Task Should_Remove_Rocket() var rocket = faker.Generate(); z.Add(rocket); - await z.SaveChangesAsync().ConfigureAwait(false); + await z.SaveChangesAsync(); return rocket.Id; } ); diff --git a/test/Sample.Grpc.Tests/Rockets/UpdateRocketTests.cs b/test/Sample.Grpc.Tests/Rockets/UpdateRocketTests.cs index c2b7a8df1..56bd60f71 100644 --- a/test/Sample.Grpc.Tests/Rockets/UpdateRocketTests.cs +++ b/test/Sample.Grpc.Tests/Rockets/UpdateRocketTests.cs @@ -7,14 +7,11 @@ namespace Sample.Grpc.Tests.Rockets; -public class UpdateRocketTests : WebAppFixtureTest +public class UpdateRocketTests(ITestOutputHelper testOutputHelper, TestWebAppFixture testWebAppFixture) + : WebAppFixtureTest(testOutputHelper, testWebAppFixture) { private static readonly Faker Faker = new(); - public UpdateRocketTests(ITestOutputHelper testOutputHelper, TestWebAppFixture testWebAppFixture) : base(testOutputHelper, testWebAppFixture) - { - } - [Fact] public async Task Should_Update_A_Rocket() { @@ -63,7 +60,7 @@ public async Task Should_Validate_Required_Fields(UpdateRocketRequest request, s e.Message.Should().Contain(propertyName); } - private class ShouldValidateUsersRequiredFieldData : TheoryData + private sealed class ShouldValidateUsersRequiredFieldData : TheoryData { public ShouldValidateUsersRequiredFieldData() { diff --git a/test/Sample.Grpc.Tests/SqliteConnectionService.cs b/test/Sample.Grpc.Tests/SqliteConnectionService.cs index 92e1acdd2..bf5911e98 100644 --- a/test/Sample.Grpc.Tests/SqliteConnectionService.cs +++ b/test/Sample.Grpc.Tests/SqliteConnectionService.cs @@ -4,18 +4,11 @@ namespace Sample.Grpc.Tests; -internal class SqliteConnectionService : IHostedService +internal sealed class SqliteConnectionService(IServiceProvider serviceProvider) : IHostedService { - private readonly IServiceProvider _serviceProvider; - - public SqliteConnectionService(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public async Task StartAsync(CancellationToken cancellationToken) { - await _serviceProvider.WithScoped() + await serviceProvider.WithScoped() .Invoke(z => z.Database.EnsureCreatedAsync(cancellationToken)) .ConfigureAwait(false); } diff --git a/test/Sample.Grpc.Tests/Validation/Integration/CustomMessageHandlerIntegrationTest.cs b/test/Sample.Grpc.Tests/Validation/Integration/CustomMessageHandlerIntegrationTest.cs index da65da7e2..58d84fd63 100644 --- a/test/Sample.Grpc.Tests/Validation/Integration/CustomMessageHandlerIntegrationTest.cs +++ b/test/Sample.Grpc.Tests/Validation/Integration/CustomMessageHandlerIntegrationTest.cs @@ -1,21 +1,13 @@ using FluentValidation.Results; using Grpc.Core; -using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.Extensions.DependencyInjection; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Rocket.Surgery.LaunchPad.Grpc.Validation; using Sample.Grpc.Tests.Helpers; namespace Sample.Grpc.Tests.Validation.Integration; -public class CustomMessageHandlerIntegrationTest : WebAppFixtureTest +public class CustomMessageHandlerIntegrationTest(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) + : WebAppFixtureTest(testOutputHelper, factory) { - public CustomMessageHandlerIntegrationTest(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : base(testOutputHelper, factory) - { - } - [Fact] public async Task Should_ThrowInvalidArgument_When_NameOfMessageIsEmpty() { @@ -39,7 +31,7 @@ await client.GetRocketsAsync( Assert.Equal("Property Id failed validation.", rpcException.Status.Detail); } - private class CustomMessageHandler : IValidatorErrorMessageHandler + private sealed class CustomMessageHandler : IValidatorErrorMessageHandler { public Task HandleAsync(IEnumerable failures) { diff --git a/test/Sample.Grpc.Tests/Validation/Integration/CustomValidatorIntegrationTest.cs b/test/Sample.Grpc.Tests/Validation/Integration/CustomValidatorIntegrationTest.cs index 53637660a..f4e375115 100644 --- a/test/Sample.Grpc.Tests/Validation/Integration/CustomValidatorIntegrationTest.cs +++ b/test/Sample.Grpc.Tests/Validation/Integration/CustomValidatorIntegrationTest.cs @@ -1,16 +1,14 @@ using Grpc.Core; using Rocket.Surgery.DependencyInjection; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Core; using Sample.Core.Domain; using Sample.Grpc.Tests.Helpers; namespace Sample.Grpc.Tests.Validation.Integration; -public class CustomValidatorIntegrationTest : WebAppFixtureTest +public class CustomValidatorIntegrationTest(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) + : WebAppFixtureTest(testOutputHelper, factory) { - public CustomValidatorIntegrationTest(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : base(testOutputHelper, factory) { } [Fact] public async Task Should_ResponseMessage_When_MessageIsValid() { diff --git a/test/Sample.Grpc.Tests/Validation/WebApplicationFactoryHelper.cs b/test/Sample.Grpc.Tests/Validation/WebApplicationFactoryHelper.cs index 137a4ecf1..0b8dfff18 100644 --- a/test/Sample.Grpc.Tests/Validation/WebApplicationFactoryHelper.cs +++ b/test/Sample.Grpc.Tests/Validation/WebApplicationFactoryHelper.cs @@ -1,8 +1,6 @@ using Alba; using Grpc.Net.Client; -using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Grpc.Tests.Validation; @@ -26,7 +24,7 @@ protected override async Task SendAsync(HttpRequestMessage } } - private class ResponseVersionHandler : DelegatingHandler + private sealed class ResponseVersionHandler : DelegatingHandler { protected override async Task SendAsync( HttpRequestMessage request, diff --git a/test/Sample.Pages.Tests/FoundationTests.cs b/test/Sample.Pages.Tests/FoundationTests.cs index 131e9dcb4..e7f03fff5 100644 --- a/test/Sample.Pages.Tests/FoundationTests.cs +++ b/test/Sample.Pages.Tests/FoundationTests.cs @@ -1,13 +1,11 @@ using System.Net; using AutoMapper; using Microsoft.Extensions.DependencyInjection; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; using Sample.Pages.Tests.Helpers; namespace Sample.Pages.Tests; -public class FoundationTests : WebAppFixtureTest +public class FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : WebAppFixtureTest(testOutputHelper, factory) { [Fact] public void AutoMapper() @@ -22,6 +20,4 @@ public async Task Starts() var response = await AlbaHost.Server.CreateClient().GetAsync("/"); response.StatusCode.Should().Be(HttpStatusCode.OK); } - - public FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : base(testOutputHelper, factory) { } } diff --git a/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs index 4d785bcff..892a273c3 100644 --- a/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs @@ -3,9 +3,4 @@ namespace Sample.Pages.Tests.Helpers; -public class TestWebAppFixture : LaunchPadWebAppFixture, IAsyncLifetime -{ - public TestWebAppFixture() : base(new SqliteExtension()) - { - } -} +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; diff --git a/test/Sample.Pages.Tests/SqliteConnectionService.cs b/test/Sample.Pages.Tests/SqliteConnectionService.cs index 3a67ce2d4..85d1b03b7 100644 --- a/test/Sample.Pages.Tests/SqliteConnectionService.cs +++ b/test/Sample.Pages.Tests/SqliteConnectionService.cs @@ -4,18 +4,11 @@ namespace Sample.Pages.Tests; -internal class SqliteConnectionService : IHostedService +internal sealed class SqliteConnectionService(IServiceProvider serviceProvider) : IHostedService { - private readonly IServiceProvider _serviceProvider; - - public SqliteConnectionService(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public async Task StartAsync(CancellationToken cancellationToken) { - await _serviceProvider.WithScoped() + await serviceProvider.WithScoped() .Invoke(z => z.Database.EnsureCreatedAsync(cancellationToken)) .ConfigureAwait(false); } diff --git a/test/Sample.Restful.Tests/ApiDescriptionData.cs b/test/Sample.Restful.Tests/ApiDescriptionData.cs index 5ab1d88eb..10b36f018 100644 --- a/test/Sample.Restful.Tests/ApiDescriptionData.cs +++ b/test/Sample.Restful.Tests/ApiDescriptionData.cs @@ -1,11 +1,10 @@ using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Restful.Tests; -internal class ApiDescriptionData : TheoryData +internal sealed class ApiDescriptionData : TheoryData where T : class, ILaunchPadWebAppFixture, IAsyncLifetime, new() { public ApiDescriptionData() @@ -20,14 +19,9 @@ public ApiDescriptionData() } } -public class ApiDescriptionData +public class ApiDescriptionData(ApiDescription description) { - public ApiDescriptionData(ApiDescription description) - { - Description = description; - } - - public ApiDescription Description { get; } + public ApiDescription Description { get; } = description; public override string ToString() { diff --git a/test/Sample.Restful.Tests/FoundationTests.cs b/test/Sample.Restful.Tests/FoundationTests.cs index 88f2ebad3..e04c7e42b 100644 --- a/test/Sample.Restful.Tests/FoundationTests.cs +++ b/test/Sample.Restful.Tests/FoundationTests.cs @@ -2,16 +2,13 @@ using AutoMapper; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.AspNetCore.Testing; -using Sample.BlazorServer.Tests; using Sample.Restful.Tests.Helpers; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; namespace Sample.Restful.Tests; -public class FoundationTests : WebAppFixtureTest +public class FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : WebAppFixtureTest(testOutputHelper, factory) { [Fact] public void AutoMapper() @@ -27,10 +24,6 @@ public async Task Starts() response.StatusCode.Should().Be(HttpStatusCode.NotFound); } - public FoundationTests(ITestOutputHelper testOutputHelper, TestWebAppFixture factory) : base(testOutputHelper, factory) - { - } - [Theory] [ClassData(typeof(OpenApiDocuments))] public void OpenApiDocument(string document) @@ -39,7 +32,7 @@ public void OpenApiDocument(string document) .GetSwagger(document).Should().NotBeNull(); } - private class OpenApiDocuments : TheoryData + private sealed class OpenApiDocuments : TheoryData { public OpenApiDocuments() { diff --git a/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs b/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs index 646e12397..ab05c9ac3 100644 --- a/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs @@ -5,7 +5,7 @@ using Microsoft.Extensions.Hosting; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; -namespace Sample.BlazorServer.Tests; +namespace Sample.Restful.Tests.Helpers; public sealed class SqliteExtension : IResettableAlbaExtension where TDbContext : DbContext { @@ -64,4 +64,4 @@ public IHostBuilder Configure(IHostBuilder builder) return builder; } -} \ No newline at end of file +} diff --git a/test/Sample.Restful.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.Restful.Tests/Helpers/TestWebAppFixture.cs index 266751fa5..7de680890 100644 --- a/test/Sample.Restful.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.Restful.Tests/Helpers/TestWebAppFixture.cs @@ -1,12 +1,6 @@ using Rocket.Surgery.LaunchPad.AspNetCore.Testing; -using Sample.BlazorServer.Tests; using Sample.Core.Domain; namespace Sample.Restful.Tests.Helpers; -public class TestWebAppFixture : LaunchPadWebAppFixture, IAsyncLifetime -{ - public TestWebAppFixture() : base(new SqliteExtension()) - { - } -} +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; diff --git a/test/Sample.Restful.Tests/Helpers/WebAppFixtureTest.cs b/test/Sample.Restful.Tests/Helpers/WebAppFixtureTest.cs index e468a7497..49763ae4c 100644 --- a/test/Sample.Restful.Tests/Helpers/WebAppFixtureTest.cs +++ b/test/Sample.Restful.Tests/Helpers/WebAppFixtureTest.cs @@ -5,7 +5,7 @@ using Serilog; using Serilog.Events; -namespace Sample.BlazorServer.Tests; +namespace Sample.Restful.Tests.Helpers; public abstract class WebAppFixtureTest : LoggerTest, IClassFixture, IAsyncLifetime where TAppFixture : class, ILaunchPadWebAppFixture diff --git a/test/Sample.Restful.Tests/RestfulConventionTests.cs b/test/Sample.Restful.Tests/RestfulConventionTests.cs index 5b4230cfd..15166c94b 100644 --- a/test/Sample.Restful.Tests/RestfulConventionTests.cs +++ b/test/Sample.Restful.Tests/RestfulConventionTests.cs @@ -17,6 +17,7 @@ public void Should_Have_Success_Response_Types(ApiDescriptionData description) [ClassData(typeof(ApiDescriptionData))] public void Should_Have_Not_Found_Responses(ApiDescriptionData description) { + // ReSharper disable once NullableWarningSuppressionIsUsed var method = ( description.Description.ActionDescriptor as ControllerActionDescriptor )!.MethodInfo; if (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(IAsyncEnumerable<>)) return; description.Description.SupportedResponseTypes.Should().Contain(z => z.StatusCode == StatusCodes.Status404NotFound); diff --git a/test/Sample.Restful.Tests/SqliteConnectionService.cs b/test/Sample.Restful.Tests/SqliteConnectionService.cs index 4e444d9af..c04e3d852 100644 --- a/test/Sample.Restful.Tests/SqliteConnectionService.cs +++ b/test/Sample.Restful.Tests/SqliteConnectionService.cs @@ -4,18 +4,11 @@ namespace Sample.Restful.Tests; -internal class SqliteConnectionService : IHostedService +internal sealed class SqliteConnectionService(IServiceProvider serviceProvider) : IHostedService { - private readonly IServiceProvider _serviceProvider; - - public SqliteConnectionService(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public async Task StartAsync(CancellationToken cancellationToken) { - await _serviceProvider.WithScoped() + await serviceProvider.WithScoped() .Invoke(z => z.Database.EnsureCreatedAsync(cancellationToken)) .ConfigureAwait(false); }