From a7c46f03fd9d49722062fb502ce59b0258dca388 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Wed, 24 Apr 2024 20:21:49 -0400 Subject: [PATCH] Next (#1970) * Feature/conventions next (#1947) * Update open-telemetry to v1.8.1 (#1945) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * Update dependency SimplerSoftware.EntityFrameworkCore.SqlServer.NodaTime to v8 (#1666) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * Updated projects * wip * wip * wip * more conventions changes * wip * wip on fixing tests * wip on starting fixing alba tests * drop legacy analyzers * Unit tests are now fixed... --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * updated dotnet tools * Feature/ latest preview (#1948) * more wip * Fix some lp errors * update to latest conventions (#1950) * next preview (#1951) * revert automapper back to using assembly scanning (#1952) * revert automapper back to using assembly scanning * Automatically linting code --------- Co-authored-by: Rocket Understudy <33589210+rsg-bot@users.noreply.github.com> * Revert "revert automapper back to using assembly scanning (#1952)" This reverts commit 757cab72adfc722343db9e408600d822d1db6abb. * Bump preview (#1955) * bumps * fixed some bits * latest v * latest v * bump lp (#1956) * Updated to latest preview (#1960) * Nextpreivew0again (#1967) * bump conventions * bump lp * bump lp * Automatically linting code --------- Co-authored-by: Rocket Understudy <33589210+rsg-bot@users.noreply.github.com> * Automatically linting code --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Rocket Understudy <33589210+rsg-bot@users.noreply.github.com> --- .build/.build.csproj | 2 +- .config/dotnet-tools.json | 2 +- Directory.Build.props | 2 +- Directory.Build.targets | 2 +- Directory.Packages.props | 60 ++-- Directory.Packages.support.props | 9 - LaunchPad.sln | 105 ------- Readme.md | 4 - sample/Sample.BlazorServer/Program.cs | 48 +++- .../Sample.BlazorServer.csproj | 2 +- sample/Sample.BlazorServer/Startup.cs | 48 ---- sample/Sample.BlazorWasm/Program.cs | 24 +- .../Sample.BlazorWasm.csproj | 1 + sample/Sample.Classic.Restful/Program.cs | 63 +++-- .../Sample.Classic.Restful.csproj | 2 +- sample/Sample.Classic.Restful/Startup.cs | 59 ---- sample/Sample.Command/Program.cs | 38 +-- sample/Sample.Command/Sample.Command.csproj | 3 +- sample/Sample.Core/Domain/RocketDbContext.cs | 18 +- .../LaunchRecords/CreateLaunchRecord.cs | 13 +- .../LaunchRecords/DeleteLaunchRecord.cs | 13 +- .../LaunchRecords/EditLaunchRecord.cs | 5 +- .../LaunchRecords/GetLaunchRecord.cs | 14 +- .../LaunchRecords/ListLaunchRecords.cs | 14 +- .../Operations/Rockets/CreateRocket.cs | 19 +- .../Operations/Rockets/DeleteRocket.cs | 9 +- .../Operations/Rockets/EditRocket.cs | 17 +- .../Operations/Rockets/GetRocket.cs | 9 +- .../Rockets/GetRocketLaunchRecord.cs | 16 +- .../Rockets/GetRocketLaunchRecords.cs | 16 +- .../Operations/Rockets/ListRockets.cs | 7 +- sample/Sample.Core/Sample.Core.csproj | 2 +- sample/Sample.Function/.gitignore | 264 ------------------ .../Sample.Function/.vscode/extensions.json | 3 - sample/Sample.Function/LocalServices.cs | 16 -- sample/Sample.Function/Sample_Function.csproj | 21 -- sample/Sample.Function/Service.cs | 6 - sample/Sample.Function/Startup.cs | 24 -- sample/Sample.Function/TestFunction.cs | 40 --- sample/Sample.Function/host.json | 11 - sample/Sample.Graphql/Program.cs | 53 ++-- sample/Sample.Graphql/Sample.Graphql.csproj | 2 +- sample/Sample.Grpc/Program.cs | 41 +-- sample/Sample.Grpc/Sample.Grpc.csproj | 2 +- sample/Sample.Grpc/Startup.cs | 36 --- .../Pages/Rockets/Create.cshtml.cs | 14 +- sample/Sample.Pages/Program.cs | 129 ++++++++- sample/Sample.Pages/Sample.Pages.csproj | 3 +- sample/Sample.Pages/Startup.cs | 143 ---------- .../Sample.Restful.Client.csproj | 2 +- sample/Sample.Restful/Program.cs | 28 +- sample/Sample.Restful/Sample.Restful.csproj | 2 +- sample/Sample.Worker/Program.cs | 22 +- sample/Sample.Worker/Sample.Worker.csproj | 2 +- ...rgery.LaunchPad.Analyzers.roslyn4.0.csproj | 24 -- ...rgery.LaunchPad.Analyzers.roslyn4.4.csproj | 24 -- .../Composition/RestfulApiMethodBuilder.cs | 67 ++--- .../Composition/RestfulApiParameterMatcher.cs | 32 +-- .../ControllerActionBodyGenerator.cs | 33 +-- .../GraphqlMutationActionBodyGenerator.cs | 32 +-- ...raphqlOptionalPropertyTrackingGenerator.cs | 9 +- src/Analyzers/InheritFromGenerator.cs | 40 +-- .../Rocket.Surgery.LaunchPad.Analyzers.csproj | 23 -- src/Analyzers/SyntaxExtensions.cs | 11 +- ...Surgery.LaunchPad.AspNetCore.Blazor.csproj | 2 +- src/AspNetCore.Blazor/Validation.cs | 14 +- .../Conventions/NewtonsoftJsonConvention.cs | 7 +- ...LaunchPad.AspNetCore.NewtonsoftJson.csproj | 2 +- ...onProblemDetailsNewtonsoftJsonConverter.cs | 42 ++- ...urgery.LaunchPad.AspNetCore.Spatial.csproj | 2 +- src/AspNetCore.Testing/LaunchPadExtension.cs | 59 +--- .../LaunchPadWebAppFixture.cs | 2 +- ...urgery.LaunchPad.AspNetCore.Testing.csproj | 2 +- .../RestfulApiActionModelConvention.cs | 96 +++---- .../RestfulApiApplicationModelProvider.cs | 13 +- .../Composition/RestfulApiMethodBuilder.cs | 67 ++--- .../Composition/RestfulApiParameterMatcher.cs | 22 +- .../Conventions/AspNetCoreConvention.cs | 34 +-- ...CoreConventionInstrumentationConvention.cs | 25 +- .../Conventions/FluentValidationConvention.cs | 181 ++++++------ .../Conventions/ProblemDetailsConvention.cs | 92 +++--- .../Conventions/SwashbuckleConvention.cs | 32 +-- .../Conventions/SystemJsonTextConvention.cs | 7 +- .../Filters/SerilogLoggingPageFilter.cs | 15 +- src/AspNetCore/LaunchPadHelpers.cs | 13 +- src/AspNetCore/OpenApi/AuthorizeFilter.cs | 18 +- .../OpenApi/NodaTimeSwashbuckleExtensions.cs | 51 ++-- src/AspNetCore/OpenApi/OperationIdFilter.cs | 11 +- .../OpenApi/StronglyTypedIdSchemaFilter.cs | 4 +- src/AspNetCore/RestfulApiController.cs | 37 +-- ...Rocket.Surgery.LaunchPad.AspNetCore.csproj | 3 +- .../FluentValidationProblemDetails.cs | 16 +- .../ValidationProblemDetailsConverter.cs | 29 +- .../Validation/ValidatorInterceptor.cs | 6 +- ...t.Surgery.LaunchPad.EntityFramework.csproj | 2 +- .../SqliteDateTimeOffsetModelCreating.cs | 22 +- ...onsoftJsonCompositeNodaPatternConverter.cs | 8 +- ...LaunchPad.Foundation.NewtonsoftJson.csproj | 2 +- src/Foundation/Assigned.cs | 26 +- .../Conventions/FluentValidationConvention.cs | 37 ++- .../Conventions/InstrumentationConvention.cs | 21 +- .../Conventions/MediatRConvention.cs | 28 +- .../Conventions/NodaTimeConvention.cs | 7 +- src/Foundation/ExistingValueOptionsFactory.cs | 19 +- .../FluentValidationProblemDetail.cs | 9 +- src/Foundation/NodaTimeDestructuringPolicy.cs | 12 +- ...Rocket.Surgery.LaunchPad.Foundation.csproj | 2 +- .../Validation/StringInValidator.cs | 7 +- .../ValidationHealthCheckResults.cs | 19 +- .../Validation/ValidationPipelineBehavior.cs | 21 +- .../Conventions/SerilogFunctionsConvention.cs | 116 -------- src/Functions/LaunchPadFunctionStartup.cs | 132 --------- .../Rocket.Surgery.LaunchPad.Functions.csproj | 14 - src/Functions/RocketBooster.cs | 228 --------------- src/Grpc/Rocket.Surgery.LaunchPad.Grpc.csproj | 2 +- src/Grpc/Validation/ValidationInterceptor.cs | 19 +- .../EnvironmentLoggingConvention.cs | 4 +- .../Conventions/OpenTelemetryConvention.cs | 26 +- .../SerilogConsoleLoggingConvention.cs | 7 +- .../SerilogDebugLoggingConvention.cs | 9 +- .../Conventions/SerilogHostingConvention.cs | 51 ++-- .../Rocket.Surgery.LaunchPad.Hosting.csproj | 3 +- .../OpenTelemetryHostBuilderExtensions.cs | 35 --- .../RocketSurgeryOpenTelemetryExtensions.cs | 43 --- .../Conventions/GraphqlConvention.cs | 7 +- .../Conventions/InstrumentationConvention.cs | 14 +- src/HotChocolate/GraphqlErrorFilter.cs | 54 ++-- src/HotChocolate/GraphqlExtensions.cs | 45 +-- .../Helpers/IntToStructBaseType.cs | 31 +- .../Helpers/StringToClassBaseType.cs | 28 +- .../Helpers/StringToStructBaseType.cs | 28 +- .../NestedTypeNameTypeInterceptor.cs | 14 +- ...cket.Surgery.LaunchPad.HotChocolate.csproj | 2 +- .../CustomValidationMiddlewareInjector.cs | 115 ++------ .../Validation/ValidationMiddleware.cs | 18 +- .../AutoMapperNewtonsoftJsonConvention.cs | 7 +- ...ry.LaunchPad.Mapping.NewtonsoftJson.csproj | 2 +- src/Mapping/AutoMapperConvention.cs | 40 ++- .../AutoMapperHostBuilderExtensions.cs | 7 +- src/Mapping/OnlyDefinedPropertiesMethods.cs | 47 +--- .../Rocket.Surgery.LaunchPad.Mapping.csproj | 2 +- src/Metadata/GitVersion.cs | 200 ++++++++++--- src/Metadata/PrefixExtensions.cs | 4 +- .../Rocket.Surgery.LaunchPad.Metadata.csproj | 2 +- .../ConfigureOptionsLoggingConvention.cs | 11 +- ...rilogEnrichEnvironmentLoggingConvention.cs | 7 +- .../SerilogEnrichLoggingConvention.cs | 7 +- .../SerilogEnrichSpansConvention.cs | 9 +- .../SerilogReadFromConfigurationConvention.cs | 12 +- .../Rocket.Surgery.LaunchPad.Serilog.csproj | 2 +- src/Serilog/RocketSurgerySerilogExtensions.cs | 15 +- ...erilogAbstractionsHostBuilderExtensions.cs | 12 +- ...NetTopologySuiteSerializationExtensions.cs | 14 +- ...ry.LaunchPad.Spatial.NewtonsoftJson.csproj | 2 +- .../NetTopologySuiteDestructuringPolicy.cs | 52 ++-- ...teSystemTextJsonSerializationExtensions.cs | 14 +- .../Rocket.Surgery.LaunchPad.Spatial.csproj | 2 +- ...y.LaunchPad.StrawberryShake.Spatial.csproj | 2 +- ...t.Surgery.LaunchPad.StrawberryShake.csproj | 2 +- .../IOpenTelemetryAsyncConvention.cs | 22 ++ .../IOpenTelemetryConvention.cs} | 6 +- .../IOpenTelemetryMetricsConvention.cs | 39 +-- src/Telemetry/OpenTelemetryAsyncConvention.cs | 19 ++ .../OpenTelemetryConvention.cs} | 6 +- .../OpenTelemetryHostBuilderExtensions.cs | 57 ---- .../Rocket.Surgery.LaunchPad.Telemetry.csproj | 2 +- .../RocketSurgeryOpenTelemetryExtensions.cs | 135 +++++++-- src/Testing/FakeClockConvention.cs | 7 +- .../Rocket.Surgery.LaunchPad.Testing.csproj | 6 +- ...ocket.Surgery.LaunchPad.Web.Hosting.csproj | 4 +- .../Analyzers.Tests.roslyn4.0.csproj | 24 -- .../Analyzers.Tests.roslyn4.4.csproj | 24 -- .../Analyzers.Tests.roslyn4.6.csproj | 2 +- test/Analyzers.Tests/Analyzers.Tests.csproj | 2 +- test/Analyzers.Tests/GeneratorTest.cs | 6 +- ...lOptionalPropertyTrackingGeneratorTests.cs | 20 +- ...n_Using_InheritsFromGenerator.verified.txt | 1 - ...ropertyTracking=OtherAssembly.verified.txt | 1 - ...propertyTracking=SameAssembly.verified.txt | 1 - ...ropertyTracking=OtherAssembly.verified.txt | 1 - ...propertyTracking=SameAssembly.verified.txt | 1 - ...ropertyTracking=OtherAssembly.verified.txt | 1 - ...propertyTracking=SameAssembly.verified.txt | 1 - test/AspNetCore.Tests/AspNetCore.Tests.csproj | 2 +- test/Extensions.Tests/ConventionFakeTest.cs | 18 +- test/Extensions.Tests/Extensions.Tests.csproj | 2 +- .../FakeClockConventionTests.cs | 14 +- test/Extensions.Tests/FeatureFactory.cs | 52 ++-- .../Mapping/AutoMapperProfile.cs | 194 ++++++++++--- .../Extensions.Tests/Mapping/DurationTests.cs | 51 ++-- test/Extensions.Tests/Mapping/InstantTests.cs | 35 +-- .../Mapping/LocalDateTests.cs | 35 +-- .../Mapping/LocalDateTimeTests.cs | 31 +- .../Mapping/LocalTimeTests.cs | 55 ++-- .../Mapping/OffsetDateTimeTests.cs | 31 +- test/Extensions.Tests/Mapping/OffsetTests.cs | 11 +- test/Extensions.Tests/Mapping/PeriodTests.cs | 11 +- .../Mapping/TypeConverterTest.cs | 150 ++++------ test/Extensions.Tests/MediatRTests.cs | 61 ++-- .../StringInValidatorTests.cs | 33 ++- .../HealthCheckOptionsValidationTests.cs | 11 +- .../Validation/OptionsValidationTests.cs | 13 +- test/Functions.Tests/Functions.Tests.csproj | 9 - .../Functions.Tests/RocketHostBuilderTests.cs | 91 ------ test/Functions.Tests/TestAssemblyProvider.cs | 17 -- test/Metadata.Tests/Metadata.Tests.csproj | 2 +- .../Helpers/SqliteExtension.cs | 5 +- .../Helpers/TestWebAppFixture.cs | 2 +- .../Sample.BlazorServer.Tests.csproj | 2 +- .../HandleTestHostBase.cs | 32 ++- .../Helpers/SqliteExtension.cs | 7 +- .../Helpers/TestWebAppFixture.cs | 2 +- .../Sample.Classic.Restful.Tests.csproj | 2 +- .../Sample.Command.Tests.csproj | 2 +- test/Sample.Core.Tests/HandleTestHostBase.cs | 21 +- .../Sample.Core.Tests.csproj | 2 +- .../Helpers/SqliteExtension.cs | 9 +- test/Sample.Graphql.Tests/NamedSchemaTests.cs | 39 --- .../Sample.Graphql.Tests.csproj | 2 +- .../Helpers/SqliteExtension.cs | 9 +- .../Helpers/TestWebAppFixture.cs | 2 +- .../LaunchRecords/GetLaunchRecordTests.cs | 62 ++-- .../LaunchRecords/UpdateLaunchRecordTests.cs | 59 ++-- .../Sample.Grpc.Tests.csproj | 2 +- .../Helpers/SqliteExtension.cs | 7 +- .../Helpers/TestWebAppFixture.cs | 2 +- .../Sample.Pages.Tests.csproj | 2 +- .../Helpers/SqliteExtension.cs | 9 +- .../Sample.Restful.Tests.csproj | 2 +- .../Sample.Worker.Tests.csproj | 2 +- 230 files changed, 2096 insertions(+), 3976 deletions(-) delete mode 100644 sample/Sample.BlazorServer/Startup.cs delete mode 100644 sample/Sample.Classic.Restful/Startup.cs delete mode 100644 sample/Sample.Function/.gitignore delete mode 100644 sample/Sample.Function/.vscode/extensions.json delete mode 100644 sample/Sample.Function/LocalServices.cs delete mode 100644 sample/Sample.Function/Sample_Function.csproj delete mode 100644 sample/Sample.Function/Service.cs delete mode 100644 sample/Sample.Function/Startup.cs delete mode 100644 sample/Sample.Function/TestFunction.cs delete mode 100644 sample/Sample.Function/host.json delete mode 100644 sample/Sample.Grpc/Startup.cs delete mode 100644 sample/Sample.Pages/Startup.cs delete mode 100644 src/Analyzers.roslyn4.0/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.0.csproj delete mode 100644 src/Analyzers.roslyn4.4/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.4.csproj delete mode 100644 src/Functions/Conventions/SerilogFunctionsConvention.cs delete mode 100644 src/Functions/LaunchPadFunctionStartup.cs delete mode 100644 src/Functions/Rocket.Surgery.LaunchPad.Functions.csproj delete mode 100644 src/Functions/RocketBooster.cs delete mode 100644 src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs delete mode 100644 src/Hosting/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs create mode 100644 src/Telemetry/IOpenTelemetryAsyncConvention.cs rename src/{Hosting/Telemetry/IOpenTelemetryMetricsConvention.cs => Telemetry/IOpenTelemetryConvention.cs} (83%) create mode 100644 src/Telemetry/OpenTelemetryAsyncConvention.cs rename src/{Hosting/Telemetry/OpenTelemetryMetricsConvention.cs => Telemetry/OpenTelemetryConvention.cs} (63%) delete mode 100644 src/Telemetry/OpenTelemetryHostBuilderExtensions.cs delete mode 100644 test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj delete mode 100644 test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj delete mode 100644 test/Functions.Tests/Functions.Tests.csproj delete mode 100644 test/Functions.Tests/RocketHostBuilderTests.cs delete mode 100644 test/Functions.Tests/TestAssemblyProvider.cs delete mode 100644 test/Sample.Graphql.Tests/NamedSchemaTests.cs diff --git a/.build/.build.csproj b/.build/.build.csproj index 38e96b159..fa011d8f5 100644 --- a/.build/.build.csproj +++ b/.build/.build.csproj @@ -2,7 +2,7 @@ Exe - net6.0 + net8.0 false False diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index a016b17fe..0c468f1b1 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -31,7 +31,7 @@ "commands": ["docfx"] }, "strawberryshake.tools": { - "version": "14.0.0-p.85", + "version": "14.0.0-p.90", "commands": ["dotnet-graphql"] }, "dotnet-outdated-tool": { diff --git a/Directory.Build.props b/Directory.Build.props index da92d5301..8032e32e0 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -17,7 +17,7 @@ 1 true enable - true + true false $(NoWarn);0436;CA1014;CA1062 latest diff --git a/Directory.Build.targets b/Directory.Build.targets index ec49c280f..0bef46cd9 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -23,11 +23,11 @@ PrivateAssets="All" Condition="'$(MSBuildProjectName)'!='.build'" /> + --> - --> diff --git a/Directory.Packages.props b/Directory.Packages.props index d10942b64..baa16c0fb 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -32,27 +32,27 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + @@ -91,18 +91,16 @@ - - - - - - + + + + + + - - - - + + diff --git a/Directory.Packages.support.props b/Directory.Packages.support.props index bbb08c998..d3a7398af 100644 --- a/Directory.Packages.support.props +++ b/Directory.Packages.support.props @@ -3,13 +3,4 @@ - - - - - - - - - diff --git a/LaunchPad.sln b/LaunchPad.sln index 2df550346..a2e9a05b9 100644 --- a/LaunchPad.sln +++ b/LaunchPad.sln @@ -104,12 +104,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.Me EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Metadata.Tests", "test\Metadata.Tests\Metadata.Tests.csproj", "{082F2EB5-93BE-4C71-B468-8A81A45A6BD7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.Functions", "src\Functions\Rocket.Surgery.LaunchPad.Functions.csproj", "{90DD3DB0-0304-4D79-A249-09E123BBC1E4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Functions.Tests", "test\Functions.Tests\Functions.Tests.csproj", "{3DC043AE-557B-4D07-85F2-2913E446C808}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample_Function", "sample\Sample.Function\Sample_Function.csproj", "{041A8889-1B35-4BFD-B146-9DA7CB99DAF1}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.Grpc", "src\Grpc\Rocket.Surgery.LaunchPad.Grpc.csproj", "{7A012ECC-B3E9-4A0B-96BB-EA87DE6EECA8}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.AspNetCore.Blazor", "src\AspNetCore.Blazor\Rocket.Surgery.LaunchPad.AspNetCore.Blazor.csproj", "{EB665FF0-13EA-489A-A2B9-E8220B223A7C}" @@ -152,14 +146,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.Classic.Restful.Test EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.Telemetry", "src\Telemetry\Rocket.Surgery.LaunchPad.Telemetry.csproj", "{9700269F-7954-49DE-8096-D5A941A2F4D0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.Analyzers.roslyn4.0", "src\Analyzers.roslyn4.0\Rocket.Surgery.LaunchPad.Analyzers.roslyn4.0.csproj", "{375E9FDB-C768-4EF4-9DCB-554B969D5944}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.Analyzers.roslyn4.4", "src\Analyzers.roslyn4.4\Rocket.Surgery.LaunchPad.Analyzers.roslyn4.4.csproj", "{27AAD3E0-1690-455F-9348-6847E22BC07E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Analyzers.Tests.roslyn4.0", "test\Analyzers.Tests.roslyn4.0\Analyzers.Tests.roslyn4.0.csproj", "{A0C6C503-4448-490E-9C52-FAB2F15A62D0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Analyzers.Tests.roslyn4.4", "test\Analyzers.Tests.roslyn4.4\Analyzers.Tests.roslyn4.4.csproj", "{6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.StrawberryShake", "src\StrawberryShake\Rocket.Surgery.LaunchPad.StrawberryShake.csproj", "{0DD3D13C-BB79-4222-B4E0-2B824C6BA4E8}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rocket.Surgery.LaunchPad.StrawberryShake.Spatial", "src\StrawberryShake.Spatial\Rocket.Surgery.LaunchPad.StrawberryShake.Spatial.csproj", "{4A176BF2-DC9D-4D6B-8F36-B672273CF09B}" @@ -516,42 +502,6 @@ Global {082F2EB5-93BE-4C71-B468-8A81A45A6BD7}.Release|x64.Build.0 = Release|Any CPU {082F2EB5-93BE-4C71-B468-8A81A45A6BD7}.Release|x86.ActiveCfg = Release|Any CPU {082F2EB5-93BE-4C71-B468-8A81A45A6BD7}.Release|x86.Build.0 = Release|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Debug|x64.ActiveCfg = Debug|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Debug|x64.Build.0 = Debug|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Debug|x86.ActiveCfg = Debug|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Debug|x86.Build.0 = Debug|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Release|Any CPU.Build.0 = Release|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Release|x64.ActiveCfg = Release|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Release|x64.Build.0 = Release|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Release|x86.ActiveCfg = Release|Any CPU - {90DD3DB0-0304-4D79-A249-09E123BBC1E4}.Release|x86.Build.0 = Release|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Debug|x64.ActiveCfg = Debug|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Debug|x64.Build.0 = Debug|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Debug|x86.ActiveCfg = Debug|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Debug|x86.Build.0 = Debug|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Release|Any CPU.Build.0 = Release|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Release|x64.ActiveCfg = Release|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Release|x64.Build.0 = Release|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Release|x86.ActiveCfg = Release|Any CPU - {3DC043AE-557B-4D07-85F2-2913E446C808}.Release|x86.Build.0 = Release|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Debug|x64.ActiveCfg = Debug|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Debug|x64.Build.0 = Debug|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Debug|x86.ActiveCfg = Debug|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Debug|x86.Build.0 = Debug|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Release|Any CPU.Build.0 = Release|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Release|x64.ActiveCfg = Release|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Release|x64.Build.0 = Release|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Release|x86.ActiveCfg = Release|Any CPU - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1}.Release|x86.Build.0 = Release|Any CPU {7A012ECC-B3E9-4A0B-96BB-EA87DE6EECA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7A012ECC-B3E9-4A0B-96BB-EA87DE6EECA8}.Debug|Any CPU.Build.0 = Debug|Any CPU {7A012ECC-B3E9-4A0B-96BB-EA87DE6EECA8}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -804,54 +754,6 @@ Global {9700269F-7954-49DE-8096-D5A941A2F4D0}.Release|x64.Build.0 = Release|Any CPU {9700269F-7954-49DE-8096-D5A941A2F4D0}.Release|x86.ActiveCfg = Release|Any CPU {9700269F-7954-49DE-8096-D5A941A2F4D0}.Release|x86.Build.0 = Release|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Debug|Any CPU.Build.0 = Debug|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Debug|x64.ActiveCfg = Debug|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Debug|x64.Build.0 = Debug|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Debug|x86.ActiveCfg = Debug|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Debug|x86.Build.0 = Debug|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Release|Any CPU.ActiveCfg = Release|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Release|Any CPU.Build.0 = Release|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Release|x64.ActiveCfg = Release|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Release|x64.Build.0 = Release|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Release|x86.ActiveCfg = Release|Any CPU - {375E9FDB-C768-4EF4-9DCB-554B969D5944}.Release|x86.Build.0 = Release|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Debug|x64.ActiveCfg = Debug|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Debug|x64.Build.0 = Debug|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Debug|x86.ActiveCfg = Debug|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Debug|x86.Build.0 = Debug|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Release|Any CPU.Build.0 = Release|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Release|x64.ActiveCfg = Release|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Release|x64.Build.0 = Release|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Release|x86.ActiveCfg = Release|Any CPU - {27AAD3E0-1690-455F-9348-6847E22BC07E}.Release|x86.Build.0 = Release|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Debug|x64.ActiveCfg = Debug|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Debug|x64.Build.0 = Debug|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Debug|x86.ActiveCfg = Debug|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Debug|x86.Build.0 = Debug|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Release|Any CPU.Build.0 = Release|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Release|x64.ActiveCfg = Release|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Release|x64.Build.0 = Release|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Release|x86.ActiveCfg = Release|Any CPU - {A0C6C503-4448-490E-9C52-FAB2F15A62D0}.Release|x86.Build.0 = Release|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Debug|x64.ActiveCfg = Debug|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Debug|x64.Build.0 = Debug|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Debug|x86.ActiveCfg = Debug|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Debug|x86.Build.0 = Debug|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Release|Any CPU.Build.0 = Release|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Release|x64.ActiveCfg = Release|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Release|x64.Build.0 = Release|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Release|x86.ActiveCfg = Release|Any CPU - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D}.Release|x86.Build.0 = Release|Any CPU {0DD3D13C-BB79-4222-B4E0-2B824C6BA4E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0DD3D13C-BB79-4222-B4E0-2B824C6BA4E8}.Debug|Any CPU.Build.0 = Debug|Any CPU {0DD3D13C-BB79-4222-B4E0-2B824C6BA4E8}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -931,9 +833,6 @@ Global {7B5B74FF-F8AB-4690-8A57-3D8E10678D91} = {DF33E0FB-9790-4654-B60F-8AB22E0CC3D1} {BFB85E25-9351-43E8-B3C2-199009CE23FA} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} {082F2EB5-93BE-4C71-B468-8A81A45A6BD7} = {DF33E0FB-9790-4654-B60F-8AB22E0CC3D1} - {90DD3DB0-0304-4D79-A249-09E123BBC1E4} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} - {3DC043AE-557B-4D07-85F2-2913E446C808} = {DF33E0FB-9790-4654-B60F-8AB22E0CC3D1} - {041A8889-1B35-4BFD-B146-9DA7CB99DAF1} = {5D11C19B-E8E4-4CE3-9C8A-1D368578EBCB} {7A012ECC-B3E9-4A0B-96BB-EA87DE6EECA8} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} {EB665FF0-13EA-489A-A2B9-E8220B223A7C} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} {05E51CB7-2C57-4627-B57A-032714CEB21E} = {5D11C19B-E8E4-4CE3-9C8A-1D368578EBCB} @@ -955,10 +854,6 @@ Global {2C09FAF6-434D-442F-94B2-02AB906B477C} = {5D11C19B-E8E4-4CE3-9C8A-1D368578EBCB} {2EF6A468-3689-4407-8A11-2E3F5DEDAC0A} = {DF33E0FB-9790-4654-B60F-8AB22E0CC3D1} {9700269F-7954-49DE-8096-D5A941A2F4D0} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} - {375E9FDB-C768-4EF4-9DCB-554B969D5944} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} - {27AAD3E0-1690-455F-9348-6847E22BC07E} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} - {A0C6C503-4448-490E-9C52-FAB2F15A62D0} = {DF33E0FB-9790-4654-B60F-8AB22E0CC3D1} - {6A8FB8CA-6BB5-4A51-B38E-AA5BBBFA636D} = {DF33E0FB-9790-4654-B60F-8AB22E0CC3D1} {0DD3D13C-BB79-4222-B4E0-2B824C6BA4E8} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} {4A176BF2-DC9D-4D6B-8F36-B672273CF09B} = {8FFDF555-DB50-45F9-9A2D-6410F39151C3} {C3A456FA-D2FE-4109-8DC3-E8191F878C1E} = {D65A8130-6A58-4693-A96C-8C1DFA3CA355} diff --git a/Readme.md b/Readme.md index 53d535533..ff1d42b4c 100644 --- a/Readme.md +++ b/Readme.md @@ -29,7 +29,6 @@ A common set of libraries used to build console and web applications. | Rocket.Surgery.LaunchPad.EntityFramework | [![nuget-version-nutptsm/tbya-badge]![nuget-downloads-nutptsm/tbya-badge]][nuget-nutptsm/tbya] | | Rocket.Surgery.LaunchPad.Foundation | [![nuget-version-kb2xyygxvala-badge]![nuget-downloads-kb2xyygxvala-badge]][nuget-kb2xyygxvala] | | Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson | [![nuget-version-m0yumfedtfoa-badge]![nuget-downloads-m0yumfedtfoa-badge]][nuget-m0yumfedtfoa] | -| Rocket.Surgery.LaunchPad.Functions | [![nuget-version-hllqtixjuvag-badge]![nuget-downloads-hllqtixjuvag-badge]][nuget-hllqtixjuvag] | | Rocket.Surgery.LaunchPad.Grpc | [![nuget-version-auwnvpy8f+6g-badge]![nuget-downloads-auwnvpy8f+6g-badge]][nuget-auwnvpy8f+6g] | | Rocket.Surgery.LaunchPad.Hosting | [![nuget-version-w/tyeoj0dncw-badge]![nuget-downloads-w/tyeoj0dncw-badge]][nuget-w/tyeoj0dncw] | | Rocket.Surgery.LaunchPad.HotChocolate | [![nuget-version-ozd3tvimwvrq-badge]![nuget-downloads-ozd3tvimwvrq-badge]][nuget-ozd3tvimwvrq] | @@ -87,9 +86,6 @@ TBD [nuget-m0yumfedtfoa]: https://www.nuget.org/packages/Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson/ [nuget-version-m0yumfedtfoa-badge]: https://img.shields.io/nuget/v/Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" [nuget-downloads-m0yumfedtfoa-badge]: https://img.shields.io/nuget/dt/Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" -[nuget-hllqtixjuvag]: https://www.nuget.org/packages/Rocket.Surgery.LaunchPad.Functions/ -[nuget-version-hllqtixjuvag-badge]: https://img.shields.io/nuget/v/Rocket.Surgery.LaunchPad.Functions.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" -[nuget-downloads-hllqtixjuvag-badge]: https://img.shields.io/nuget/dt/Rocket.Surgery.LaunchPad.Functions.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" [nuget-auwnvpy8f+6g]: https://www.nuget.org/packages/Rocket.Surgery.LaunchPad.Grpc/ [nuget-version-auwnvpy8f+6g-badge]: https://img.shields.io/nuget/v/Rocket.Surgery.LaunchPad.Grpc.svg?color=004880&logo=nuget&style=flat-square "NuGet Version" [nuget-downloads-auwnvpy8f+6g-badge]: https://img.shields.io/nuget/dt/Rocket.Surgery.LaunchPad.Grpc.svg?color=004880&logo=nuget&style=flat-square "NuGet Downloads" diff --git a/sample/Sample.BlazorServer/Program.cs b/sample/Sample.BlazorServer/Program.cs index 8ae40cc9a..16071cc9c 100644 --- a/sample/Sample.BlazorServer/Program.cs +++ b/sample/Sample.BlazorServer/Program.cs @@ -1,21 +1,39 @@ -using Microsoft.Extensions.DependencyModel; +using System.Runtime.Loader; using Rocket.Surgery.Conventions; using Rocket.Surgery.Hosting; +using Rocket.Surgery.LaunchPad.AspNetCore; +using Sample.BlazorServer; +using Sample.BlazorServer.Data; -namespace Sample.BlazorServer; +var builder = WebApplication.CreateBuilder(args); -[ImportConventions] -public static partial class Program +builder.Services.AddRazorPages(); +builder.Services.AddServerSideBlazor(); +builder.Services.AddSingleton(); + +var app = await builder.LaunchWith(RocketBooster.For(Imports.Instance), b => b.Set(AssemblyLoadContext.Default)); + +if (builder.Environment.IsDevelopment()) { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) - { - return Host.CreateDefaultBuilder(args) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)) - .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()); - } + app.UseDeveloperExceptionPage(); } +else +{ + app.UseExceptionHandler("/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); + +app.UseLaunchPadRequestLogging(); + +app.UseRouting(); + +app.MapBlazorHub(); +app.MapFallbackToPage("/_Host"); + +await app.RunAsync(); + +public partial class Program; \ No newline at end of file diff --git a/sample/Sample.BlazorServer/Sample.BlazorServer.csproj b/sample/Sample.BlazorServer/Sample.BlazorServer.csproj index 99996128b..f786c2c18 100644 --- a/sample/Sample.BlazorServer/Sample.BlazorServer.csproj +++ b/sample/Sample.BlazorServer/Sample.BlazorServer.csproj @@ -1,7 +1,7 @@ - net8.0 + net8.0 diff --git a/sample/Sample.BlazorServer/Startup.cs b/sample/Sample.BlazorServer/Startup.cs deleted file mode 100644 index f201ea493..000000000 --- a/sample/Sample.BlazorServer/Startup.cs +++ /dev/null @@ -1,48 +0,0 @@ -using Rocket.Surgery.LaunchPad.AspNetCore; -using Sample.BlazorServer.Data; - -namespace Sample.BlazorServer; - -public class Startup(IConfiguration configuration) -{ - 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 - public void ConfigureServices(IServiceCollection services) - { - services.AddRazorPages(); - services.AddServerSideBlazor(); - services.AddSingleton(); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler("/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); - } - - app.UseHttpsRedirection(); - app.UseStaticFiles(); - - app.UseLaunchPadRequestLogging(); - - app.UseRouting(); - - app.UseEndpoints( - endpoints => - { - endpoints.MapBlazorHub(); - endpoints.MapFallbackToPage("/_Host"); - } - ); - } -} diff --git a/sample/Sample.BlazorWasm/Program.cs b/sample/Sample.BlazorWasm/Program.cs index c8bc44e5e..fa68ebcdd 100644 --- a/sample/Sample.BlazorWasm/Program.cs +++ b/sample/Sample.BlazorWasm/Program.cs @@ -1,25 +1,15 @@ using FluentValidation; using MediatR; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; -using Rocket.Surgery.Conventions; using Rocket.Surgery.WebAssembly.Hosting; +using Sample.BlazorWasm; -namespace Sample.BlazorWasm; +var builder = WebAssemblyHostBuilder.CreateDefault(args); -[ImportConventions] -public static partial class Program -{ - public static async Task Main(string[] args) - { - var builder = await WebAssemblyHostBuilder.CreateDefault(args) - .ConfigureRocketSurgery(AppDomain.CurrentDomain, GetConventions) - ; - builder.RootComponents.Add("app"); - builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); +builder.RootComponents.Add("app"); +builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new(builder.HostEnvironment.BaseAddress), }); - await builder.Build().RunAsync(); - } -} +await ( await builder.ConfigureRocketSurgery(Imports.Instance) ).RunAsync(); public static class TestHandler { @@ -66,6 +56,4 @@ public Task Handle(Request request, CancellationToken cancellationToke ); } } -} - - +} \ No newline at end of file diff --git a/sample/Sample.BlazorWasm/Sample.BlazorWasm.csproj b/sample/Sample.BlazorWasm/Sample.BlazorWasm.csproj index 9e032a8f1..67f02bddd 100644 --- a/sample/Sample.BlazorWasm/Sample.BlazorWasm.csproj +++ b/sample/Sample.BlazorWasm/Sample.BlazorWasm.csproj @@ -2,6 +2,7 @@ net8.0-browser false + true diff --git a/sample/Sample.Classic.Restful/Program.cs b/sample/Sample.Classic.Restful/Program.cs index d8e3a450b..cc6378eef 100644 --- a/sample/Sample.Classic.Restful/Program.cs +++ b/sample/Sample.Classic.Restful/Program.cs @@ -1,22 +1,45 @@ -using Microsoft.Extensions.DependencyModel; +using System.Reflection; +using System.Runtime.Loader; +using Hellang.Middleware.ProblemDetails; +using Rocket.Surgery.Conventions; using Rocket.Surgery.Hosting; +using Rocket.Surgery.LaunchPad.AspNetCore; +using Sample.Classic.Restful; +using Swashbuckle.AspNetCore.SwaggerGen; -namespace Sample.Classic.Restful; - -/// -/// Startup interop (here for testing only or for 3.1 support) -/// -public static partial class Program -{ - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) - { - return Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(Imports.GetConventions)); - } -} +var builder = WebApplication + .CreateBuilder(args); +builder.Services.AddControllers().AddControllersAsServices(); +builder.Services + .Configure( + c => c.SwaggerDoc( + "v1", + new() + { + Version = typeof(Program).GetCustomAttribute()?.Version + ?? typeof(Program).GetCustomAttribute()?.Version ?? "0.1.0", + Title = "Test Application", + } + ) + ); +var app = await builder.LaunchWith(RocketBooster.For(Imports.Instance), b => b.Set(AssemblyLoadContext.Default)); + +app.UseProblemDetails(); +app.UseHttpsRedirection(); + +app.UseLaunchPadRequestLogging(); + +app.UseRouting(); + +app + .UseSwaggerUI() + .UseReDoc(); + +app.UseAuthorization(); + +app.MapControllers(); +app.MapSwagger(); + +await app.RunAsync(); + +public partial class Program; \ No newline at end of file diff --git a/sample/Sample.Classic.Restful/Sample.Classic.Restful.csproj b/sample/Sample.Classic.Restful/Sample.Classic.Restful.csproj index 5656286eb..21c54008e 100644 --- a/sample/Sample.Classic.Restful/Sample.Classic.Restful.csproj +++ b/sample/Sample.Classic.Restful/Sample.Classic.Restful.csproj @@ -1,6 +1,6 @@ - net8.0 + net8.0 true true true diff --git a/sample/Sample.Classic.Restful/Startup.cs b/sample/Sample.Classic.Restful/Startup.cs deleted file mode 100644 index eea22f851..000000000 --- a/sample/Sample.Classic.Restful/Startup.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Reflection; -using Hellang.Middleware.ProblemDetails; -using Microsoft.OpenApi.Models; -using Rocket.Surgery.LaunchPad.AspNetCore; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Sample.Classic.Restful; - -/// -/// Startup interop (here for testing only or for 3.1 support) -/// -public class Startup(IConfiguration configuration) -{ - 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) - { - services.AddControllers().AddControllersAsServices(); - services - .Configure( - c => c.SwaggerDoc( - "v1", - new OpenApiInfo - { - Version = typeof(Startup).GetCustomAttribute()?.Version - ?? typeof(Startup).GetCustomAttribute()?.Version ?? "0.1.0", - Title = "Test Application", - } - ) - ); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.UseProblemDetails(); - app.UseHttpsRedirection(); - - app.UseLaunchPadRequestLogging(); - - app.UseRouting(); - - app - .UseSwaggerUI() - .UseReDoc(); - - app.UseAuthorization(); - - app.UseEndpoints( - endpoints => - { - endpoints.MapControllers(); - - endpoints.MapSwagger(); - } - ); - } -} diff --git a/sample/Sample.Command/Program.cs b/sample/Sample.Command/Program.cs index 452ae4b3e..a44b68089 100644 --- a/sample/Sample.Command/Program.cs +++ b/sample/Sample.Command/Program.cs @@ -2,30 +2,30 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Rocket.Surgery.CommandLine; using Rocket.Surgery.Conventions; -using Rocket.Surgery.Conventions.CommandLine; using Rocket.Surgery.Hosting; using Sample.Command; using Spectre.Console.Cli; -[assembly: ImportConventions(Namespace = "Sample.Command")] +var builder = Host.CreateApplicationBuilder(args); -await Host.CreateDefaultBuilder(args) - .LaunchWith( - RocketBooster.For(Imports.GetConventions), - builder => builder.SetDefaultCommand() - .ConfigureLogging(z => z.AddConsole()) - .UseDryIoc() - .ConfigureDryIoc( - x => - { - x.Use(new InstanceThing()); - x.Register(Reuse.Singleton); - } - ) - .ConfigureCommandLine((_, app) => app.AddCommand("dump")) - ) - .RunAsync(); +var host = await builder.LaunchWith( + RocketBooster.For(Imports.Instance), + b => b + .SetDefaultCommand() + .ConfigureLogging(z => z.AddConsole()) + .UseDryIoc() + .ConfigureDryIoc( + x => + { + x.Use(new InstanceThing()); + x.Register(Reuse.Singleton); + } + ) + .ConfigureCommandLine((_, app) => app.AddCommand("dump")) +); +await host.RunAsync(); public class InstanceThing { @@ -57,4 +57,4 @@ public override int Execute([NotNull] CommandContext context, [NotNull] AppSetti logger.LogInformation("Test"); return 1; } -} +} \ No newline at end of file diff --git a/sample/Sample.Command/Sample.Command.csproj b/sample/Sample.Command/Sample.Command.csproj index 71ccb34a0..8d749aad6 100644 --- a/sample/Sample.Command/Sample.Command.csproj +++ b/sample/Sample.Command/Sample.Command.csproj @@ -1,13 +1,14 @@ Exe - net8.0 + net8.0 + diff --git a/sample/Sample.Core/Domain/RocketDbContext.cs b/sample/Sample.Core/Domain/RocketDbContext.cs index 662ce13d5..cd5aa3013 100644 --- a/sample/Sample.Core/Domain/RocketDbContext.cs +++ b/sample/Sample.Core/Domain/RocketDbContext.cs @@ -11,7 +11,7 @@ namespace Sample.Core.Domain; public DbSet Rockets { get; set; } = null!; public DbSet LaunchRecords { get; set; } = null!; -#if NET6_0_OR_GREATER + #if NET6_0_OR_GREATER protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { configurationBuilder @@ -21,7 +21,7 @@ protected override void ConfigureConventions(ModelConfigurationBuilder configura .Properties() .HaveConversion(); } -#endif + #endif } public class StronglyTypedIdValueConverterSelector(ValueConverterSelectorDependencies dependencies) : ValueConverterSelector(dependencies) @@ -29,17 +29,13 @@ public class StronglyTypedIdValueConverterSelector(ValueConverterSelectorDepende [return: NotNullIfNotNull("type")] private static Type? UnwrapNullableType(Type? type) { - if (type is null) - { - return null; - } + if (type is null) return null; return Nullable.GetUnderlyingType(type) ?? type; } // The dictionary in the base type is private, so we need our own one here. - private readonly ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo> _converters - = new ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo>(); + private readonly ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo> _converters = new(); public override IEnumerable Select(Type modelClrType, Type? providerClrType = null) { @@ -60,7 +56,6 @@ public override IEnumerable Select(Type modelClrType, Type? var converterType = underlyingModelType.GetNestedType("EfCoreValueConverter"); if (converterType != null) - { yield return _converters.GetOrAdd( ( underlyingModelType, typeof(Guid) ), _ => @@ -70,10 +65,9 @@ public override IEnumerable Select(Type modelClrType, Type? info => (ValueConverter)Activator.CreateInstance(converterType, info.MappingHints)!; // Build the info for our strongly-typed ID => Guid converter - return new ValueConverterInfo(modelClrType, typeof(Guid), factory); + return new(modelClrType, typeof(Guid), factory); } ); - } } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs index 4e56a79ee..c0131a9be 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/CreateLaunchRecord.cs @@ -97,21 +97,18 @@ public async Task Handle(Request request, CancellationToken cancellati { var record = mapper.Map(request); - var rocket = await dbContext.Rockets.FindAsync(new object[] { request.RocketId }, cancellationToken); - if (rocket == null) - { - throw new RequestFailedException("Rocket not found!"); - } + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.RocketId, }, cancellationToken); + if (rocket == null) throw new RequestFailedException("Rocket not found!"); record.Rocket = rocket; await dbContext.AddAsync(record, cancellationToken).ConfigureAwait(false); await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return new Response + return new() { - Id = record.Id + Id = record.Id, }; } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs index 00497661d..72c0ce680 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/DeleteLaunchRecord.cs @@ -36,20 +36,15 @@ private class Handler(RocketDbContext dbContext) : IRequestHandler { public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await dbContext.LaunchRecords.FindAsync(new object[] { request.Id }, cancellationToken); - if (rocket == null) - { - throw new NotFoundException(); - } + var rocket = await dbContext.LaunchRecords.FindAsync(new object[] { request.Id, }, cancellationToken); + if (rocket == null) throw new NotFoundException(); // contrived for testing - if (rocket.Id == new LaunchRecordId(new Guid("bad361de-a6d5-425a-9cf6-f9b2dd236be6"))) - { + if (rocket.Id == new LaunchRecordId(new("bad361de-a6d5-425a-9cf6-f9b2dd236be6"))) throw new NotAuthorizedException("Unable to operate on given record"); - } dbContext.Remove(rocket); await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs index 2659881a0..ae1edb9d7 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/EditLaunchRecord.cs @@ -110,10 +110,7 @@ private async Task GetLaunchRecord(LaunchRecordId id, Cancellation .Include(z => z.Rocket) .FirstOrDefaultAsync(z => z.Id == id, cancellationToken) .ConfigureAwait(false); - if (rocket == null) - { - throw new NotFoundException(); - } + if (rocket == null) throw new NotFoundException(); return rocket; } diff --git a/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs b/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs index 7c51216e4..6037f6177 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/GetLaunchRecord.cs @@ -36,15 +36,13 @@ private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandl { public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await dbContext.LaunchRecords - .Include(x => x.Rocket) - .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken); - if (rocket == null) - { - throw new NotFoundException(); - } + var rocket = await dbContext + .LaunchRecords + .Include(x => x.Rocket) + .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken); + if (rocket == null) throw new NotFoundException(); return mapper.Map(rocket); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs b/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs index f89c8a043..4c7432906 100644 --- a/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs +++ b/sample/Sample.Core/Operations/LaunchRecords/ListLaunchRecords.cs @@ -24,17 +24,15 @@ private class Handler(RocketDbContext dbContext, IMapper mapper) : IStreamReques { public IAsyncEnumerable Handle(Request request, CancellationToken cancellationToken) { - var query = dbContext.LaunchRecords - .Include(x => x.Rocket) - .AsQueryable(); - if (request.RocketType.HasValue) - { - query = query.Where(z => z.Rocket.Type == request.RocketType); - } + var query = dbContext + .LaunchRecords + .Include(x => x.Rocket) + .AsQueryable(); + if (request.RocketType.HasValue) query = query.Where(z => z.Rocket.Type == request.RocketType); return query .ProjectTo(mapper.ConfigurationProvider) .ToAsyncEnumerable(); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/Rockets/CreateRocket.cs b/sample/Sample.Core/Operations/Rockets/CreateRocket.cs index 0b979c1a1..067cdac94 100644 --- a/sample/Sample.Core/Operations/Rockets/CreateRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/CreateRocket.cs @@ -67,10 +67,10 @@ private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandl { public async Task Handle(Request request, CancellationToken cancellationToken) { - var existingRocket = await dbContext.Rockets.AsQueryable() - .FirstOrDefaultAsync(z => z.SerialNumber == request.SerialNumber, cancellationToken); + var existingRocket = await dbContext + .Rockets.AsQueryable() + .FirstOrDefaultAsync(z => z.SerialNumber == request.SerialNumber, cancellationToken); if (existingRocket != null) - { throw new RequestFailedException("A Rocket already exists with that serial number!") { Title = "Rocket Creation Failed", @@ -80,20 +80,19 @@ public async Task Handle(Request request, CancellationToken cancellati { id = existingRocket.Id, type = existingRocket.Type, - sn = existingRocket.SerialNumber - } - } + sn = existingRocket.SerialNumber, + }, + }, }; - } var rocket = mapper.Map(request); await dbContext.AddAsync(rocket, cancellationToken).ConfigureAwait(false); await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - return new Response + return new() { - Id = rocket.Id + Id = rocket.Id, }; } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs b/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs index 756bda824..54baf0931 100644 --- a/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/DeleteRocket.cs @@ -34,14 +34,11 @@ private class Handler(RocketDbContext dbContext) : IRequestHandler { public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); - if (rocket == null) - { - throw new NotFoundException(); - } + 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); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/Rockets/EditRocket.cs b/sample/Sample.Core/Operations/Rockets/EditRocket.cs index 3c2290be1..299df5e23 100644 --- a/sample/Sample.Core/Operations/Rockets/EditRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/EditRocket.cs @@ -77,12 +77,10 @@ private class RequestHandler(RocketDbContext dbContext, IMapper mapper, IMediato { private async Task GetRocket(RocketId id, CancellationToken cancellationToken) { - var rocket = await dbContext.Rockets.FindAsync(new object[] { id }, cancellationToken) - .ConfigureAwait(false); - if (rocket == null) - { - throw new NotFoundException(); - } + var rocket = await dbContext + .Rockets.FindAsync(new object[] { id, }, cancellationToken) + .ConfigureAwait(false); + if (rocket == null) throw new NotFoundException(); return rocket; } @@ -96,10 +94,7 @@ protected override async Task GetRequest(PatchRequest patchRequest, Can public async Task Handle(Request request, CancellationToken cancellationToken) { var rocket = await GetRocket(request.Id, cancellationToken); - if (rocket == null) - { - throw new NotFoundException(); - } + if (rocket == null) throw new NotFoundException(); mapper.Map(request, rocket); dbContext.Update(rocket); @@ -108,4 +103,4 @@ public async Task Handle(Request request, CancellationToken cancell return mapper.Map(rocket); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/Rockets/GetRocket.cs b/sample/Sample.Core/Operations/Rockets/GetRocket.cs index c2e40291f..78acba39a 100644 --- a/sample/Sample.Core/Operations/Rockets/GetRocket.cs +++ b/sample/Sample.Core/Operations/Rockets/GetRocket.cs @@ -35,13 +35,10 @@ private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandl { public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken).ConfigureAwait(false); - if (rocket == null) - { - throw new NotFoundException(); - } + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id, }, cancellationToken).ConfigureAwait(false); + if (rocket == null) throw new NotFoundException(); return mapper.Map(rocket); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs index 6c6cf7bae..6e9302883 100644 --- a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs +++ b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecord.cs @@ -40,19 +40,13 @@ private class Handler(RocketDbContext dbContext, IMapper mapper) : IRequestHandl { public async Task Handle(Request request, CancellationToken cancellationToken) { - var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); - if (rocket == null) - { - throw new NotFoundException(); - } + 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); - if (launchRecord == null) - { - throw new NotFoundException(); - } + var launchRecord = await dbContext.LaunchRecords.FindAsync(new object[] { request.LaunchRecordId, }, cancellationToken); + if (launchRecord == null) throw new NotFoundException(); return mapper.Map(launchRecord); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs index 64426958b..b46858863 100644 --- a/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs +++ b/sample/Sample.Core/Operations/Rockets/GetRocketLaunchRecords.cs @@ -35,19 +35,17 @@ private class Handler(RocketDbContext dbContext, IMapper mapper) : IStreamReques { public async IAsyncEnumerable Handle(Request request, [EnumeratorCancellation] CancellationToken cancellationToken) { - var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id }, cancellationToken); - if (rocket == null) - { - throw new NotFoundException(); - } + var rocket = await dbContext.Rockets.FindAsync(new object[] { request.Id, }, cancellationToken); + if (rocket == null) throw new NotFoundException(); - var query = dbContext.LaunchRecords.AsQueryable() - .Where(z => z.RocketId == rocket.Id) - .ProjectTo(mapper.ConfigurationProvider); + var query = dbContext + .LaunchRecords.AsQueryable() + .Where(z => z.RocketId == rocket.Id) + .ProjectTo(mapper.ConfigurationProvider); await foreach (var item in query.AsAsyncEnumerable().WithCancellation(cancellationToken)) { yield return item; } } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Operations/Rockets/ListRockets.cs b/sample/Sample.Core/Operations/Rockets/ListRockets.cs index 3e1a2ba93..e61b459cb 100644 --- a/sample/Sample.Core/Operations/Rockets/ListRockets.cs +++ b/sample/Sample.Core/Operations/Rockets/ListRockets.cs @@ -25,12 +25,9 @@ private class Handler(RocketDbContext dbContext, IMapper mapper) : IStreamReques public IAsyncEnumerable Handle(Request request, CancellationToken cancellationToken) { var query = dbContext.Rockets.AsQueryable(); - if (request.RocketType.HasValue) - { - query = query.Where(z => z.Type == request.RocketType); - } + if (request.RocketType.HasValue) query = query.Where(z => z.Type == request.RocketType); return query.ProjectTo(mapper.ConfigurationProvider).AsAsyncEnumerable(); } } -} +} \ No newline at end of file diff --git a/sample/Sample.Core/Sample.Core.csproj b/sample/Sample.Core/Sample.Core.csproj index 8136990df..7acc99d06 100644 --- a/sample/Sample.Core/Sample.Core.csproj +++ b/sample/Sample.Core/Sample.Core.csproj @@ -1,7 +1,7 @@ - net8.0 + net8.0 true diff --git a/sample/Sample.Function/.gitignore b/sample/Sample.Function/.gitignore deleted file mode 100644 index ff5b00c50..000000000 --- a/sample/Sample.Function/.gitignore +++ /dev/null @@ -1,264 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# Azure Functions localsettings file -local.settings.json - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# DNX -project.lock.json -project.fragment.lock.json -artifacts/ - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings -# but database connection strings (with potential passwords) will be unencrypted -#*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config -# NuGet v3's project.json files produces more ignoreable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -node_modules/ -orleans.codegen.cs - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml - -# CodeRush -.cr/ - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc \ No newline at end of file diff --git a/sample/Sample.Function/.vscode/extensions.json b/sample/Sample.Function/.vscode/extensions.json deleted file mode 100644 index 2e04e5736..000000000 --- a/sample/Sample.Function/.vscode/extensions.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "recommendations": ["ms-azuretools.vscode-azurefunctions"] -} diff --git a/sample/Sample.Function/LocalServices.cs b/sample/Sample.Function/LocalServices.cs deleted file mode 100644 index 922df4e3c..000000000 --- a/sample/Sample.Function/LocalServices.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.Conventions.DependencyInjection; - -namespace Sample_Function; - -[PublicAPI] -[ExportConvention] -public class LocalServices : IServiceConvention -{ - public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) - { - services.AddSingleton(new Service()); - } -} diff --git a/sample/Sample.Function/Sample_Function.csproj b/sample/Sample.Function/Sample_Function.csproj deleted file mode 100644 index 3a38a5534..000000000 --- a/sample/Sample.Function/Sample_Function.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - net8.0 - v4 - - - - - - - PreserveNewest - - - PreserveNewest - Never - - - - - - diff --git a/sample/Sample.Function/Service.cs b/sample/Sample.Function/Service.cs deleted file mode 100644 index 686173b16..000000000 --- a/sample/Sample.Function/Service.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Sample_Function; - -public class Service -{ - public string Value { get; } = "A Thing!"; -} diff --git a/sample/Sample.Function/Startup.cs b/sample/Sample.Function/Startup.cs deleted file mode 100644 index 80bba03c8..000000000 --- a/sample/Sample.Function/Startup.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Microsoft.Azure.Functions.Extensions.DependencyInjection; -using Microsoft.Azure.WebJobs.Hosting; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.LaunchPad.Functions; -using Sample_Function; - -[assembly: WebJobsStartup(typeof(Startup))] - -namespace Sample_Function; - -public class Startup : LaunchPadFunctionStartup -{ - public override void Setup(ConventionContextBuilder contextBuilder) - { - } - - public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder, IConventionContext context) - { - } - - public override void Configure(IFunctionsHostBuilder builder, IConventionContext context) - { - } -} diff --git a/sample/Sample.Function/TestFunction.cs b/sample/Sample.Function/TestFunction.cs deleted file mode 100644 index f38c6de78..000000000 --- a/sample/Sample.Function/TestFunction.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Azure.WebJobs; -using Microsoft.Azure.WebJobs.Extensions.Http; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; - -namespace Sample_Function; - -public class TestFunction(Service service) -{ - [FunctionName("TestFunction")] - public async Task Run( - [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] - HttpRequest req, - ILogger log - ) - { - log.LogInformation("C# HTTP trigger function processed a request"); - - string? name = req.Query["name"]; - - using var reader = new StreamReader(req.Body); - var requestBody = await reader.ReadToEndAsync(); -#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; - - return new OkObjectResult(responseMessage); - } -} diff --git a/sample/Sample.Function/host.json b/sample/Sample.Function/host.json deleted file mode 100644 index 667c31c2f..000000000 --- a/sample/Sample.Function/host.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "2.0", - "logging": { - "applicationInsights": { - "samplingExcludedTypes": "Request", - "samplingSettings": { - "isEnabled": true - } - } - } -} diff --git a/sample/Sample.Graphql/Program.cs b/sample/Sample.Graphql/Program.cs index d440e6804..05a39b914 100644 --- a/sample/Sample.Graphql/Program.cs +++ b/sample/Sample.Graphql/Program.cs @@ -1,37 +1,36 @@ +using System.Runtime.Loader; using HotChocolate.Types.Spatial; -using Microsoft.Extensions.DependencyModel; +using Rocket.Surgery.Conventions; +using Rocket.Surgery.Hosting; using Rocket.Surgery.LaunchPad.AspNetCore; using Rocket.Surgery.LaunchPad.HotChocolate; using Sample.Core.Models; using Sample.Graphql; -using Rocket.Surgery.Web.Hosting; - -var builder = WebApplication.CreateBuilder(args) - .LaunchWith( - RocketBooster.ForDependencyContext(DependencyContext.Default!), - z => z.WithConventionsFrom(Imports.GetConventions) - ); - -builder.Services - .AddGraphQLServer() - .AddSorting() - .AddFiltering() - .AddProjections() - .ConfigureStronglyTypedId() - .ConfigureStronglyTypedId() + +var builder = WebApplication.CreateBuilder(args); + +builder + .Services + .AddGraphQLServer() + .AddSorting() + .AddFiltering() + .AddProjections() + .ConfigureStronglyTypedId() + .ConfigureStronglyTypedId() // .AddDefaultTransactionScopeHandler() // .AddSpatialProjections() - .AddType(new GeometryType("Geometry", BindingBehavior.Implicit)) - .AddSpatialTypes() - .AddSpatialFiltering() - .AddSpatialProjections() - .AddExecutableTypes() - .AddQueryType() - .AddMutationType() - .ModifyRequestOptions(options => options.IncludeExceptionDetails = true); - -var app = builder.Build(); + .AddType(new GeometryType("Geometry", BindingBehavior.Implicit)) + .AddSpatialTypes() + .AddSpatialFiltering() + .AddSpatialProjections() + .AddExecutableTypes() + .AddQueryType() + .AddMutationType() + .ModifyRequestOptions(options => options.IncludeExceptionDetails = true); + +var app = await builder + .LaunchWith(RocketBooster.For(Imports.Instance), b => b.Set(AssemblyLoadContext.Default)); app.UseHttpLogging(); app.UseLaunchPadRequestLogging(); @@ -42,4 +41,4 @@ app.Run(); -public partial class Program; +public partial class Program; \ No newline at end of file diff --git a/sample/Sample.Graphql/Sample.Graphql.csproj b/sample/Sample.Graphql/Sample.Graphql.csproj index 6b48f2564..38bfcaeec 100644 --- a/sample/Sample.Graphql/Sample.Graphql.csproj +++ b/sample/Sample.Graphql/Sample.Graphql.csproj @@ -1,7 +1,7 @@ - net8.0 + net8.0 Sample.Graphql.Executable diff --git a/sample/Sample.Grpc/Program.cs b/sample/Sample.Grpc/Program.cs index 98b3701a9..8ca3bcd2d 100644 --- a/sample/Sample.Grpc/Program.cs +++ b/sample/Sample.Grpc/Program.cs @@ -1,23 +1,26 @@ -using Microsoft.Extensions.DependencyModel; -using Rocket.Surgery.Conventions; using Rocket.Surgery.Hosting; +using Rocket.Surgery.LaunchPad.AspNetCore; +using Sample.Grpc; +using Sample.Grpc.Services; -namespace Sample.Grpc; +var app = await WebApplication + .CreateBuilder(args) + .LaunchWith(RocketBooster.For(Imports.Instance)); -[ImportConventions] -public static partial class Program -{ - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } +app.UseLaunchPadRequestLogging(); - // Additional configuration is required to successfully run gRPC on macOS. - // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682 - public static IHostBuilder CreateHostBuilder(string[] args) - { - return Host.CreateDefaultBuilder(args) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)) - .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); - } -} +app.UseRouting(); + +app.MapGrpcService(); +app.MapGrpcService(); + +app.MapGet( + "/", + async context => await context.Response.WriteAsync( + "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909" + ) +); + +await app.RunAsync(); + +public partial class Program; \ No newline at end of file diff --git a/sample/Sample.Grpc/Sample.Grpc.csproj b/sample/Sample.Grpc/Sample.Grpc.csproj index df2920bdb..e66ca39e0 100644 --- a/sample/Sample.Grpc/Sample.Grpc.csproj +++ b/sample/Sample.Grpc/Sample.Grpc.csproj @@ -1,7 +1,7 @@ - net8.0 + net8.0 diff --git a/sample/Sample.Grpc/Startup.cs b/sample/Sample.Grpc/Startup.cs deleted file mode 100644 index 8cfa2bcd1..000000000 --- a/sample/Sample.Grpc/Startup.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Rocket.Surgery.LaunchPad.AspNetCore; -using Sample.Grpc.Services; - -namespace Sample.Grpc; - -public class Startup -{ - // 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 - public void ConfigureServices(IServiceCollection services) - { - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - app.UseLaunchPadRequestLogging(); - - app.UseRouting(); - - app.UseEndpoints( - endpoints => - { - endpoints.MapGrpcService(); - endpoints.MapGrpcService(); - - endpoints.MapGet( - "/", - async context => await context.Response.WriteAsync( - "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909" - ) - ); - } - ); - } -} diff --git a/sample/Sample.Pages/Pages/Rockets/Create.cshtml.cs b/sample/Sample.Pages/Pages/Rockets/Create.cshtml.cs index 9c2e8803e..3fb39c234 100644 --- a/sample/Sample.Pages/Pages/Rockets/Create.cshtml.cs +++ b/sample/Sample.Pages/Pages/Rockets/Create.cshtml.cs @@ -6,22 +6,18 @@ namespace Sample.Pages.Pages.Rockets; public class RocketCreateModel : MediatorPageModel { - [BindProperty] public CreateRocket.Request Model { get; set; } = new(); + [BindProperty] + public CreateRocket.Request Model { get; set; } = new(); [UsedImplicitly] - public void OnGet() - { - } + public void OnGet() { } [UsedImplicitly] public async Task OnPost() { - if (!ModelState.IsValid) - { - return Page(); - } + if (!ModelState.IsValid) return Page(); await Send(Model); return RedirectToPage("Index"); } -} +} \ No newline at end of file diff --git a/sample/Sample.Pages/Program.cs b/sample/Sample.Pages/Program.cs index c97d1434e..688d52c7a 100644 --- a/sample/Sample.Pages/Program.cs +++ b/sample/Sample.Pages/Program.cs @@ -1,21 +1,130 @@ -using Microsoft.Extensions.DependencyModel; +using System.Runtime.Loader; +using System.Text; +using System.Text.Json; +using Humanizer; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Rocket.Surgery.Conventions; using Rocket.Surgery.Hosting; +using Rocket.Surgery.LaunchPad.AspNetCore; +using Sample.Pages; -namespace Sample.Pages; +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddRazorPages(); +builder.Services.AddControllersWithViews(); -[ImportConventions] -public static partial class Program +var app = await builder.LaunchWith(RocketBooster.For(Imports.Instance), b => b.Set(AssemblyLoadContext.Default)); + +if (builder.Environment.IsDevelopment()) +{ + app.UseDeveloperExceptionPage(); +} +else { - public static void Main(string[] args) + app.UseExceptionHandler("/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); +} + +app.UseHttpsRedirection(); +app.UseStaticFiles(); + +app.UseLaunchPadRequestLogging(); + +app.UseRouting(); + +app.UseAuthorization(); + +app.MapHealthChecks( + "/health", + new() { - CreateHostBuilder(args).Build().Run(); + ResponseWriter = WriteResponse, + ResultStatusCodes = new Dictionary + { + { HealthStatus.Healthy, StatusCodes.Status200OK }, + { HealthStatus.Degraded, StatusCodes.Status500InternalServerError }, + { HealthStatus.Unhealthy, StatusCodes.Status503ServiceUnavailable }, + }, } +); +app.MapRazorPages(); + +await app.RunAsync(); + +static Task WriteResponse(HttpContext context, HealthReport healthReport) +{ + context.Response.ContentType = "application/json; charset=utf-8"; - public static IHostBuilder CreateHostBuilder(string[] args) + var options = new JsonWriterOptions { Indented = true, }; + + using var memoryStream = new MemoryStream(); + using (var jsonWriter = new Utf8JsonWriter(memoryStream, options)) { - return Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)); + jsonWriter.WriteStartObject(); + jsonWriter.WriteString("status", healthReport.Status.ToString()); + jsonWriter.WriteStartObject("results"); + + foreach (var healthReportEntry in healthReport.Entries) + { + jsonWriter.WriteStartObject(healthReportEntry.Key); + jsonWriter.WriteString( + "status", + healthReportEntry.Value.Status.ToString() + ); + jsonWriter.WriteString( + "duration", + healthReportEntry.Value.Duration.Humanize() + ); + jsonWriter.WriteString( + "description", + healthReportEntry.Value.Description + ); + + jsonWriter.WriteStartObject("data"); + foreach (var item in healthReportEntry.Value.Data) + { + jsonWriter.WritePropertyName(item.Key); + + JsonSerializer.Serialize( + jsonWriter, + item.Value, + item.Value.GetType() + ); + } + + jsonWriter.WriteEndObject(); + + if (healthReportEntry.Value.Tags.Any()) + { + jsonWriter.WriteStartArray("tags"); + foreach (var item in healthReportEntry.Value.Tags) + { + jsonWriter.WriteStringValue(item); + } + + jsonWriter.WriteEndArray(); + } + + if (healthReportEntry.Value.Exception != null) + { + var ex = healthReportEntry.Value.Exception; + jsonWriter.WriteStartObject("exception"); + jsonWriter.WriteString("message", ex.Message); + jsonWriter.WriteString("stacktrace", ex.StackTrace); + jsonWriter.WriteString("inner", ex.InnerException?.ToString()); + jsonWriter.WriteEndObject(); + } + + jsonWriter.WriteEndObject(); + } + + jsonWriter.WriteEndObject(); + jsonWriter.WriteEndObject(); } + + return context.Response.WriteAsync( + Encoding.UTF8.GetString(memoryStream.ToArray()) + ); } + +public partial class Program; \ No newline at end of file diff --git a/sample/Sample.Pages/Sample.Pages.csproj b/sample/Sample.Pages/Sample.Pages.csproj index 6cd87c7f2..93f7aef6b 100644 --- a/sample/Sample.Pages/Sample.Pages.csproj +++ b/sample/Sample.Pages/Sample.Pages.csproj @@ -1,10 +1,11 @@ - net8.0 + net8.0 + diff --git a/sample/Sample.Pages/Startup.cs b/sample/Sample.Pages/Startup.cs deleted file mode 100644 index a87ddda2f..000000000 --- a/sample/Sample.Pages/Startup.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System.Text; -using System.Text.Json; -using Humanizer; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; -using Microsoft.Extensions.Diagnostics.HealthChecks; -using Rocket.Surgery.LaunchPad.AspNetCore; - -namespace Sample.Pages; - -public class Startup(IConfiguration configuration) -{ - private static Task WriteResponse(HttpContext context, HealthReport healthReport) - { - context.Response.ContentType = "application/json; charset=utf-8"; - - var options = new JsonWriterOptions { Indented = true }; - - using var memoryStream = new MemoryStream(); - using (var jsonWriter = new Utf8JsonWriter(memoryStream, options)) - { - jsonWriter.WriteStartObject(); - jsonWriter.WriteString("status", healthReport.Status.ToString()); - jsonWriter.WriteStartObject("results"); - - foreach (var healthReportEntry in healthReport.Entries) - { - jsonWriter.WriteStartObject(healthReportEntry.Key); - jsonWriter.WriteString( - "status", - healthReportEntry.Value.Status.ToString() - ); - jsonWriter.WriteString( - "duration", - healthReportEntry.Value.Duration.Humanize() - ); - jsonWriter.WriteString( - "description", - healthReportEntry.Value.Description - ); - - jsonWriter.WriteStartObject("data"); - foreach (var item in healthReportEntry.Value.Data) - { - jsonWriter.WritePropertyName(item.Key); - - JsonSerializer.Serialize( - jsonWriter, item.Value, - item.Value.GetType() - ); - } - - jsonWriter.WriteEndObject(); - - if (healthReportEntry.Value.Tags.Any()) - { - jsonWriter.WriteStartArray("tags"); - foreach (var item in healthReportEntry.Value.Tags) - { - jsonWriter.WriteStringValue(item); - } - - jsonWriter.WriteEndArray(); - } - - if (healthReportEntry.Value.Exception != null) - { - var ex = healthReportEntry.Value.Exception; - jsonWriter.WriteStartObject("exception"); - jsonWriter.WriteString("message", ex.Message); - jsonWriter.WriteString("stacktrace", ex.StackTrace); - jsonWriter.WriteString("inner", ex.InnerException?.ToString()); - jsonWriter.WriteEndObject(); - } - - jsonWriter.WriteEndObject(); - } - - jsonWriter.WriteEndObject(); - jsonWriter.WriteEndObject(); - } - - return context.Response.WriteAsync( - Encoding.UTF8.GetString(memoryStream.ToArray()) - ); - } - - 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) - { - services.AddRazorPages(); - services.AddControllersWithViews(); - // services.Configure( - // x => - // { - // - // }); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler("/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); - } - - app.UseHttpsRedirection(); - app.UseStaticFiles(); - - app.UseLaunchPadRequestLogging(); - - app.UseRouting(); - - app.UseAuthorization(); - - app.UseEndpoints( - endpoints => - { - endpoints.MapHealthChecks( - "/health", new HealthCheckOptions - { - ResponseWriter = WriteResponse, - ResultStatusCodes = new Dictionary - { - { HealthStatus.Healthy, StatusCodes.Status200OK }, - { HealthStatus.Degraded, StatusCodes.Status500InternalServerError }, - { HealthStatus.Unhealthy, StatusCodes.Status503ServiceUnavailable } - } - } - ); - endpoints.MapRazorPages(); - } - ); - } -} diff --git a/sample/Sample.Restful.Client/Sample.Restful.Client.csproj b/sample/Sample.Restful.Client/Sample.Restful.Client.csproj index 5052d395b..966a122f6 100644 --- a/sample/Sample.Restful.Client/Sample.Restful.Client.csproj +++ b/sample/Sample.Restful.Client/Sample.Restful.Client.csproj @@ -1,6 +1,6 @@ - netstandard2.1;net8.0 + net8.0 true diff --git a/sample/Sample.Restful/Program.cs b/sample/Sample.Restful/Program.cs index c1bd4fde3..4394549e8 100644 --- a/sample/Sample.Restful/Program.cs +++ b/sample/Sample.Restful/Program.cs @@ -4,18 +4,15 @@ using FluentValidation; using Hellang.Middleware.ProblemDetails; using Humanizer; -using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; -using Microsoft.OpenApi.Models; +using Rocket.Surgery.Hosting; using Rocket.Surgery.LaunchPad.AspNetCore; -using Rocket.Surgery.Web.Hosting; using Sample.Restful; using Serilog; using Swashbuckle.AspNetCore.SwaggerGen; -var builder = WebApplication.CreateBuilder(args) - .ConfigureRocketSurgery(Imports.GetConventions); +var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers().AddControllersAsServices(); builder.Services.AddHostedService(); @@ -23,16 +20,17 @@ .Configure( c => c.SwaggerDoc( "v1", - new OpenApiInfo + new() { Version = typeof(Program).GetCustomAttribute()?.Version - ?? typeof(Program).GetCustomAttribute()?.Version ?? "0.1.0", + ?? typeof(Program).GetCustomAttribute()?.Version ?? "0.1.0", Title = "Test Application", } ) ); -var app = builder.Build(); +var app = await builder + .LaunchWith(RocketBooster.For(Imports.Instance)); app.UseProblemDetails(); app.UseHttpsRedirection(); @@ -53,15 +51,16 @@ app.UseAuthorization(); app.MapHealthChecks( - "/health", new HealthCheckOptions + "/health", + new() { ResponseWriter = WriteResponse, ResultStatusCodes = new Dictionary { { HealthStatus.Healthy, StatusCodes.Status200OK }, { HealthStatus.Degraded, StatusCodes.Status500InternalServerError }, - { HealthStatus.Unhealthy, StatusCodes.Status503ServiceUnavailable } - } + { HealthStatus.Unhealthy, StatusCodes.Status503ServiceUnavailable }, + }, } ); @@ -76,7 +75,7 @@ static Task WriteResponse(HttpContext context, HealthReport healthReport) { context.Response.ContentType = "application/json; charset=utf-8"; - var options = new JsonWriterOptions { Indented = true }; + var options = new JsonWriterOptions { Indented = true, }; using var memoryStream = new MemoryStream(); using (var jsonWriter = new Utf8JsonWriter(memoryStream, options)) @@ -107,7 +106,8 @@ static Task WriteResponse(HttpContext context, HealthReport healthReport) jsonWriter.WritePropertyName(item.Key); JsonSerializer.Serialize( - jsonWriter, item.Value, + jsonWriter, + item.Value, item.Value.GetType() ); } @@ -171,4 +171,4 @@ protected override Task ExecuteAsync(CancellationToken stoppingToken) var v = options.Value.A; return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/sample/Sample.Restful/Sample.Restful.csproj b/sample/Sample.Restful/Sample.Restful.csproj index 41b85e036..aa5f17c01 100644 --- a/sample/Sample.Restful/Sample.Restful.csproj +++ b/sample/Sample.Restful/Sample.Restful.csproj @@ -1,6 +1,6 @@ - net8.0 + net8.0 true true true diff --git a/sample/Sample.Worker/Program.cs b/sample/Sample.Worker/Program.cs index 30ab5c265..45c378887 100644 --- a/sample/Sample.Worker/Program.cs +++ b/sample/Sample.Worker/Program.cs @@ -1,21 +1,9 @@ -using Microsoft.Extensions.DependencyModel; -using Rocket.Surgery.Conventions; using Rocket.Surgery.Hosting; +using Sample.Worker; -namespace Sample.Worker; +var builder = Host + .CreateApplicationBuilder(args); +builder.Services.AddHostedService(); -[ImportConventions] -public static partial class Program -{ - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - public static IHostBuilder CreateHostBuilder(string[] args) - { - return Host.CreateDefaultBuilder(args) - .LaunchWith(RocketBooster.ForDependencyContext(DependencyContext.Default!), z => z.WithConventionsFrom(GetConventions)) - .ConfigureServices((_, services) => { services.AddHostedService(); }); - } -} +await ( await builder.LaunchWith(RocketBooster.For(Imports.Instance)) ).RunAsync(); \ No newline at end of file diff --git a/sample/Sample.Worker/Sample.Worker.csproj b/sample/Sample.Worker/Sample.Worker.csproj index 7ee1a9523..e3bc18b8a 100644 --- a/sample/Sample.Worker/Sample.Worker.csproj +++ b/sample/Sample.Worker/Sample.Worker.csproj @@ -1,6 +1,6 @@ - net8.0 + net8.0 diff --git a/src/Analyzers.roslyn4.0/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.0.csproj b/src/Analyzers.roslyn4.0/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.0.csproj deleted file mode 100644 index 3f8aefa42..000000000 --- a/src/Analyzers.roslyn4.0/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.0.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - netstandard2.0 - true - <_Analyzer_Roslyn_Version_>$(MSBuildProjectName.Replace("Rocket.Surgery.LaunchPad.Analyzers.", "")) - $(DefineConstants);ROSLYN4_0 - false - Rocket.Surgery.LaunchPad.Analyzers - true - - - - - - - - - - - diff --git a/src/Analyzers.roslyn4.4/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.4.csproj b/src/Analyzers.roslyn4.4/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.4.csproj deleted file mode 100644 index d75834217..000000000 --- a/src/Analyzers.roslyn4.4/Rocket.Surgery.LaunchPad.Analyzers.roslyn4.4.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - netstandard2.0 - true - <_Analyzer_Roslyn_Version_>$(MSBuildProjectName.Replace("Rocket.Surgery.LaunchPad.Analyzers.", "")) - $(DefineConstants);ROSLYN4_0;ROSLYN4_4 - false - Rocket.Surgery.LaunchPad.Analyzers - true - - - - - - - - - - - diff --git a/src/Analyzers/Composition/RestfulApiMethodBuilder.cs b/src/Analyzers/Composition/RestfulApiMethodBuilder.cs index e771fac05..e075a4095 100644 --- a/src/Analyzers/Composition/RestfulApiMethodBuilder.cs +++ b/src/Analyzers/Composition/RestfulApiMethodBuilder.cs @@ -10,7 +10,7 @@ internal class RestfulApiMethodBuilder : IRestfulApiMethodMatcher { private static RestfulApiParameterMatcher DefaultMatcher(Index index) { - return new RestfulApiParameterMatcher( + return new( index, ApiConventionNameMatchBehavior.Any, Array.Empty(), @@ -43,7 +43,7 @@ public RestfulApiMethodBuilder(RestfulApiMethod method) /// public RestfulApiMethodBuilder MatchSuffix(string value, params string[] values) { - _names = new[] { value }.Concat(values).ToArray(); + _names = new[] { value, }.Concat(values).ToArray(); _nameMatchBehavior = ApiConventionNameMatchBehavior.Suffix; return this; @@ -57,7 +57,7 @@ public RestfulApiMethodBuilder MatchSuffix(string value, params string[] values) /// public RestfulApiMethodBuilder MatchPrefix(string value, params string[] values) { - _names = new[] { value }.Concat(values).ToArray(); + _names = new[] { value, }.Concat(values).ToArray(); _nameMatchBehavior = ApiConventionNameMatchBehavior.Prefix; return this; @@ -71,7 +71,7 @@ public RestfulApiMethodBuilder MatchPrefix(string value, params string[] values) /// public RestfulApiMethodBuilder MatchName(string value, params string[] values) { - _names = new[] { value }.Concat(values).ToArray(); + _names = new[] { value, }.Concat(values).ToArray(); _nameMatchBehavior = ApiConventionNameMatchBehavior.Exact; return this; @@ -89,15 +89,12 @@ public RestfulApiMethodBuilder MatchName(string value, params string[] values) /// public RestfulApiMethodBuilder MatchParameterName(Index parameter, string value, params string[] values) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = DefaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = DefaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, ApiConventionNameMatchBehavior.Exact, - new[] { value }.Concat(values).ToArray(), + new[] { value, }.Concat(values).ToArray(), item.TypeMatch, item.Type ); @@ -115,10 +112,7 @@ public RestfulApiMethodBuilder MatchParameterName(Index parameter, string value, /// public RestfulApiMethodBuilder HasParameter(Index parameter) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = DefaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = DefaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( @@ -155,15 +149,12 @@ public RestfulApiMethodBuilder MatchParameterCount(int count) /// public RestfulApiMethodBuilder MatchParameterPrefix(Index parameter, string value, params string[] values) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = DefaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = DefaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, ApiConventionNameMatchBehavior.Prefix, - new[] { value }.Concat(values).ToArray(), + new[] { value, }.Concat(values).ToArray(), item.TypeMatch, item.Type ); @@ -183,15 +174,12 @@ public RestfulApiMethodBuilder MatchParameterPrefix(Index parameter, string valu /// public RestfulApiMethodBuilder MatchParameterSuffix(Index parameter, string value, params string[] values) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = DefaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = DefaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, ApiConventionNameMatchBehavior.Suffix, - new[] { value }.Concat(values).ToArray(), + new[] { value, }.Concat(values).ToArray(), item.TypeMatch, item.Type ); @@ -210,10 +198,7 @@ public RestfulApiMethodBuilder MatchParameterSuffix(Index parameter, string valu /// public RestfulApiMethodBuilder MatchParameterType(Index parameter, INamedTypeSymbol type) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = DefaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = DefaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, @@ -234,26 +219,24 @@ internal bool IsValid() internal bool IsMatch(ActionModel actionModel) { var nameMatch = _nameMatchBehavior switch - { - ApiConventionNameMatchBehavior.Exact => _names.Any(name => actionModel.ActionName.Equals(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Prefix => _names.Any(name => actionModel.ActionName.StartsWith(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Suffix => _names.Any(name => actionModel.ActionName.EndsWith(name, StringComparison.OrdinalIgnoreCase)), - _ => true - }; + { + ApiConventionNameMatchBehavior.Exact => _names.Any(name => actionModel.ActionName.Equals(name, StringComparison.OrdinalIgnoreCase)), + ApiConventionNameMatchBehavior.Prefix => _names.Any( + name => actionModel.ActionName.StartsWith(name, StringComparison.OrdinalIgnoreCase) + ), + ApiConventionNameMatchBehavior.Suffix => _names.Any( + name => actionModel.ActionName.EndsWith(name, StringComparison.OrdinalIgnoreCase) + ), + _ => true, + }; if (!nameMatch) return false; var parameters = actionModel.ActionMethod.Parameters; - if (_parameterCount.HasValue && parameters.Length != _parameterCount.Value) - { - return false; - } + if (_parameterCount.HasValue && parameters.Length != _parameterCount.Value) return false; - if (parameters.Length >= _parameters.Count) - { - return _parameters.Values.All(z => z.IsMatch(actionModel)); - } + if (parameters.Length >= _parameters.Count) return _parameters.Values.All(z => z.IsMatch(actionModel)); return false; } @@ -269,4 +252,4 @@ bool IRestfulApiMethodMatcher.IsMatch(ActionModel actionModel) } } -internal record ActionModel(Compilation Compilation, string ActionName, IMethodSymbol ActionMethod); +internal record ActionModel(Compilation Compilation, string ActionName, IMethodSymbol ActionMethod); \ No newline at end of file diff --git a/src/Analyzers/Composition/RestfulApiParameterMatcher.cs b/src/Analyzers/Composition/RestfulApiParameterMatcher.cs index b8e71a356..cce120a30 100644 --- a/src/Analyzers/Composition/RestfulApiParameterMatcher.cs +++ b/src/Analyzers/Composition/RestfulApiParameterMatcher.cs @@ -5,7 +5,8 @@ namespace Rocket.Surgery.LaunchPad.Analyzers.Composition; -internal class RestfulApiParameterMatcher( +internal class RestfulApiParameterMatcher +( Index parameterIndex, ApiConventionNameMatchBehavior nameMatch, string[] names, @@ -33,24 +34,15 @@ public bool IsMatch(ActionModel actionModel) { static bool CheckType(ITypeSymbol symbol, INamedTypeSymbol type) { - if (symbol is not INamedTypeSymbol namedTypeSymbol) - { - return false; - } + if (symbol is not INamedTypeSymbol namedTypeSymbol) return false; return namedTypeSymbol.IsGenericType && SymbolEqualityComparer.Default.Equals(namedTypeSymbol.OriginalDefinition, type); } var parameterIs = CheckType(parameter.Type, Type); - if (!parameterIs) - { - parameterIs = parameter.Type.AllInterfaces.Any(inter => CheckType(inter, Type)); - } + if (!parameterIs) parameterIs = parameter.Type.AllInterfaces.Any(inter => CheckType(inter, Type)); - if (!parameterIs) - { - return false; - } + if (!parameterIs) return false; } else if (!actionModel.Compilation.HasImplicitConversion(parameter.Type, Type)) { @@ -59,16 +51,16 @@ static bool CheckType(ITypeSymbol symbol, INamedTypeSymbol type) } return NameMatch switch - { - ApiConventionNameMatchBehavior.Exact => Names.Any(name => parameter.Name.Equals(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Prefix => Names.Any(name => parameter.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Suffix => Names.Any(name => parameter.Name.EndsWith(name, StringComparison.OrdinalIgnoreCase)), - _ => true - }; + { + ApiConventionNameMatchBehavior.Exact => Names.Any(name => parameter.Name.Equals(name, StringComparison.OrdinalIgnoreCase)), + ApiConventionNameMatchBehavior.Prefix => Names.Any(name => parameter.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase)), + ApiConventionNameMatchBehavior.Suffix => Names.Any(name => parameter.Name.EndsWith(name, StringComparison.OrdinalIgnoreCase)), + _ => true, + }; } return false; } } -// IApiDescriptionProvider +// IApiDescriptionProvider \ No newline at end of file diff --git a/src/Analyzers/ControllerActionBodyGenerator.cs b/src/Analyzers/ControllerActionBodyGenerator.cs index c2db349d2..e1fe774b3 100644 --- a/src/Analyzers/ControllerActionBodyGenerator.cs +++ b/src/Analyzers/ControllerActionBodyGenerator.cs @@ -43,10 +43,8 @@ public class ControllerActionBodyGenerator : IIncrementalGenerator ; if (!isStream) - { newSyntax = newSyntax .AddModifiers(Token(SyntaxKind.AsyncKeyword)); - } var block = Block(); var resultName = parameter.Name == "result" ? "r" : "result"; @@ -154,10 +152,7 @@ public class ControllerActionBodyGenerator : IIncrementalGenerator } } - if (failed) - { - return null; - } + if (failed) return null; var bindingMembers = parameterType .GetMembers() @@ -268,11 +263,8 @@ public class ControllerActionBodyGenerator : IIncrementalGenerator } if (isUnit) - { block = block.AddStatements(ExpressionStatement(sendRequestExpression)); - } else - { block = block .AddStatements( LocalDeclarationStatement( @@ -282,7 +274,6 @@ public class ControllerActionBodyGenerator : IIncrementalGenerator ) ) ); - } var knownStatusCodes = symbol .GetAttributes() @@ -319,7 +310,6 @@ public class ControllerActionBodyGenerator : IIncrementalGenerator var newParam = declaredParam; if (matcher is { }) - { switch (matcher) { case { Method: RestfulApiMethod.List, }: @@ -344,48 +334,33 @@ public class ControllerActionBodyGenerator : IIncrementalGenerator break; } } - } newSyntax = newSyntax.WithParameterList(newSyntax.ParameterList.ReplaceNode(declaredParam, newParam)); } - if (!hasDefault) - { - newSyntax = newSyntax.AddAttributeLists(createSimpleAttribute("ProducesDefaultResponseType")); - } + if (!hasDefault) newSyntax = newSyntax.AddAttributeLists(createSimpleAttribute("ProducesDefaultResponseType")); var statusCode = hasSuccess ? knownStatusCodes.First(z => z is >= 200 and < 300) : StatusCodes.Status200OK; if (!hasSuccess) { if (isUnitResult) - { statusCode = StatusCodes.Status204NoContent; - } - else if (matcher is { }) - { - statusCode = statusCodeMap[matcher.Method]; - } + else if (matcher is { }) statusCode = statusCodeMap[matcher.Method]; newSyntax = newSyntax.AddAttributeLists(produces(statusCode)); } if (!knownStatusCodes.Contains(StatusCodes.Status404NotFound) && matcher?.Method != RestfulApiMethod.List) - { newSyntax = newSyntax.AddAttributeLists(produces(StatusCodes.Status404NotFound, "ProblemDetails")); - } if (!knownStatusCodes.Contains(StatusCodes.Status400BadRequest)) - { newSyntax = newSyntax.AddAttributeLists(produces(StatusCodes.Status400BadRequest, "ProblemDetails")); - } if (!knownStatusCodes.Contains(StatusCodes.Status422UnprocessableEntity)) - { newSyntax = newSyntax.AddAttributeLists( produces(StatusCodes.Status422UnprocessableEntity, "FluentValidationProblemDetails") ); - } if (isStream) @@ -546,7 +521,6 @@ static ExpressionSyntax statusCodeResult(int statusCode) static AttributeListSyntax produces(int statusCode, string? responseType = null) { if (responseType is { }) - { return AttributeList( SingletonSeparatedList( Attribute( @@ -563,7 +537,6 @@ static AttributeListSyntax produces(int statusCode, string? responseType = null) ) ) ); - } return AttributeList( SingletonSeparatedList( diff --git a/src/Analyzers/GraphqlMutationActionBodyGenerator.cs b/src/Analyzers/GraphqlMutationActionBodyGenerator.cs index 07ab02819..3e8c27e30 100644 --- a/src/Analyzers/GraphqlMutationActionBodyGenerator.cs +++ b/src/Analyzers/GraphqlMutationActionBodyGenerator.cs @@ -43,10 +43,8 @@ ExpressionSyntax requestExpression ; if (!isStream) - { newSyntax = newSyntax .AddModifiers(Token(SyntaxKind.AsyncKeyword)); - } var block = Block(); var resultName = parameter.Name == "result" ? "r" : "result"; @@ -54,7 +52,6 @@ ExpressionSyntax requestExpression 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( Diagnostic.Create( GeneratorDiagnostics.ParameterMustExist, @@ -64,7 +61,6 @@ ExpressionSyntax requestExpression requestType.Name ) ); - } var claimsPrincipalProperty = requestType @@ -79,9 +75,7 @@ ExpressionSyntax requestExpression ); var hasClaimsPrincipal = claimsPrincipalProperty is { }; if (hasClaimsPrincipal) - { if (claimsPrincipalParameter is null) - { context.ReportDiagnostic( Diagnostic.Create( GeneratorDiagnostics.ParameterMustExist, @@ -91,13 +85,8 @@ ExpressionSyntax requestExpression requestType.Name ) ); - } - } - if (( hasClaimsPrincipal && claimsPrincipalParameter is null ) || mediatorParameter is null) - { - return null; - } + if (( hasClaimsPrincipal && claimsPrincipalParameter is null ) || mediatorParameter is null) return null; if (!requestType.IsRecord) { @@ -134,7 +123,6 @@ ExpressionSyntax requestExpression { var expressions = new List(); if (hasClaimsPrincipal) - { // ReSharper disable NullableWarningSuppressionIsUsed expressions.Add( AssignmentExpression( @@ -143,9 +131,7 @@ ExpressionSyntax requestExpression IdentifierName(claimsPrincipalParameter!.Name) ) ); - // ReSharper enable NullableWarningSuppressionIsUsed - } - + // ReSharper enable NullableWarningSuppressionIsUsed if (expressions.Any()) { var withExpression = WithExpression( @@ -193,7 +179,6 @@ ExpressionSyntax requestExpression if (isUnit) - { block = block.AddStatements( ExpressionStatement(sendRequestExpression), ReturnStatement( @@ -204,9 +189,7 @@ ExpressionSyntax requestExpression ) ) ); - } else - { block = block .AddStatements( LocalDeclarationStatement( @@ -217,7 +200,6 @@ ExpressionSyntax requestExpression ), ReturnStatement(IdentifierName(resultName)) ); - } return newSyntax @@ -231,10 +213,7 @@ static ExpressionSyntax sendMediatorRequest( ) { var arguments = new List { Argument(nameSyntax), }; - if (cancellationTokenParameter is { }) - { - arguments.Add(Argument(IdentifierName(cancellationTokenParameter.Name))); - } + if (cancellationTokenParameter is { }) arguments.Add(Argument(IdentifierName(cancellationTokenParameter.Name))); return AwaitExpression( InvocationExpression( @@ -272,10 +251,7 @@ static ExpressionSyntax streamMediatorRequest( ) { var arguments = new List { Argument(nameSyntax), }; - if (cancellationTokenParameter is { }) - { - arguments.Add(Argument(IdentifierName(cancellationTokenParameter.Name))); - } + if (cancellationTokenParameter is { }) arguments.Add(Argument(IdentifierName(cancellationTokenParameter.Name))); return InvocationExpression( MemberAccessExpression( diff --git a/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs b/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs index 21d5b59ba..745754176 100644 --- a/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs +++ b/src/Analyzers/GraphqlOptionalPropertyTrackingGenerator.cs @@ -45,9 +45,7 @@ INamedTypeSymbol targetSymbol if (targetSymbol.Interfaces.FirstOrDefault(z => z.Name.StartsWith("IPropertyTracking", StringComparison.Ordinal)) is not { TypeArguments: [INamedTypeSymbol propertyTrackingSymbol,], }) - { return; - } var classToInherit = ( isRecord @@ -191,9 +189,7 @@ INamedTypeSymbol targetSymbol if (!SymbolEqualityComparer.Default.Equals(propertyType, propertySymbol.Type) && propertyType is { TypeKind: TypeKind.Struct or TypeKind.Enum, } && typeName is not NullableTypeSyntax) - { typeName = NullableType(typeName); - } addNamespacesFromPropertyType(namespaces, propertyType); classToInherit = classToInherit.AddMembers( @@ -213,10 +209,7 @@ INamedTypeSymbol targetSymbol ? namedTypeSymbol.TypeArguments[0] : propertySymbol.Type; var type = ParseTypeName(propertyType.ToDisplayString(NullableFlowState.MaybeNull, SymbolDisplayFormat.MinimallyQualifiedFormat)); - if (propertyType is { TypeKind: TypeKind.Struct or TypeKind.Enum, } && type is not NullableTypeSyntax) - { - type = NullableType(type); - } + if (propertyType is { TypeKind: TypeKind.Struct or TypeKind.Enum, } && type is not NullableTypeSyntax) type = NullableType(type); addNamespacesFromPropertyType(namespaces, propertyType); diff --git a/src/Analyzers/InheritFromGenerator.cs b/src/Analyzers/InheritFromGenerator.cs index 98d795d63..6a26bc759 100644 --- a/src/Analyzers/InheritFromGenerator.cs +++ b/src/Analyzers/InheritFromGenerator.cs @@ -239,10 +239,7 @@ private static TypeDeclarationSyntax AddInheritableMembers( INamedTypeSymbol inheritFromSymbol ) { - if (!compilation.HasImplicitConversion(targetSymbol, inheritFromSymbol)) - { - classToInherit = classToInherit.AddMembers(members.ToArray()); - } + if (!compilation.HasImplicitConversion(targetSymbol, inheritFromSymbol)) classToInherit = classToInherit.AddMembers(members.ToArray()); return inheritFromSymbol .DeclaringSyntaxReferences.Select(z => z.GetSyntax()) @@ -607,12 +604,10 @@ ImmutableArray attributes // they will be named InheritFrom // filter the members to remove excluded properties if (!declaration.Modifiers.Any(z => z.IsKind(SyntaxKind.PartialKeyword))) - { -// context.ReportDiagnostic( -// Diagnostic.Create(GeneratorDiagnostics.MustBePartial, declaration.Identifier.GetLocation(), declaration.GetFullMetadataName()) -// ); + // context.ReportDiagnostic( + // Diagnostic.Create(GeneratorDiagnostics.MustBePartial, declaration.Identifier.GetLocation(), declaration.GetFullMetadataName()) + // ); return; - } var classToInherit = ClassDeclaration(declaration.Identifier) .WithModifiers(TokenList(declaration.Modifiers.Select(z => z.WithoutTrivia()))) @@ -646,10 +641,7 @@ ImmutableArray attributes var visitor = new RuleExpressionVisitor(excludedMembers); constructor.Accept(visitor); - if (visitor is { Results: [] results, }) - { - continue; - } + if (visitor is { Results: [] results, }) continue; var parameters = constructor .ParameterList.Parameters.Where( @@ -670,7 +662,6 @@ ImmutableArray attributes .DescendantNodes() .OfType() .Any(z => z is { Expression: SimpleNameSyntax { Identifier.Text: { Length: > 0, } invocationName, }, } && invocationName == methodName)) - { context.ReportDiagnostic( Diagnostic.Create( GeneratorDiagnostics.ValidatorShouldCallGeneratedValidationMethod, @@ -678,7 +669,6 @@ ImmutableArray attributes methodName ) ); - } namespaces = namespaces.AddDistinctUsingStatements(inheritFromSyntax.SyntaxTree.GetCompilationUnitRoot().Usings); classToInherit = classToInherit.AddMembers(method); @@ -786,10 +776,7 @@ private void HandleRuleFor(InvocationExpressionSyntax parent, MemberAccessExpres private void HandleRuleSet(InvocationExpressionSyntax parent, ArgumentSyntax action) { // TODO: Support methods? - if (HandleNestedAction(action) is { } updatedAction) - { - _results.Add(parent.ReplaceNode(action, updatedAction)); - } + if (HandleNestedAction(action) is { } updatedAction) _results.Add(parent.ReplaceNode(action, updatedAction)); } private void HandleWhen(InvocationExpressionSyntax parent, ArgumentSyntax predicate, ArgumentSyntax whenAction, ArgumentSyntax? otherwiseAction) @@ -806,10 +793,7 @@ private void HandleWhen(InvocationExpressionSyntax parent, ArgumentSyntax predic && expression.Identifier.Text == parameter.Identifier.Text ) .Any(z => excludedMembers.Contains(z.Name.Identifier.Text)); - if (predicateContainsExcludedMember) - { - return; - } + if (predicateContainsExcludedMember) return; if (otherwiseAction is null && HandleNestedAction(whenAction) is { } updatedWhenAction) { @@ -817,10 +801,7 @@ private void HandleWhen(InvocationExpressionSyntax parent, ArgumentSyntax predic return; } - if (otherwiseAction is null) - { - return; - } + if (otherwiseAction is null) return; switch ( HandleNestedAction(whenAction), HandleNestedAction(otherwiseAction) ) { @@ -867,10 +848,7 @@ private void HandleWhen(InvocationExpressionSyntax parent, ArgumentSyntax predic // TODO: Support methods? var visitor = new RuleExpressionVisitor(excludedMembers); visitor.Visit(action); - if (visitor.Results.Length == 0) - { - return null; - } + if (visitor.Results.Length == 0) return null; var removeNodes = action .DescendantNodes() diff --git a/src/Analyzers/Rocket.Surgery.LaunchPad.Analyzers.csproj b/src/Analyzers/Rocket.Surgery.LaunchPad.Analyzers.csproj index 13a49fd75..6a81e9900 100644 --- a/src/Analyzers/Rocket.Surgery.LaunchPad.Analyzers.csproj +++ b/src/Analyzers/Rocket.Surgery.LaunchPad.Analyzers.csproj @@ -13,17 +13,6 @@ IncludeAssets="runtime;build;buildMultitargeting;buildTransitive;native;contentfiles;analyzers" PrivateAssets="All" /> - - - - - z.IsKind(SyntaxKind.PartialKeyword))) - { context.ReportDiagnostic( Diagnostic.Create(GeneratorDiagnostics.MustBePartial, parentSyntax.Identifier.GetLocation(), parentSyntax.GetFullMetadataName()) ); - } parent = parentSyntax.Parent; } @@ -106,10 +104,7 @@ public static string GetFullMetadataName(this TypeDeclarationSyntax? source) public static string GetFullMetadataName(this ISymbol? s) { - if (s == null || IsRootNamespace(s)) - { - return string.Empty; - } + if (s == null || IsRootNamespace(s)) return string.Empty; var sb = new StringBuilder(s.MetadataName); var last = s; @@ -119,13 +114,9 @@ public static string GetFullMetadataName(this ISymbol? s) while (!IsRootNamespace(s)) { if (s is ITypeSymbol && last is ITypeSymbol) - { sb.Insert(0, '+'); - } else - { sb.Insert(0, '.'); - } sb.Insert(0, s.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); s = s.ContainingSymbol; diff --git a/src/AspNetCore.Blazor/Rocket.Surgery.LaunchPad.AspNetCore.Blazor.csproj b/src/AspNetCore.Blazor/Rocket.Surgery.LaunchPad.AspNetCore.Blazor.csproj index 4a9428435..a56f57d9f 100644 --- a/src/AspNetCore.Blazor/Rocket.Surgery.LaunchPad.AspNetCore.Blazor.csproj +++ b/src/AspNetCore.Blazor/Rocket.Surgery.LaunchPad.AspNetCore.Blazor.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/AspNetCore.Blazor/Validation.cs b/src/AspNetCore.Blazor/Validation.cs index 3c57d0813..f9e1f0421 100644 --- a/src/AspNetCore.Blazor/Validation.cs +++ b/src/AspNetCore.Blazor/Validation.cs @@ -28,10 +28,7 @@ private static FieldIdentifier ToFieldIdentifier(EditContext editContext, string while (true) { var nextTokenEnd = propertyPath.IndexOfAny(_separators); - if (nextTokenEnd < 0) - { - return new(obj, propertyPath); - } + if (nextTokenEnd < 0) return new(obj, propertyPath); var nextToken = propertyPath.Substring(0, nextTokenEnd); propertyPath = propertyPath.Substring(nextTokenEnd + 1); @@ -52,19 +49,14 @@ private static FieldIdentifier ToFieldIdentifier(EditContext editContext, string { // It's a regular property var prop = obj.GetType().GetProperty(nextToken); - if (prop == null) - { - throw new InvalidOperationException($"Could not find property named {nextToken} on object of type {obj.GetType().FullName}."); - } + if (prop == null) throw new InvalidOperationException($"Could not find property named {nextToken} on object of type {obj.GetType().FullName}."); newObj = prop.GetValue(obj); } if (newObj == null) - { // This is as far as we can go return new(obj, nextToken); - } obj = newObj; } @@ -144,13 +136,11 @@ private static async void ValidateField( protected override void OnInitialized() { if (CurrentEditContext == null) - { throw new InvalidOperationException( $"{nameof(FluentValidator)} requires a cascading " + $"parameter of type {nameof(EditContext)}. For example, you can use {nameof(FluentValidator)} " + $"inside an {nameof(EditForm)}." ); - } AddFluentValidation(Validator, CurrentEditContext, Services); } diff --git a/src/AspNetCore.NewtonsoftJson/Conventions/NewtonsoftJsonConvention.cs b/src/AspNetCore.NewtonsoftJson/Conventions/NewtonsoftJsonConvention.cs index 93efa2955..e54b1eb45 100644 --- a/src/AspNetCore.NewtonsoftJson/Conventions/NewtonsoftJsonConvention.cs +++ b/src/AspNetCore.NewtonsoftJson/Conventions/NewtonsoftJsonConvention.cs @@ -37,10 +37,7 @@ public NewtonsoftJsonConvention(FoundationOptions? options = null) /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); services.WithMvcCore().AddNewtonsoftJson(); services @@ -57,4 +54,4 @@ public void Register(IConventionContext context, IConfiguration configuration, I ) ); } -} +} \ No newline at end of file diff --git a/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj b/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj index 9edfad19f..a4b21ce90 100644 --- a/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj +++ b/src/AspNetCore.NewtonsoftJson/Rocket.Surgery.LaunchPad.AspNetCore.NewtonsoftJson.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) Rocket.Surgery.LaunchPad.AspNetCore diff --git a/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs b/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs index 52e5972d8..718c44686 100644 --- a/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs +++ b/src/AspNetCore.NewtonsoftJson/ValidationProblemDetailsNewtonsoftJsonConverter.cs @@ -18,19 +18,14 @@ public sealed class ValidationProblemDetailsNewtonsoftJsonConverter : JsonConver Type objectType, FluentValidationProblemDetails? existingValue, bool hasExistingValue, - [NotNull] JsonSerializer serializer + [NotNull] + JsonSerializer serializer ) { - if (serializer == null) - { - throw new ArgumentNullException(nameof(serializer)); - } + ArgumentNullException.ThrowIfNull(serializer); var annotatedProblemDetails = serializer.Deserialize(reader); - if (annotatedProblemDetails == null) - { - return null; - } + if (annotatedProblemDetails == null) return null; var problemDetails = existingValue ?? new FluentValidationProblemDetails(); annotatedProblemDetails.CopyTo(problemDetails); @@ -39,20 +34,16 @@ [NotNull] JsonSerializer serializer /// public override void WriteJson( - [NotNull] JsonWriter writer, + [NotNull] + JsonWriter writer, FluentValidationProblemDetails? value, - [NotNull] JsonSerializer serializer + [NotNull] + JsonSerializer serializer ) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); - if (serializer == null) - { - throw new ArgumentNullException(nameof(serializer)); - } + ArgumentNullException.ThrowIfNull(serializer); if (value == null) { @@ -69,9 +60,7 @@ internal class AnnotatedProblemDetails /// /// Required for JSON.NET deserialization. /// - public AnnotatedProblemDetails() - { - } + public AnnotatedProblemDetails() { } /// /// Required for JSON.NET deserialization. @@ -120,7 +109,8 @@ public AnnotatedProblemDetails(FluentValidationProblemDetails problemDetails) public IDictionary Errors { get; } = new Dictionary(StringComparer.Ordinal); - [JsonProperty(PropertyName = "rules")] public IEnumerable Rules { get; internal set; } = Array.Empty(); + [JsonProperty(PropertyName = "rules")] + public IEnumerable Rules { get; internal set; } = Array.Empty(); public void CopyTo(FluentValidationProblemDetails problemDetails) { @@ -130,16 +120,16 @@ public void CopyTo(FluentValidationProblemDetails problemDetails) problemDetails.Instance = Instance; problemDetails.Detail = Detail; - foreach (var (key, value) in Extensions) + foreach (( var key, var value ) in Extensions) { problemDetails.Extensions[key] = value; } Rules = problemDetails.Rules; - foreach (var (key, value) in problemDetails.ValidationErrors) + foreach (( var key, var value ) in problemDetails.ValidationErrors) { Errors[key] = value; } } } -} +} \ No newline at end of file diff --git a/src/AspNetCore.Spatial/Rocket.Surgery.LaunchPad.AspNetCore.Spatial.csproj b/src/AspNetCore.Spatial/Rocket.Surgery.LaunchPad.AspNetCore.Spatial.csproj index 6e2c7c90d..058372507 100644 --- a/src/AspNetCore.Spatial/Rocket.Surgery.LaunchPad.AspNetCore.Spatial.csproj +++ b/src/AspNetCore.Spatial/Rocket.Surgery.LaunchPad.AspNetCore.Spatial.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) Rocket.Surgery.LaunchPad.AspNetCore diff --git a/src/AspNetCore.Testing/LaunchPadExtension.cs b/src/AspNetCore.Testing/LaunchPadExtension.cs index 32e944f32..2f1a7e0ab 100644 --- a/src/AspNetCore.Testing/LaunchPadExtension.cs +++ b/src/AspNetCore.Testing/LaunchPadExtension.cs @@ -1,4 +1,3 @@ -using System.Reflection; using Alba; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.HttpLogging; @@ -6,62 +5,31 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Rocket.Surgery.Conventions.Testing; -using Rocket.Surgery.Hosting; namespace Rocket.Surgery.LaunchPad.AspNetCore.Testing; /// -/// An that is used for launchpad is used to get the assembly to test +/// An that is used for launchpad is used to get the assembly to test /// /// public class LaunchPadExtension : LaunchPadExtension { /// - /// Create the test extension + /// Create the test extension /// /// - public LaunchPadExtension(ILoggerFactory loggerFactory) : base(typeof(TTestAssembly), loggerFactory) - { - } + public LaunchPadExtension(ILoggerFactory loggerFactory) : base(loggerFactory) { } } #pragma warning disable CA1816 #pragma warning disable CA1063 /// -/// An that is used for launchpad +/// An that is used for launchpad /// -public class LaunchPadExtension : IAlbaExtension +public class LaunchPadExtension(ILoggerFactory loggerFactory) : IAlbaExtension { - private readonly Assembly _testAssemblyReference; - private readonly ILoggerFactory _loggerFactory; - - /// - /// 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 virtual void Dispose() - { - } + public virtual void Dispose() { } /// public virtual ValueTask DisposeAsync() @@ -70,7 +38,7 @@ public virtual ValueTask DisposeAsync() } /// - /// Virtual method that can be overridden to do something before the host is started + /// Virtual method that can be overridden to do something before the host is started /// /// /// @@ -80,23 +48,18 @@ public virtual Task Start(IAlbaHost host) } /// - /// Virtual method that can be overridden to do something before the host is configured + /// 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((_, 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; - })); + builder.ConfigureServices(s => s.AddHttpLogging(options => options.LoggingFields = HttpLoggingFields.All)); return builder; } } #pragma warning restore CA1816 -#pragma warning restore CA1063 +#pragma warning restore CA1063 \ No newline at end of file diff --git a/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs b/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs index 6d55c2b91..992007de5 100644 --- a/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs +++ b/src/AspNetCore.Testing/LaunchPadWebAppFixture.cs @@ -33,7 +33,7 @@ protected LaunchPadWebAppFixture(IResettableAlbaExtension resettableAlbaExtensio protected LaunchPadWebAppFixture(params IAlbaExtension[] extensions) { _loggerFactory = new(); - _extensions = [new LaunchPadExtension(this, _loggerFactory), ..extensions,]; + _extensions = [new LaunchPadExtension(_loggerFactory), ..extensions,]; } /// diff --git a/src/AspNetCore.Testing/Rocket.Surgery.LaunchPad.AspNetCore.Testing.csproj b/src/AspNetCore.Testing/Rocket.Surgery.LaunchPad.AspNetCore.Testing.csproj index 3ef27eff1..1d572900d 100644 --- a/src/AspNetCore.Testing/Rocket.Surgery.LaunchPad.AspNetCore.Testing.csproj +++ b/src/AspNetCore.Testing/Rocket.Surgery.LaunchPad.AspNetCore.Testing.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs b/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs index e98126475..4dc2e008e 100644 --- a/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs +++ b/src/AspNetCore/Composition/RestfulApiActionModelConvention.cs @@ -17,16 +17,14 @@ internal class RestfulApiActionModelConvention : IActionModelConvention, ISchema { private static string? GetHttpMethod(ActionModel action) { - var httpMethods = action.Attributes - .OfType() - .SelectMany(a => a.HttpMethods) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToArray(); + var httpMethods = action + .Attributes + .OfType() + .SelectMany(a => a.HttpMethods) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); // Not valid for actions with more than one verb - if (httpMethods.Length > 1) - { - return null; - } + if (httpMethods.Length > 1) return null; return httpMethods[0]; } @@ -35,11 +33,13 @@ internal class RestfulApiActionModelConvention : IActionModelConvention, ISchema private static void ExtractParameterDetails(ActionModel action) { var requestParameter = action.Parameters.FirstOrDefault( - z => z.ParameterInfo.ParameterType.GetInterfaces().Any( - i => i.IsGenericType && - ( typeof(IRequest<>) == i.GetGenericTypeDefinition() - || typeof(IStreamRequest<>) == i.GetGenericTypeDefinition() ) - ) + z => z + .ParameterInfo.ParameterType.GetInterfaces() + .Any( + i => i.IsGenericType + && ( typeof(IRequest<>) == i.GetGenericTypeDefinition() + || typeof(IStreamRequest<>) == i.GetGenericTypeDefinition() ) + ) ) ; if (requestParameter is null) return; @@ -49,24 +49,30 @@ private static void ExtractParameterDetails(ActionModel action) { _propertiesToHideFromOpenApi.TryAdd( requestParameter.ParameterType, - requestParameter.ParameterType.GetProperties().Select(z => z.Name).Except( - requestParameter.Attributes.OfType().SelectMany(z => z.Include) - ).ToArray() + requestParameter + .ParameterType.GetProperties() + .Select(z => z.Name) + .Except( + requestParameter.Attributes.OfType().SelectMany(z => z.Include) + ) + .ToArray() ); return; } var index = action.Parameters.IndexOf(requestParameter); var newAttributes = requestParameter.Attributes.ToList(); - var otherParams = action.Parameters - .Except(new[] { requestParameter }) - .Select(z => z.ParameterName) - .ToArray(); - - var propertyAndFieldNames = requestParameter.ParameterType - .GetProperties() - .Select(z => z.Name) - .ToArray(); + var otherParams = action + .Parameters + .Except(new[] { requestParameter, }) + .Select(z => z.ParameterName) + .ToArray(); + + var propertyAndFieldNames = requestParameter + .ParameterType + .GetProperties() + .Select(z => z.Name) + .ToArray(); var bindNames = propertyAndFieldNames .Except(otherParams, StringComparer.OrdinalIgnoreCase) .ToArray(); @@ -81,11 +87,11 @@ private static void ExtractParameterDetails(ActionModel action) ); _propertiesToHideFromOpenApi.TryAdd(requestParameter.ParameterType, ignoreBindings); - var model = action.Parameters[index] = new ParameterModel(requestParameter.ParameterInfo, newAttributes) + var model = action.Parameters[index] = new(requestParameter.ParameterInfo, newAttributes) { Action = requestParameter.Action, BindingInfo = requestParameter.BindingInfo, - ParameterName = requestParameter.ParameterName + ParameterName = requestParameter.ParameterName, }; foreach (var item in requestParameter.Properties) { @@ -100,7 +106,8 @@ private static void ExtractParameterDetails(ActionModel action) private readonly RestfulApiOptions _options; /// - /// An action model convention that allows and to be used as parameters to controller actions. + /// An action model convention that allows and to be used as parameters to + /// controller actions. /// /// public RestfulApiActionModelConvention(IOptions options) @@ -113,8 +120,9 @@ private void UpdateProviders( ActionModel actionModel ) { - var providerLookup = actionModel.Filters.OfType() - .ToLookup(x => x.StatusCode); + var providerLookup = actionModel + .Filters.OfType() + .ToLookup(x => x.StatusCode); var hasSuccess = providerLookup.Any(z => z.Key is >= 200 and < 300); var match = _matchers @@ -124,53 +132,35 @@ ActionModel actionModel .SelectMany(z => z) .Any(z => z is IApiDefaultResponseMetadataProvider); - if (!hasDefault) - { - actionModel.Filters.Add(new ProducesDefaultResponseTypeAttribute()); - } + if (!hasDefault) actionModel.Filters.Add(new ProducesDefaultResponseTypeAttribute()); if (!hasSuccess) { if (actionModel.ActionMethod.ReturnType == typeof(Task)) - { actionModel.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status204NoContent)); - } else if (match != null) - { actionModel.Filters.Add(new ProducesResponseTypeAttribute(_options.MethodStatusCodeMap[match.Method])); - } else - { actionModel.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status200OK)); - } } if (!providerLookup[StatusCodes.Status404NotFound].Any() && match?.Method != RestfulApiMethod.List) - { actionModel.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status404NotFound)); - } if (!providerLookup[StatusCodes.Status400BadRequest].Any()) - { actionModel.Filters.Add(new ProducesResponseTypeAttribute(typeof(ProblemDetails), StatusCodes.Status400BadRequest)); - } if (!providerLookup[_options.ValidationStatusCode].Any()) - { actionModel.Filters.Add( new ProducesResponseTypeAttribute(typeof(FluentValidationProblemDetails), _options.ValidationStatusCode) ); - } } // 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)) - { - return; - } + if (!typeof(RestfulApiController).IsAssignableFrom(action.Controller.ControllerType)) return; var httpMethod = GetHttpMethod(action); if (string.IsNullOrWhiteSpace(httpMethod)) @@ -183,13 +173,11 @@ public void Apply(ActionModel action) public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if (_propertiesToHideFromOpenApi.TryGetValue(context.Type, out var propertiesToRemove)) - { foreach (var property in propertiesToRemove .Join(schema.Properties, z => z, z => z.Key, (_, b) => b.Key, StringComparer.OrdinalIgnoreCase) .ToArray()) { schema.Properties.Remove(property); } - } } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs b/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs index de1c4c71b..8f5d52da7 100644 --- a/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs +++ b/src/AspNetCore/Composition/RestfulApiApplicationModelProvider.cs @@ -7,17 +7,14 @@ internal class RestfulApiApplicationModelProvider(IOptions op { public List ActionModelConventions { get; } = new() { - new RestfulApiActionModelConvention(options) + new RestfulApiActionModelConvention(options), }; public void OnProvidersExecuted(ApplicationModelProviderContext context) { foreach (var controller in context.Result.Controllers) { - if (!typeof(RestfulApiController).IsAssignableFrom(controller.ControllerType)) - { - return; - } + if (!typeof(RestfulApiController).IsAssignableFrom(controller.ControllerType)) return; foreach (var action in controller.Actions) { @@ -29,9 +26,7 @@ public void OnProvidersExecuted(ApplicationModelProviderContext context) } } - public void OnProvidersExecuting(ApplicationModelProviderContext context) - { - } + public void OnProvidersExecuting(ApplicationModelProviderContext context) { } public int Order => -1000; -} +} \ No newline at end of file diff --git a/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs b/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs index 7a44f2fb3..76bba5400 100644 --- a/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs +++ b/src/AspNetCore/Composition/RestfulApiMethodBuilder.cs @@ -11,7 +11,7 @@ public class RestfulApiMethodBuilder : IRestfulApiMethodMatcher { private static RestfulApiParameterMatcher defaultMatcher(Index index) { - return new RestfulApiParameterMatcher( + return new( index, ApiConventionNameMatchBehavior.Any, Array.Empty(), @@ -44,7 +44,7 @@ public RestfulApiMethodBuilder(RestfulApiMethod method) /// public RestfulApiMethodBuilder MatchSuffix(string value, params string[] values) { - _names = new[] { value }.Concat(values).ToArray(); + _names = new[] { value, }.Concat(values).ToArray(); _nameMatchBehavior = ApiConventionNameMatchBehavior.Suffix; return this; @@ -58,7 +58,7 @@ public RestfulApiMethodBuilder MatchSuffix(string value, params string[] values) /// public RestfulApiMethodBuilder MatchPrefix(string value, params string[] values) { - _names = new[] { value }.Concat(values).ToArray(); + _names = new[] { value, }.Concat(values).ToArray(); _nameMatchBehavior = ApiConventionNameMatchBehavior.Prefix; return this; @@ -72,7 +72,7 @@ public RestfulApiMethodBuilder MatchPrefix(string value, params string[] values) /// public RestfulApiMethodBuilder MatchName(string value, params string[] values) { - _names = new[] { value }.Concat(values).ToArray(); + _names = new[] { value, }.Concat(values).ToArray(); _nameMatchBehavior = ApiConventionNameMatchBehavior.Exact; return this; @@ -90,15 +90,12 @@ public RestfulApiMethodBuilder MatchName(string value, params string[] values) /// public RestfulApiMethodBuilder MatchParameterName(Index parameter, string value, params string[] values) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = defaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = defaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, ApiConventionNameMatchBehavior.Exact, - new[] { value }.Concat(values).ToArray(), + new[] { value, }.Concat(values).ToArray(), item.TypeMatch, item.Type ); @@ -116,10 +113,7 @@ public RestfulApiMethodBuilder MatchParameterName(Index parameter, string value, /// public RestfulApiMethodBuilder HasParameter(Index parameter) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = defaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = defaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( @@ -156,15 +150,12 @@ public RestfulApiMethodBuilder MatchParameterCount(int count) /// public RestfulApiMethodBuilder MatchParameterPrefix(Index parameter, string value, params string[] values) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = defaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = defaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, ApiConventionNameMatchBehavior.Prefix, - new[] { value }.Concat(values).ToArray(), + new[] { value, }.Concat(values).ToArray(), item.TypeMatch, item.Type ); @@ -184,15 +175,12 @@ public RestfulApiMethodBuilder MatchParameterPrefix(Index parameter, string valu /// public RestfulApiMethodBuilder MatchParameterSuffix(Index parameter, string value, params string[] values) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = defaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = defaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, ApiConventionNameMatchBehavior.Suffix, - new[] { value }.Concat(values).ToArray(), + new[] { value, }.Concat(values).ToArray(), item.TypeMatch, item.Type ); @@ -211,10 +199,7 @@ public RestfulApiMethodBuilder MatchParameterSuffix(Index parameter, string valu /// public RestfulApiMethodBuilder MatchParameterType(Index parameter, Type type) { - if (!_parameters.TryGetValue(parameter, out var item)) - { - item = _parameters[parameter] = defaultMatcher(parameter); - } + if (!_parameters.TryGetValue(parameter, out var item)) item = _parameters[parameter] = defaultMatcher(parameter); _parameters[parameter] = new RestfulApiParameterMatcher( parameter, @@ -236,26 +221,24 @@ internal bool IsValid() internal bool IsMatch(ActionModel actionModel) { var nameMatch = _nameMatchBehavior switch - { - ApiConventionNameMatchBehavior.Exact => _names.Any(name => actionModel.ActionName.Equals(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Prefix => _names.Any(name => actionModel.ActionName.StartsWith(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Suffix => _names.Any(name => actionModel.ActionName.EndsWith(name, StringComparison.OrdinalIgnoreCase)), - _ => true - }; + { + ApiConventionNameMatchBehavior.Exact => _names.Any(name => actionModel.ActionName.Equals(name, StringComparison.OrdinalIgnoreCase)), + ApiConventionNameMatchBehavior.Prefix => _names.Any( + name => actionModel.ActionName.StartsWith(name, StringComparison.OrdinalIgnoreCase) + ), + ApiConventionNameMatchBehavior.Suffix => _names.Any( + name => actionModel.ActionName.EndsWith(name, StringComparison.OrdinalIgnoreCase) + ), + _ => true, + }; if (!nameMatch) return false; var parameters = actionModel.ActionMethod.GetParameters(); - if (_parameterCount.HasValue && parameters.Length != _parameterCount.Value) - { - return false; - } + if (_parameterCount.HasValue && parameters.Length != _parameterCount.Value) return false; - if (parameters.Length >= _parameters.Count) - { - return _parameters.Values.All(z => z.IsMatch(actionModel)); - } + if (parameters.Length >= _parameters.Count) return _parameters.Values.All(z => z.IsMatch(actionModel)); return false; } @@ -270,4 +253,4 @@ bool IRestfulApiMethodMatcher.IsMatch(ActionModel actionModel) { return IsMatch(actionModel); } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs b/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs index 4eb2e602b..c8cf217f0 100644 --- a/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs +++ b/src/AspNetCore/Composition/RestfulApiParameterMatcher.cs @@ -6,7 +6,8 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Composition; -internal class RestfulApiParameterMatcher( +internal class RestfulApiParameterMatcher +( Index parameterIndex, ApiConventionNameMatchBehavior nameMatch, string[] names, @@ -36,10 +37,7 @@ public bool IsMatch(ActionModel actionModel) var parameterIs = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == Type; if (!parameterIs) parameterIs = parameter.ParameterType.GetInterfaces().Any(inter => inter.IsGenericType && inter.GetGenericTypeDefinition() == Type); - if (!parameterIs) - { - return false; - } + if (!parameterIs) return false; } else if (!Type.IsAssignableFrom(parameter.ParameterType)) { @@ -49,12 +47,12 @@ public bool IsMatch(ActionModel actionModel) // ReSharper disable NullableWarningSuppressionIsUsed return NameMatch switch - { - ApiConventionNameMatchBehavior.Exact => Names.Any(name => parameter.Name!.Equals(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Prefix => Names.Any(name => parameter.Name!.StartsWith(name, StringComparison.OrdinalIgnoreCase)), - ApiConventionNameMatchBehavior.Suffix => Names.Any(name => parameter.Name!.EndsWith(name, StringComparison.OrdinalIgnoreCase)), - _ => true - }; + { + ApiConventionNameMatchBehavior.Exact => Names.Any(name => parameter.Name!.Equals(name, StringComparison.OrdinalIgnoreCase)), + ApiConventionNameMatchBehavior.Prefix => Names.Any(name => parameter.Name!.StartsWith(name, StringComparison.OrdinalIgnoreCase)), + ApiConventionNameMatchBehavior.Suffix => Names.Any(name => parameter.Name!.EndsWith(name, StringComparison.OrdinalIgnoreCase)), + _ => true, + }; // ReSharper enable NullableWarningSuppressionIsUsed } @@ -62,4 +60,4 @@ public bool IsMatch(ActionModel actionModel) } } -// IApiDescriptionProvider +// IApiDescriptionProvider \ No newline at end of file diff --git a/src/AspNetCore/Conventions/AspNetCoreConvention.cs b/src/AspNetCore/Conventions/AspNetCoreConvention.cs index abf828815..c739bcfd5 100644 --- a/src/AspNetCore/Conventions/AspNetCoreConvention.cs +++ b/src/AspNetCore/Conventions/AspNetCoreConvention.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.Conventions.Reflection; using Rocket.Surgery.LaunchPad.AspNetCore.Filters; namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions; @@ -28,12 +27,10 @@ IEnumerable assemblies foreach (var assembly in assemblies) { if (!seenAssemblies.Add(assembly)) - { // "assemblies" may contain duplicate values, but we want unique ApplicationPart instances. // Note that we prefer using a HashSet over Distinct since the latter isn't // guaranteed to preserve the original ordering. continue; - } var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly); foreach (var applicationPart in partFactory.GetApplicationParts(assembly)) @@ -54,10 +51,11 @@ private static IEnumerable GetApplicationPartAssemblies(Assembly assem { // Use ApplicationPartAttribute to get the closure of direct or transitive dependencies // that reference MVC. - var assembliesFromAttributes = assembly.GetCustomAttributes() - .Select(name => Assembly.Load(name.AssemblyName)) - .OrderBy(a => a.FullName, StringComparer.Ordinal) - .SelectMany(GetAssemblyClosure); + var assembliesFromAttributes = assembly + .GetCustomAttributes() + .Select(name => Assembly.Load(name.AssemblyName)) + .OrderBy(a => a.FullName, StringComparer.Ordinal) + .SelectMany(GetAssemblyClosure); // The SDK will not include the entry assembly as an application part. We'll explicitly list it // and have it appear before all other assemblies \ ApplicationParts. @@ -69,8 +67,9 @@ private static IEnumerable GetAssemblyClosure(Assembly assembly) { yield return assembly; - var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, false) - .OrderBy(a => a.FullName, StringComparer.Ordinal); + var relatedAssemblies = RelatedAssemblyAttribute + .GetRelatedAssemblies(assembly, false) + .OrderBy(a => a.FullName, StringComparer.Ordinal); foreach (var relatedAssembly in relatedAssemblies) { @@ -98,24 +97,19 @@ public AspNetCoreConvention(AspNetCoreOptions? options = null) /// TODO Edit XML Comment Template for Register public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); services -#if NET6_0_OR_GREATER .AddEndpointsApiExplorer() -#endif .AddMvcCore() .AddApiExplorer(); PopulateDefaultParts( // ReSharper disable once NullableWarningSuppressionIsUsed GetServiceFromCollection(services)!, - context.AssemblyCandidateFinder - .GetCandidateAssemblies("Rocket.Surgery.LaunchPad.AspNetCore") - .Where(_options.AssemblyPartFilter) - .SelectMany(GetApplicationPartAssemblies) + context + .AssemblyProvider.GetAssemblies(s => s.FromAssemblyDependenciesOf(typeof(AspNetCoreConvention))) + .Where(_options.AssemblyPartFilter) + .SelectMany(GetApplicationPartAssemblies) ); services.Configure( @@ -129,4 +123,4 @@ public void Register(IConventionContext context, IConfiguration configuration, I } ); } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs b/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs index d8b642a7c..1f9e17776 100644 --- a/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs +++ b/src/AspNetCore/Conventions/AspNetCoreConventionInstrumentationConvention.cs @@ -1,32 +1,27 @@ 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.AspNetCore.Conventions; /// -/// ProblemDetailsConvention. -/// Implements the +/// AspNetCoreConventionInstrumentationConvention. +/// Implements the /// -/// -/// +/// +/// [PublicAPI] [ExportConvention] [AfterConvention(typeof(AspNetCoreConvention))] -public class AspNetCoreConventionInstrumentationConvention : IOpenTelemetryMetricsConvention, IOpenTelemetryTracingConvention +public class AspNetCoreConventionInstrumentationConvention : IOpenTelemetryConvention { /// - public void Register(IConventionContext conventionContext, IConfiguration configuration, MeterProviderBuilder builder) + public void Register(IConventionContext conventionContext, IConfiguration configuration, IOpenTelemetryBuilder builder) { - builder.AddAspNetCoreInstrumentation(); + builder.WithTracing(b => b.AddAspNetCoreInstrumentation(options => options.RecordException = true)); + builder.WithMetrics(b => b.AddAspNetCoreInstrumentation()); } - - /// - public void Register(IConventionContext conventionContext, IConfiguration configuration, TracerProviderBuilder builder) - { - builder.AddAspNetCoreInstrumentation(options => options.RecordException = true); - } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Conventions/FluentValidationConvention.cs b/src/AspNetCore/Conventions/FluentValidationConvention.cs index d6068f750..861692e59 100644 --- a/src/AspNetCore/Conventions/FluentValidationConvention.cs +++ b/src/AspNetCore/Conventions/FluentValidationConvention.cs @@ -1,17 +1,10 @@ -using System.Reflection; -using FluentValidation.AspNetCore; -using FluentValidation.Validators; -using MicroElements.OpenApi.FluentValidation; -using MicroElements.Swashbuckle.FluentValidation; +using FluentValidation.AspNetCore; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Any; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.Extensions; using Rocket.Surgery.LaunchPad.AspNetCore.Validation; -using Rocket.Surgery.LaunchPad.Foundation.Validation; namespace Rocket.Surgery.LaunchPad.AspNetCore.Conventions; @@ -28,91 +21,91 @@ public partial class FluentValidationConvention : IServiceConvention { private static void AddFluentValidationRules(IServiceCollection services) { - services.AddSingleton( - new FluentValidationRule("NotEmpty") - .WithCondition(propertyValidator => propertyValidator is INotEmptyValidator) - .WithApply( - context => - { - var ruleContext = ( (ValidationRuleContext)context - .GetType() - .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) - .First(z => z.PropertyType == typeof(ValidationRuleContext)) - .GetValue(context)! ) - .GetReflectionContext(); - var propertyType = ruleContext?.PropertyInfo?.DeclaringType; - if (propertyType == typeof(string)) - { - context.Schema.Properties[context.PropertyKey].MinLength = 1; - } - } - ) - ); - - services.AddSingleton( - new FluentValidationRule("ValueTypeOrEnum") - .WithApply( - context => - { - var ruleContext = ( (ValidationRuleContext)context - .GetType() - .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) - .First(z => z.PropertyType == typeof(ValidationRuleContext)) - .GetValue(context)! ) - .GetReflectionContext(); - var propertyType = ruleContext?.PropertyInfo?.DeclaringType; - if (propertyType != null && ( ( propertyType.IsValueType && Nullable.GetUnderlyingType(propertyType) == null ) || propertyType.IsEnum )) - { - context.Schema.Required.Add(context.PropertyKey); - context.Schema.Properties[context.PropertyKey].Nullable = false; - } - } - ) - ); - - services.AddSingleton( - new FluentValidationRule("Nullable") - .WithApply( - context => - { - var ruleContext = ( (ValidationRuleContext)context - .GetType() - .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) - .First(z => z.PropertyType == typeof(ValidationRuleContext)) - .GetValue(context)! ) - .GetReflectionContext(); - context.Schema.Properties[context.PropertyKey].Nullable = - context.PropertyValidator is not (INotNullValidator or INotEmptyValidator) - || ( ruleContext is { PropertyInfo: FieldInfo fi, } && getNullableValue(fi.GetNullability(), fi.FieldType) ) - ; - - static bool getNullableValue(Nullability nullability, Type propertyType) - { - return nullability switch - { - Nullability.Nullable => true, - Nullability.NonNullable => false, - Nullability.NotDefined => !propertyType.IsValueType || Nullable.GetUnderlyingType(propertyType) is { }, - _ => false, - }; - } - } - ) - ); - - services.AddSingleton( - new FluentValidationRule("IsOneOf") - .WithCondition(propertyValidator => propertyValidator is IStringInValidator) - .WithApply( - context => - { - 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(); - } - ) - ); +// services.AddSingleton( +// new FluentValidationRule("NotEmpty") +// .WithCondition(propertyValidator => propertyValidator is INotEmptyValidator) +// .WithApply( +// context => +// { +// var ruleContext = ( (ValidationRuleContext)context +// .GetType() +// .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) +// .First(z => z.PropertyType == typeof(ValidationRuleContext)) +// .GetValue(context)! ) +// .GetReflectionContext(); +// var propertyType = ruleContext?.PropertyInfo?.DeclaringType; +// if (propertyType == typeof(string)) +// { +// (context.Schema.Properties[context.PropertyKey] ??= new ()).MinLength = 1; +// } +// } +// ) +// ); +// +// services.AddSingleton( +// new FluentValidationRule("ValueTypeOrEnum") +// .WithApply( +// context => +// { +// var ruleContext = ( (ValidationRuleContext)context +// .GetType() +// .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) +// .First(z => z.PropertyType == typeof(ValidationRuleContext)) +// .GetValue(context)! ) +// .GetReflectionContext(); +// var propertyType = ruleContext?.PropertyInfo?.DeclaringType; +// if (propertyType != null && ( ( propertyType.IsValueType && Nullable.GetUnderlyingType(propertyType) == null ) || propertyType.IsEnum )) +// { +// context.Schema.Required.Add(context.PropertyKey); +// (context.Schema.Properties[context.PropertyKey] ??= new ()).Nullable = false; +// } +// } +// ) +// ); +// +// services.AddSingleton( +// new FluentValidationRule("Nullable") +// .WithApply( +// context => +// { +// var ruleContext = ( (ValidationRuleContext)context +// .GetType() +// .GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) +// .First(z => z.PropertyType == typeof(ValidationRuleContext)) +// .GetValue(context)! ) +// .GetReflectionContext(); +// (context.Schema.Properties[context.PropertyKey] ??= new ()).Nullable = +// context.PropertyValidator is not (INotNullValidator or INotEmptyValidator) +// || ( ruleContext is { PropertyInfo: FieldInfo fi, } && getNullableValue(fi.GetNullability(), fi.FieldType) ) +// ; +// +// static bool getNullableValue(Nullability nullability, Type propertyType) +// { +// return nullability switch +// { +// Nullability.Nullable => true, +// Nullability.NonNullable => false, +// Nullability.NotDefined => !propertyType.IsValueType || Nullable.GetUnderlyingType(propertyType) is { }, +// _ => false, +// }; +// } +// } +// ) +// ); +// +// services.AddSingleton( +// new FluentValidationRule("IsOneOf") +// .WithCondition(propertyValidator => propertyValidator is IStringInValidator) +// .WithApply( +// context => +// { +// var validator = context.PropertyValidator as IStringInValidator; +// (context.Schema.Properties[context.PropertyKey] ??= new ()).Enum = +// // ReSharper disable once NullableWarningSuppressionIsUsed +// validator!.Values.Select(x => new OpenApiString(x)).Cast().ToList(); +// } +// ) +// ); } /// @@ -128,6 +121,6 @@ public void Register(IConventionContext context, IConfiguration configuration, I .Configure(mvcOptions => mvcOptions.Filters.Insert(0, new ValidationExceptionFilter())) .Configure(options => options.JsonSerializerOptions.Converters.Add(new ValidationProblemDetailsConverter())); - AddFluentValidationRules(services); +// AddFluentValidationRules(services); } } \ No newline at end of file diff --git a/src/AspNetCore/Conventions/ProblemDetailsConvention.cs b/src/AspNetCore/Conventions/ProblemDetailsConvention.cs index c1282a3d3..2873135a0 100644 --- a/src/AspNetCore/Conventions/ProblemDetailsConvention.cs +++ b/src/AspNetCore/Conventions/ProblemDetailsConvention.cs @@ -29,53 +29,57 @@ public class ProblemDetailsConvention : IServiceConvention /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - ProblemDetailsExtensions.AddProblemDetails(services) - .AddProblemDetailsConventions(); + ProblemDetailsExtensions + .AddProblemDetails(services) + .AddProblemDetailsConventions(); - services.AddOptions() - .Configure(static options => options.SuppressModelStateInvalidFilter = true); - services.AddOptions() - .Configure>( - static (builder, apiBehaviorOptions) => - { - var currentIncludeExceptionDetails = builder.IncludeExceptionDetails; - builder.IncludeExceptionDetails = (httpContext, exception) => - exception is not IProblemDetailsData && currentIncludeExceptionDetails(httpContext, exception); - builder.OnBeforeWriteDetails = (_, problemDetails) => - { - if ( - !problemDetails.Status.HasValue - || !apiBehaviorOptions.Value.ClientErrorMapping.TryGetValue(problemDetails.Status.Value, out var clientErrorData) - ) - { - return; - } + services + .AddOptions() + .Configure(static options => options.SuppressModelStateInvalidFilter = true); + services + .AddOptions() + .Configure>( + static (builder, apiBehaviorOptions) => + { + var currentIncludeExceptionDetails = builder.IncludeExceptionDetails; + builder.IncludeExceptionDetails = (httpContext, exception) => + exception is not IProblemDetailsData && currentIncludeExceptionDetails(httpContext, exception); + builder.OnBeforeWriteDetails = (_, problemDetails) => + { + if ( + !problemDetails.Status.HasValue + || !apiBehaviorOptions.Value.ClientErrorMapping.TryGetValue( + problemDetails.Status.Value, + out var clientErrorData + ) + ) + return; - problemDetails.Title ??= clientErrorData.Title; - problemDetails.Type ??= clientErrorData.Link; - }; + problemDetails.Title ??= clientErrorData.Title; + problemDetails.Type ??= clientErrorData.Link; + }; // builder.MapToProblemDetailsDataException(StatusCodes.Status404NotFound); // builder.MapToProblemDetailsDataException(StatusCodes.Status400BadRequest); // builder.MapToProblemDetailsDataException(StatusCodes.Status403Forbidden); - builder.Map( - static exception => new FluentValidationProblemDetails(exception.Errors) - { - Status = StatusCodes.Status422UnprocessableEntity - } - ); - builder.Map( - static (ctx, ex) => ex is not IProblemDetailsData && ctx.Items[typeof(ValidationResult)] is ValidationResult, - static (ctx, _) => - { - var result = ctx.Items[typeof(ValidationResult)] as ValidationResult; - // ReSharper disable once NullableWarningSuppressionIsUsed - return new FluentValidationProblemDetails(result!.Errors) - { - Status = StatusCodes.Status422UnprocessableEntity - }; - } - ); - } - ); + builder.Map( + static exception => new FluentValidationProblemDetails(exception.Errors) + { + Status = StatusCodes.Status422UnprocessableEntity, + } + ); + builder.Map( + static (ctx, ex) => ex is not IProblemDetailsData && ctx.Items[typeof(ValidationResult)] is ValidationResult, + static (ctx, _) => + { + var result = ctx.Items[typeof(ValidationResult)] as ValidationResult; + // ReSharper disable once NullableWarningSuppressionIsUsed + return new FluentValidationProblemDetails(result!.Errors) + { + Status = StatusCodes.Status422UnprocessableEntity, + }; + } + ); + } + ); } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Conventions/SwashbuckleConvention.cs b/src/AspNetCore/Conventions/SwashbuckleConvention.cs index c83656934..0e6779959 100644 --- a/src/AspNetCore/Conventions/SwashbuckleConvention.cs +++ b/src/AspNetCore/Conventions/SwashbuckleConvention.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Microsoft.OpenApi.Models; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Composition; @@ -42,10 +41,7 @@ public partial class SwashbuckleConvention : IServiceConvention /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); services.ConfigureOptions(); @@ -56,10 +52,11 @@ public void Register(IConventionContext context, IConfiguration configuration, I // services.TryAddEnumerable(ServiceDescriptor.Transient()); - services.AddOptions() - .Configure>( - (options, mvcOptions) => options.ConfigureForNodaTime(mvcOptions.Value.JsonSerializerOptions) - ); + services + .AddOptions() + .Configure>( + (options, mvcOptions) => options.ConfigureForNodaTime(mvcOptions.Value.JsonSerializerOptions) + ); services.AddSwaggerGen( options => { @@ -72,14 +69,14 @@ public void Register(IConventionContext context, IConfiguration configuration, I options.OperationFilter(); options.MapType( - () => new OpenApiSchema + () => new() { Type = "object", AdditionalPropertiesAllowed = true, } ); options.MapType( - () => new OpenApiSchema + () => new() { Type = "object", AdditionalPropertiesAllowed = true, @@ -112,7 +109,9 @@ string schemaIdSelector(Type type) name = name[..name.IndexOf('`', StringComparison.Ordinal)]; sb.Append(name); foreach (var gt in type.GetGenericArguments()) + { sb.Append('_').Append(schemaIdSelector(gt)); + } return sb.ToString(); } @@ -122,16 +121,17 @@ string schemaIdSelector(Type type) options.CustomSchemaIds(schemaIdSelector); - foreach (var item in Directory.EnumerateFiles(AppContext.BaseDirectory, "*.xml") - .Where(x => File.Exists(Path.ChangeExtension(x, "dll")))) + foreach (var item in Directory + .EnumerateFiles(AppContext.BaseDirectory, "*.xml") + .Where(x => File.Exists(Path.ChangeExtension(x, "dll")))) { try { options.IncludeXmlComments(item, true); } -#pragma warning disable CA1031 + #pragma warning disable CA1031 catch (Exception e) -#pragma warning restore CA1031 + #pragma warning restore CA1031 { ErrorAddingXMLComments(context.Logger, e, item); } @@ -139,4 +139,4 @@ string schemaIdSelector(Type type) } ); } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Conventions/SystemJsonTextConvention.cs b/src/AspNetCore/Conventions/SystemJsonTextConvention.cs index f6c2aa25a..418175af6 100644 --- a/src/AspNetCore/Conventions/SystemJsonTextConvention.cs +++ b/src/AspNetCore/Conventions/SystemJsonTextConvention.cs @@ -38,10 +38,7 @@ public SystemJsonTextConvention(FoundationOptions? options = null) /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); services .AddOptions() @@ -51,4 +48,4 @@ public void Register(IConventionContext context, IConfiguration configuration, I .Create(nameof(JsonOptions)) ); } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs b/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs index 9ae38e860..c86bc6516 100644 --- a/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs +++ b/src/AspNetCore/Filters/SerilogLoggingPageFilter.cs @@ -8,18 +8,11 @@ internal class SerilogLoggingPageFilter(IDiagnosticContext diagnosticContext) : public void OnPageHandlerSelected(PageHandlerSelectedContext context) { var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name; - if (name != null) - { - diagnosticContext.Set("RazorPageHandler", name); - } + if (name != null) diagnosticContext.Set("RazorPageHandler", name); } // Required by the interface - public void OnPageHandlerExecuted(PageHandlerExecutedContext context) - { - } + public void OnPageHandlerExecuted(PageHandlerExecutedContext context) { } - public void OnPageHandlerExecuting(PageHandlerExecutingContext context) - { - } -} + public void OnPageHandlerExecuting(PageHandlerExecutingContext context) { } +} \ No newline at end of file diff --git a/src/AspNetCore/LaunchPadHelpers.cs b/src/AspNetCore/LaunchPadHelpers.cs index cedc83c1b..13aee1ba8 100644 --- a/src/AspNetCore/LaunchPadHelpers.cs +++ b/src/AspNetCore/LaunchPadHelpers.cs @@ -24,10 +24,7 @@ public static void DefaultEnrichDiagnosticContext(IDiagnosticContext diagnosticC diagnosticContext.Set("Scheme", request.Scheme); // Only set it if available. You're not sending sensitive data in a querystring right?! - if (request.QueryString.HasValue) - { - diagnosticContext.Set("QueryString", request.QueryString.Value); - } + if (request.QueryString.HasValue) diagnosticContext.Set("QueryString", request.QueryString.Value); // Set the content-type of the Response at this point diagnosticContext.Set("ContentType", httpContext.Response.ContentType); @@ -35,9 +32,7 @@ public static void DefaultEnrichDiagnosticContext(IDiagnosticContext diagnosticC // Retrieve the IEndpointFeature selected for the request var endpoint = httpContext.GetEndpoint(); if (endpoint is { }) // endpoint != null - { diagnosticContext.Set("EndpointName", endpoint.DisplayName); - } } /// @@ -54,7 +49,7 @@ public static LogEventLevel DefaultGetLevel(HttpContext ctx, double _, Exception : ctx.Response.StatusCode > 499 ? LogEventLevel.Error : IsHealthCheckEndpoint(ctx) // Not an error, check if it was a health check - ? LogEventLevel.Verbose // Was a health check, use Verbose + ? LogEventLevel.Verbose // Was a health check, use Verbose : LogEventLevel.Information; } @@ -62,11 +57,9 @@ private static bool IsHealthCheckEndpoint(HttpContext ctx) { var endpoint = ctx.GetEndpoint(); if (endpoint is { }) // same as !(endpoint is null) - { return string.Equals(endpoint.DisplayName, "Health checks", StringComparison.Ordinal); - } // No endpoint, so not a health check endpoint return false; } -} +} \ No newline at end of file diff --git a/src/AspNetCore/OpenApi/AuthorizeFilter.cs b/src/AspNetCore/OpenApi/AuthorizeFilter.cs index 4be834272..1aed4d4a1 100644 --- a/src/AspNetCore/OpenApi/AuthorizeFilter.cs +++ b/src/AspNetCore/OpenApi/AuthorizeFilter.cs @@ -9,29 +9,25 @@ public void Apply(OpenApiOperation operation, OperationFilterContext context) { // enhance the 401/403 with the media response if (operation.Responses.TryGetValue("401", out var value)) - { value.Headers.Add( "www-authenticate", - new OpenApiHeader + new() { // Required = true, - Schema = new OpenApiSchema { Type = "string" }, - Description = "The error details" + Schema = new() { Type = "string", }, + Description = "The error details", } ); - } if (operation.Responses.TryGetValue("403", out value)) - { value.Headers.Add( "www-authenticate", - new OpenApiHeader + new() { // Required = true, - Schema = new OpenApiSchema { Type = "string" }, - Description = "The error details" + Schema = new() { Type = "string", }, + Description = "The error details", } ); - } } -} +} \ No newline at end of file diff --git a/src/AspNetCore/OpenApi/NodaTimeSwashbuckleExtensions.cs b/src/AspNetCore/OpenApi/NodaTimeSwashbuckleExtensions.cs index b2cad6593..600a56b56 100644 --- a/src/AspNetCore/OpenApi/NodaTimeSwashbuckleExtensions.cs +++ b/src/AspNetCore/OpenApi/NodaTimeSwashbuckleExtensions.cs @@ -20,20 +20,19 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J ) { yield return ( type, - () => new OpenApiSchema + () => new() { Type = "string", Format = format, Example = new OpenApiString(JsonSerializer.Serialize(value, settings).Trim('"')), Extensions = new Dictionary { - ["clrType"] = new OpenApiString(type.FullName) - } + ["clrType"] = new OpenApiString(type.FullName), + }, } ); if (type.IsValueType) - { yield return ( typeof(Nullable<>).MakeGenericType(type), - () => new OpenApiSchema + () => new() { Type = "string", Format = format, @@ -43,10 +42,9 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J Nullable = true, Extensions = new Dictionary { - ["clrType"] = new OpenApiString(type.FullName) - } + ["clrType"] = new OpenApiString(type.FullName), + }, } ); - } } var instant = Instant.FromUnixTimeSeconds(1573000000); @@ -68,9 +66,12 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J interval.End.InZone(dateTimeZone).LocalDateTime, PeriodUnits.AllUnits ); - foreach (var (type, schema) in instantSchemas) + foreach (( var type, var schema ) in instantSchemas) + { c.MapType(type, schema); - foreach (var (type, schema) in createStringSchema( + } + + foreach (( var type, var schema ) in createStringSchema( typeof(LocalDate), LocalDate.FromDateTime(instant.ToDateTimeUtc()), "date" @@ -79,7 +80,7 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema( + foreach (( var type, var schema ) in createStringSchema( typeof(LocalTime), LocalTime.FromSecondsSinceMidnight(86400 - 12300), "time" @@ -88,7 +89,7 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema( + foreach (( var type, var schema ) in createStringSchema( typeof(LocalDateTime), LocalDateTime.FromDateTime(instant.ToDateTimeUtc()), "date-time" @@ -97,7 +98,7 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema( + foreach (( var type, var schema ) in createStringSchema( typeof(OffsetDateTime), OffsetDateTime.FromDateTimeOffset(instant.ToDateTimeOffset()), "date-time" @@ -106,27 +107,27 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema(typeof(ZonedDateTime), zonedDateTime, "date-time")) + foreach (( var type, var schema ) in createStringSchema(typeof(ZonedDateTime), zonedDateTime, "date-time")) { c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema(typeof(Offset), zonedDateTime.Offset)) + foreach (( var type, var schema ) in createStringSchema(typeof(Offset), zonedDateTime.Offset)) { c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema(typeof(Period), period)) + foreach (( var type, var schema ) in createStringSchema(typeof(Period), period)) { c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema(typeof(Duration), interval.Duration)) + foreach (( var type, var schema ) in createStringSchema(typeof(Duration), interval.Duration)) { c.MapType(type, schema); } - foreach (var (type, schema) in createStringSchema(typeof(DateTimeZone), dateTimeZone)) + foreach (( var type, var schema ) in createStringSchema(typeof(DateTimeZone), dateTimeZone)) { c.MapType(type, schema); } @@ -135,20 +136,20 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J () => { var instantSchema = instantSchemas[0].schema(); - return new OpenApiSchema + return new() { Type = "object", Nullable = false, Properties = { ["start"] = instantSchema, ["end"] = instantSchema, }, Extensions = new Dictionary { - ["clrType"] = new OpenApiString(typeof(Interval).FullName) - } + ["clrType"] = new OpenApiString(typeof(Interval).FullName), + }, }; } ); c.MapType( - () => new OpenApiSchema + () => new() { Type = "object", Nullable = true, @@ -156,11 +157,11 @@ public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c, J Extensions = new Dictionary { - ["clrType"] = new OpenApiString(typeof(Interval).FullName) - } + ["clrType"] = new OpenApiString(typeof(Interval).FullName), + }, } ); return c; } -} +} \ No newline at end of file diff --git a/src/AspNetCore/OpenApi/OperationIdFilter.cs b/src/AspNetCore/OpenApi/OperationIdFilter.cs index 90db7b577..97625e9ae 100644 --- a/src/AspNetCore/OpenApi/OperationIdFilter.cs +++ b/src/AspNetCore/OpenApi/OperationIdFilter.cs @@ -26,22 +26,19 @@ private static string Pascalize(string input) private static string Camelize(string input) { var word = Pascalize(input); -#pragma warning disable CA1308 + #pragma warning disable CA1308 return word.Length > 0 ? string.Concat(word.Substring(0, 1).ToLower(CultureInfo.InvariantCulture), word.AsSpan(1)) : word; -#pragma warning restore CA1308 + #pragma warning restore CA1308 } public void Apply(OpenApiOperation operation, OperationFilterContext context) { - if (string.IsNullOrWhiteSpace(operation.OperationId) && - context.ApiDescription.ActionDescriptor is ControllerActionDescriptor cad) - { + if (string.IsNullOrWhiteSpace(operation.OperationId) && context.ApiDescription.ActionDescriptor is ControllerActionDescriptor cad) operation.OperationId = cad.ActionName; - } foreach (var parameter in operation.Parameters) { parameter.Name = Camelize(parameter.Name); } } -} +} \ No newline at end of file diff --git a/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs b/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs index 159c4100f..418aa1c89 100644 --- a/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs +++ b/src/AspNetCore/OpenApi/StronglyTypedIdSchemaFilter.cs @@ -18,9 +18,7 @@ public static bool IsStronglyTypedId(Type? type) if (type?.GetMember("New", BindingFlags.Static | BindingFlags.Public).FirstOrDefault() is MethodInfo && type.GetMember("Empty", BindingFlags.Static | BindingFlags.Public).FirstOrDefault() is FieldInfo { } && type.GetMember("Value", BindingFlags.Instance | BindingFlags.Public).FirstOrDefault() is PropertyInfo propertyInfo) - { return propertyInfo.PropertyType; - } return null; } @@ -47,4 +45,4 @@ public void Apply(OpenApiSchema schema, SchemaFilterContext context) schema.Required = s2.Required; schema.Not = s2.Not; } -} +} \ No newline at end of file diff --git a/src/AspNetCore/RestfulApiController.cs b/src/AspNetCore/RestfulApiController.cs index 95af8120d..69808f5a6 100644 --- a/src/AspNetCore/RestfulApiController.cs +++ b/src/AspNetCore/RestfulApiController.cs @@ -29,15 +29,9 @@ protected async Task> Send( Func>> success ) { - if (request is null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); - if (success is null) - { - throw new ArgumentNullException(nameof(success)); - } + ArgumentNullException.ThrowIfNull(success); return await success(await Mediator.Send(request, HttpContext.RequestAborted).ConfigureAwait(false)) .ConfigureAwait(false); @@ -54,15 +48,9 @@ protected async Task> Send( Func> success ) { - if (request is null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); - if (success is null) - { - throw new ArgumentNullException(nameof(success)); - } + ArgumentNullException.ThrowIfNull(success); return success(await Mediator.Send(request, HttpContext.RequestAborted).ConfigureAwait(false)); } @@ -74,15 +62,9 @@ Func> success /// The method to call when the request succeeds protected async Task Send(IRequest request, Func success) { - if (request is null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); - if (success is null) - { - throw new ArgumentNullException(nameof(success)); - } + ArgumentNullException.ThrowIfNull(success); await Mediator.Send(request, HttpContext.RequestAborted).ConfigureAwait(false); return success(); @@ -94,12 +76,9 @@ protected async Task Send(IRequest request, /// The request model protected async Task Send(IRequest request) { - if (request is null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); await Mediator.Send(request, HttpContext.RequestAborted).ConfigureAwait(false); return NoContent(); } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj b/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj index 826891d40..980c40a4f 100644 --- a/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj +++ b/src/AspNetCore/Rocket.Surgery.LaunchPad.AspNetCore.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) false @@ -14,7 +14,6 @@ - diff --git a/src/AspNetCore/Validation/FluentValidationProblemDetails.cs b/src/AspNetCore/Validation/FluentValidationProblemDetails.cs index 6b7f41016..010102ec9 100644 --- a/src/AspNetCore/Validation/FluentValidationProblemDetails.cs +++ b/src/AspNetCore/Validation/FluentValidationProblemDetails.cs @@ -31,9 +31,7 @@ internal static FluentValidationProblemDetails From(ValidationProblemDetails val /// /// Construct the Fluent Validation Problem Details /// - public FluentValidationProblemDetails() : this(Array.Empty()) - { - } + public FluentValidationProblemDetails() : this(Array.Empty()) { } /// /// Build Fluent Validation Problem Details from a @@ -41,10 +39,7 @@ public FluentValidationProblemDetails() : this(Array.Empty()) /// public FluentValidationProblemDetails(ValidationResult result) : this(result.Errors) { - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } + ArgumentNullException.ThrowIfNull(result); Rules = result.RuleSetsExecuted; } @@ -55,10 +50,7 @@ public FluentValidationProblemDetails(ValidationResult result) : this(result.Err /// public FluentValidationProblemDetails(IEnumerable errors) { - if (errors == null) - { - throw new ArgumentNullException(nameof(errors)); - } + ArgumentNullException.ThrowIfNull(errors); ValidationErrors = errors .ToLookup(x => x.PropertyName) @@ -74,4 +66,4 @@ public FluentValidationProblemDetails(IEnumerable errors) /// The rules run with the validation /// public IEnumerable Rules { get; set; } = Array.Empty(); -} +} \ No newline at end of file diff --git a/src/AspNetCore/Validation/ValidationProblemDetailsConverter.cs b/src/AspNetCore/Validation/ValidationProblemDetailsConverter.cs index 69cdd53fe..20e6dad11 100644 --- a/src/AspNetCore/Validation/ValidationProblemDetailsConverter.cs +++ b/src/AspNetCore/Validation/ValidationProblemDetailsConverter.cs @@ -33,10 +33,7 @@ public override void Write( JsonSerializerOptions options ) { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } + ArgumentNullException.ThrowIfNull(writer); if (value == null) { @@ -52,9 +49,7 @@ JsonSerializerOptions options [UsedImplicitly] internal class AnnotatedProblemDetails { - public AnnotatedProblemDetails() - { - } + public AnnotatedProblemDetails() { } public AnnotatedProblemDetails(FluentValidationProblemDetails problemDetails) { @@ -76,15 +71,20 @@ public AnnotatedProblemDetails(FluentValidationProblemDetails problemDetails) } } - [JsonPropertyName("type")] public string? Type { get; set; } + [JsonPropertyName("type")] + public string? Type { get; set; } - [JsonPropertyName("title")] public string? Title { get; set; } + [JsonPropertyName("title")] + public string? Title { get; set; } - [JsonPropertyName("status")] public int? Status { get; set; } + [JsonPropertyName("status")] + public int? Status { get; set; } - [JsonPropertyName("detail")] public string? Detail { get; set; } + [JsonPropertyName("detail")] + public string? Detail { get; set; } - [JsonPropertyName("instance")] public string? Instance { get; set; } + [JsonPropertyName("instance")] + public string? Instance { get; set; } [JsonExtensionData] public IDictionary Extensions { get; } = @@ -94,7 +94,8 @@ public AnnotatedProblemDetails(FluentValidationProblemDetails problemDetails) public IDictionary Errors { get; } = new Dictionary(StringComparer.Ordinal); - [JsonPropertyName("rules")] public IEnumerable Rules { get; internal set; } = Array.Empty(); + [JsonPropertyName("rules")] + public IEnumerable Rules { get; internal set; } = Array.Empty(); public void CopyTo(FluentValidationProblemDetails problemDetails) { @@ -116,4 +117,4 @@ public void CopyTo(FluentValidationProblemDetails problemDetails) } } } -} +} \ No newline at end of file diff --git a/src/AspNetCore/Validation/ValidatorInterceptor.cs b/src/AspNetCore/Validation/ValidatorInterceptor.cs index 6b6f7573f..57682cfef 100644 --- a/src/AspNetCore/Validation/ValidatorInterceptor.cs +++ b/src/AspNetCore/Validation/ValidatorInterceptor.cs @@ -16,16 +16,14 @@ public ValidationResult AfterAspNetValidation(ActionContext actionContext, IVali { if (actionContext.ActionDescriptor.Properties.TryGetValue(typeof(CustomizeValidatorAttribute), out var value) && value is string[] includeProperties) - { - result = new ValidationResult( + result = new( result.Errors .Join(includeProperties, z => z.PropertyName, z => z, (a, _) => a, StringComparer.OrdinalIgnoreCase) ); - } if (result.IsValid) return result; actionContext.HttpContext.Items[typeof(ValidationResult)] = result; return result; } -} +} \ No newline at end of file diff --git a/src/EntityFramework/Rocket.Surgery.LaunchPad.EntityFramework.csproj b/src/EntityFramework/Rocket.Surgery.LaunchPad.EntityFramework.csproj index d47fa9655..daa22425d 100644 --- a/src/EntityFramework/Rocket.Surgery.LaunchPad.EntityFramework.csproj +++ b/src/EntityFramework/Rocket.Surgery.LaunchPad.EntityFramework.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/EntityFramework/SqliteDateTimeOffsetModelCreating.cs b/src/EntityFramework/SqliteDateTimeOffsetModelCreating.cs index c64cb7747..728c8398f 100644 --- a/src/EntityFramework/SqliteDateTimeOffsetModelCreating.cs +++ b/src/EntityFramework/SqliteDateTimeOffsetModelCreating.cs @@ -8,7 +8,6 @@ internal static class SqliteDateTimeOffsetModelCreating public static void OnModelCreating(DbContext context, ModelBuilder modelBuilder) { if (context.Database.ProviderName == "Microsoft.EntityFrameworkCore.Sqlite") - { // SQLite does not have proper support for DateTimeOffset via Entity Framework Core, see the limitations // here: https://docs.microsoft.com/en-us/ef/core/providers/sqlite/limitations#query-limitations // To work around this, when the Sqlite database provider is used, all model properties of type DateTimeOffset @@ -20,20 +19,17 @@ public static void OnModelCreating(DbContext context, ModelBuilder modelBuilder) foreach (var property in entityType.ClrType.GetProperties()) { if (property.PropertyType == typeof(DateTimeOffset) || property.PropertyType == typeof(DateTimeOffset?)) - { - modelBuilder.Entity(entityType.Name) - .Property(property.Name) - .HasConversion(new DateTimeOffsetToBinaryConverter()); - } + modelBuilder + .Entity(entityType.Name) + .Property(property.Name) + .HasConversion(new DateTimeOffsetToBinaryConverter()); if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?)) - { - modelBuilder.Entity(entityType.Name) - .Property(property.Name) - .HasConversion(new DateTimeToBinaryConverter()); - } + modelBuilder + .Entity(entityType.Name) + .Property(property.Name) + .HasConversion(new DateTimeToBinaryConverter()); } } - } } -} +} \ No newline at end of file diff --git a/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs b/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs index b069e8cd1..085f2e68b 100644 --- a/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs +++ b/src/Foundation.NewtonsoftJson/NewtonsoftJsonCompositeNodaPatternConverter.cs @@ -19,9 +19,7 @@ public sealed class NewtonsoftJsonCompositeNodaPatternConverter : NodaConvert /// Creates a new instance with a pattern and no validator. /// /// The patterns to use for parsing and formatting. - public NewtonsoftJsonCompositeNodaPatternConverter(params IPattern[] patterns) : this(null, patterns) - { - } + public NewtonsoftJsonCompositeNodaPatternConverter(params IPattern[] patterns) : this(null, patterns) { } /// /// Creates a new instance with a pattern and an optional validator. The validator will be called before each @@ -45,11 +43,9 @@ public NewtonsoftJsonCompositeNodaPatternConverter(Action? validator, params protected override T ReadJsonImpl(JsonReader reader, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) - { throw new InvalidNodaDataException( $"Unexpected token parsing {typeof(T).Name}. Expected String, got {reader.TokenType}." ); - } var text = reader.Value?.ToString(); @@ -77,4 +73,4 @@ protected override void WriteJsonImpl(JsonWriter writer, T value, JsonSerializer _validator?.Invoke(value); writer.WriteValue(_patterns[0].Format(value)); } -} +} \ No newline at end of file diff --git a/src/Foundation.NewtonsoftJson/Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson.csproj b/src/Foundation.NewtonsoftJson/Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson.csproj index efb085969..3f7d63226 100644 --- a/src/Foundation.NewtonsoftJson/Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson.csproj +++ b/src/Foundation.NewtonsoftJson/Rocket.Surgery.LaunchPad.Foundation.NewtonsoftJson.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) Rocket.Surgery.LaunchPad.Foundation diff --git a/src/Foundation/Assigned.cs b/src/Foundation/Assigned.cs index 18fa7c5bb..a538f7164 100644 --- a/src/Foundation/Assigned.cs +++ b/src/Foundation/Assigned.cs @@ -55,9 +55,9 @@ public static implicit operator Assigned(T value) /// Creates an empty Assigned that provides a default value. /// /// The default value. -#pragma warning disable CA1000 + #pragma warning disable CA1000 public static Assigned Empty(T? defaultValue = default) -#pragma warning restore CA1000 + #pragma warning restore CA1000 { return new(defaultValue, false); } @@ -115,10 +115,7 @@ public override string ToString() /// public override bool Equals(object? obj) { - if (obj is null) - { - return !_hasValue; - } + if (obj is null) return !_hasValue; return obj is Assigned n && Equals(n); } @@ -146,21 +143,12 @@ public override int GetHashCode() /// public bool Equals(Assigned? other) { - if (other is null) - { - return !_hasValue; - } + if (other is null) return !_hasValue; - if (!_hasValue && !other._hasValue) - { - return true; - } + if (!_hasValue && !other._hasValue) return true; - if (_hasValue != other._hasValue) - { - return false; - } + if (_hasValue != other._hasValue) return false; return Equals(Value, other.Value); } -} +} \ No newline at end of file diff --git a/src/Foundation/Conventions/FluentValidationConvention.cs b/src/Foundation/Conventions/FluentValidationConvention.cs index 321883dba..1a4405174 100644 --- a/src/Foundation/Conventions/FluentValidationConvention.cs +++ b/src/Foundation/Conventions/FluentValidationConvention.cs @@ -44,23 +44,32 @@ public FluentValidationConvention(FoundationOptions? options = null) /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); - services.AddValidatorsFromAssemblies( - context - .AssemblyCandidateFinder - .GetCandidateAssemblies("FluentValidation"), - _options.ValidatorLifetime, - includeInternalTypes: true + var types = context.AssemblyProvider.GetTypes( + z => z + .FromAssemblyDependenciesOf() + .GetTypes( + f => f + .AssignableTo(typeof(AbstractValidator<>)) + .NotInfoOf(TypeInfoFilter.Abstract) + .NotInfoOf(TypeInfoFilter.GenericType) + ) ); + foreach (var validator in types) + { + if (validator is not { BaseType: { IsGenericType: true, GenericTypeArguments: [var innerType,], }, }) continue; + var interfaceType = typeof(IValidator<>).MakeGenericType(innerType); + services.Add(new(interfaceType, validator, _options.ValidatorLifetime)); + services.Add(new(validator, validator, _options.ValidatorLifetime)); + } if (_options.RegisterValidationOptionsAsHealthChecks == true - || ( !_options.RegisterValidationOptionsAsHealthChecks.HasValue && Convert.ToBoolean( - context.Properties["RegisterValidationOptionsAsHealthChecks"], CultureInfo.InvariantCulture - ) ) + || ( !_options.RegisterValidationOptionsAsHealthChecks.HasValue + && Convert.ToBoolean( + context.Properties["RegisterValidationOptionsAsHealthChecks"], + CultureInfo.InvariantCulture + ) ) || Environment.CommandLine.Contains( "microsoft.extensions.apidescription.server", StringComparison.OrdinalIgnoreCase @@ -81,4 +90,4 @@ public void Register(IConventionContext context, IConfiguration configuration, I ServiceDescriptor.Describe(typeof(IStreamPipelineBehavior<,>), typeof(ValidationStreamPipelineBehavior<,>), _options.MediatorLifetime) ); } -} +} \ No newline at end of file diff --git a/src/Foundation/Conventions/InstrumentationConvention.cs b/src/Foundation/Conventions/InstrumentationConvention.cs index 1145af12d..c020f0c46 100644 --- a/src/Foundation/Conventions/InstrumentationConvention.cs +++ b/src/Foundation/Conventions/InstrumentationConvention.cs @@ -1,30 +1,25 @@ 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; /// /// InstrumentationConvention. -/// Implements and +/// Implements and /// -/// +/// [PublicAPI] [ExportConvention] -public class InstrumentationConvention : IOpenTelemetryMetricsConvention, IOpenTelemetryTracingConvention +public class InstrumentationConvention : IOpenTelemetryConvention { /// - public void Register(IConventionContext conventionContext, IConfiguration configuration, MeterProviderBuilder builder) + public void Register(IConventionContext conventionContext, IConfiguration configuration, IOpenTelemetryBuilder builder) { - builder.AddHttpClientInstrumentation(); + builder.WithTracing(b => b.AddHttpClientInstrumentation(x => x.RecordException = true)); + builder.WithMetrics(b => b.AddHttpClientInstrumentation()); } - - /// - public void Register(IConventionContext conventionContext, IConfiguration configuration, TracerProviderBuilder builder) - { - builder.AddHttpClientInstrumentation(x => x.RecordException = true); - } -} +} \ No newline at end of file diff --git a/src/Foundation/Conventions/MediatRConvention.cs b/src/Foundation/Conventions/MediatRConvention.cs index 0427952e9..cf649e1b1 100644 --- a/src/Foundation/Conventions/MediatRConvention.cs +++ b/src/Foundation/Conventions/MediatRConvention.cs @@ -1,8 +1,8 @@ -using Microsoft.Extensions.Configuration; +using MediatR; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.Conventions.Reflection; namespace Rocket.Surgery.LaunchPad.Foundation.Conventions; @@ -34,22 +34,22 @@ public MediatRConvention(FoundationOptions? options = null) /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { + // TODO: Look at converting this to use the assembly type provider + var assemblies = context.AssemblyProvider.GetAssemblies(x => x.FromAssemblyDependenciesOf()).ToArray(); + if (!assemblies.Any()) return; + services.AddMediatR( c => { - c.RegisterServicesFromAssemblies( - context.AssemblyCandidateFinder - .GetCandidateAssemblies(nameof(MediatR)) - .ToArray() - ); + c.RegisterServicesFromAssemblies(assemblies); c.Lifetime = _options switch - { - { MediatorLifetime: ServiceLifetime.Singleton } => ServiceLifetime.Singleton, - { MediatorLifetime: ServiceLifetime.Scoped } => ServiceLifetime.Scoped, - { MediatorLifetime: ServiceLifetime.Transient } => ServiceLifetime.Transient, - _ => c.Lifetime - }; + { + { MediatorLifetime: ServiceLifetime.Singleton, } => ServiceLifetime.Singleton, + { MediatorLifetime: ServiceLifetime.Scoped, } => ServiceLifetime.Scoped, + { MediatorLifetime: ServiceLifetime.Transient, } => ServiceLifetime.Transient, + _ => c.Lifetime, + }; } ); } -} +} \ No newline at end of file diff --git a/src/Foundation/Conventions/NodaTimeConvention.cs b/src/Foundation/Conventions/NodaTimeConvention.cs index 6ad08b5d3..4e403d7fd 100644 --- a/src/Foundation/Conventions/NodaTimeConvention.cs +++ b/src/Foundation/Conventions/NodaTimeConvention.cs @@ -43,12 +43,9 @@ public void Register(IConventionContext context, IServiceProvider services, ICon /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); services.TryAddSingleton(SystemClock.Instance); services.TryAddSingleton(new DateTimeZoneCache(_options.DateTimeZoneSource)); } -} +} \ No newline at end of file diff --git a/src/Foundation/ExistingValueOptionsFactory.cs b/src/Foundation/ExistingValueOptionsFactory.cs index f89a0e4d9..605d1f511 100644 --- a/src/Foundation/ExistingValueOptionsFactory.cs +++ b/src/Foundation/ExistingValueOptionsFactory.cs @@ -44,13 +44,8 @@ public TOptions Create(string name) foreach (var setup in _setups) { if (setup is IConfigureNamedOptions namedSetup) - { namedSetup.Configure(name, options); - } - else if (name == Options.DefaultName) - { - setup.Configure(options); - } + else if (name == Options.DefaultName) setup.Configure(options); } foreach (var post in _postConfigures) @@ -64,18 +59,12 @@ public TOptions Create(string name) foreach (var validate in _validations) { var result = validate.Validate(name, options); - if (result.Failed) - { - failures.AddRange(result.Failures); - } + if (result.Failed) failures.AddRange(result.Failures); } - if (failures.Count > 0) - { - throw new OptionsValidationException(name, typeof(TOptions), failures); - } + if (failures.Count > 0) throw new OptionsValidationException(name, typeof(TOptions), failures); } return options; } -} +} \ No newline at end of file diff --git a/src/Foundation/FluentValidationProblemDetail.cs b/src/Foundation/FluentValidationProblemDetail.cs index a37f38da4..e74df7522 100644 --- a/src/Foundation/FluentValidationProblemDetail.cs +++ b/src/Foundation/FluentValidationProblemDetail.cs @@ -18,7 +18,7 @@ public class FluentValidationProblemDetail /// public static implicit operator ReadOnlyDictionary(FluentValidationProblemDetail detail) { - return new ReadOnlyDictionary( + return new( new Dictionary { ["propertyName"] = detail.PropertyName, @@ -35,10 +35,7 @@ public class FluentValidationProblemDetail /// public FluentValidationProblemDetail(ValidationFailure validationFailure) { - if (validationFailure == null) - { - throw new ArgumentNullException(nameof(validationFailure)); - } + ArgumentNullException.ThrowIfNull(validationFailure); PropertyName = validationFailure.PropertyName; ErrorMessage = validationFailure.ErrorMessage; @@ -85,4 +82,4 @@ public Validator() RuleFor(x => x.ErrorMessage).NotNull(); } } -} +} \ No newline at end of file diff --git a/src/Foundation/NodaTimeDestructuringPolicy.cs b/src/Foundation/NodaTimeDestructuringPolicy.cs index 063d8e53b..81044532e 100644 --- a/src/Foundation/NodaTimeDestructuringPolicy.cs +++ b/src/Foundation/NodaTimeDestructuringPolicy.cs @@ -78,15 +78,9 @@ public bool TryDestructure(object value, ILogEventPropertyValueFactory _, [NotNu if (value is Interval interval) { var values = new List(); - if (interval.HasStart) - { - values.Add(new("Start", _.CreatePropertyValue(interval.Start))); - } - - if (interval.HasEnd) - { - values.Add(new("End", _.CreatePropertyValue(interval.End))); - } + if (interval.HasStart) values.Add(new("Start", _.CreatePropertyValue(interval.Start))); + + if (interval.HasEnd) values.Add(new("End", _.CreatePropertyValue(interval.End))); result = new StructureValue(values); return true; diff --git a/src/Foundation/Rocket.Surgery.LaunchPad.Foundation.csproj b/src/Foundation/Rocket.Surgery.LaunchPad.Foundation.csproj index 091c9d1dc..c9ba1712f 100644 --- a/src/Foundation/Rocket.Surgery.LaunchPad.Foundation.csproj +++ b/src/Foundation/Rocket.Surgery.LaunchPad.Foundation.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/Foundation/Validation/StringInValidator.cs b/src/Foundation/Validation/StringInValidator.cs index 83ff591ec..9d42f3f00 100644 --- a/src/Foundation/Validation/StringInValidator.cs +++ b/src/Foundation/Validation/StringInValidator.cs @@ -39,10 +39,7 @@ public override bool IsValid(ValidationContext context, TProperty? value) var stringValue = value is string s ? s : value.ToString(); var result = Values.Any(n => n.Equals(stringValue, comparison)); - if (result) - { - return result; - } + if (result) return result; context.MessageFormatter.AppendPropertyName(context.DisplayName); context.MessageFormatter.AppendArgument("Values", string.Join(", ", Values)); @@ -58,4 +55,4 @@ public override bool IsValid(ValidationContext context, TProperty? value) internal interface IStringInValidator { IEnumerable Values { get; } -} +} \ No newline at end of file diff --git a/src/Foundation/Validation/ValidationHealthCheckResults.cs b/src/Foundation/Validation/ValidationHealthCheckResults.cs index fddfe4670..f733d4ed5 100644 --- a/src/Foundation/Validation/ValidationHealthCheckResults.cs +++ b/src/Foundation/Validation/ValidationHealthCheckResults.cs @@ -21,15 +21,11 @@ public ValidationHealthCheckResults(IHostApplicationLifetime hostApplicationLife public void AddResult(string optionsTypeName, string optionsName, ValidationResult result) { var key = optionsTypeName; - if (optionsName != Options.DefaultName) - { - key += $"_{optionsName}"; - } + if (optionsName != Options.DefaultName) key += $"_{optionsName}"; if (result.IsValid) - { _results[key] = - new HealthReportEntry( + new( HealthStatus.Healthy, $"Options Validation {key}", TimeSpan.Zero, @@ -41,13 +37,11 @@ public void AddResult(string optionsTypeName, string optionsName, ValidationResu z => z.Key, z => (object)z.Select(x => x.ToString()).ToArray() ), - new[] { "options-validation", key } + new[] { "options-validation", key, } ); - } else - { _results[key] = - new HealthReportEntry( + new( HealthStatus.Unhealthy, $"Options Validation {key}", TimeSpan.Zero, @@ -59,8 +53,7 @@ public void AddResult(string optionsTypeName, string optionsName, ValidationResu z => z.Key, z => (object)z.Select(x => x.ToString()).ToArray() ), - new[] { "options-validation", "Options Validation", key, optionsTypeName } + new[] { "options-validation", "Options Validation", key, optionsTypeName, } ); - } } -} +} \ No newline at end of file diff --git a/src/Foundation/Validation/ValidationPipelineBehavior.cs b/src/Foundation/Validation/ValidationPipelineBehavior.cs index f0aa13e52..366be1957 100644 --- a/src/Foundation/Validation/ValidationPipelineBehavior.cs +++ b/src/Foundation/Validation/ValidationPipelineBehavior.cs @@ -9,15 +9,12 @@ internal class ValidationPipelineBehavior(IValidator? validator = null) { public async Task Handle(T request, RequestHandlerDelegate next, CancellationToken cancellationToken) { - if (validator is not null) + if (validator is { }) { var context = new ValidationContext(request); var response = await validator.ValidateAsync(context, cancellationToken).ConfigureAwait(false); - if (!response.IsValid) - { - throw new ValidationException(response.Errors); - } + if (!response.IsValid) throw new ValidationException(response.Errors); } return await next().ConfigureAwait(false); @@ -29,17 +26,17 @@ internal class ValidationStreamPipelineBehavior(IValidator? validator = { public async IAsyncEnumerable Handle(T request, StreamHandlerDelegate next, [EnumeratorCancellation] CancellationToken cancellationToken) { - if (validator is not null) + if (validator is { }) { var context = new ValidationContext(request); var response = await validator.ValidateAsync(context, cancellationToken).ConfigureAwait(false); - if (!response.IsValid) - { - throw new ValidationException(response.Errors); - } + if (!response.IsValid) throw new ValidationException(response.Errors); } - await foreach (var item in next().WithCancellation(cancellationToken)) yield return item; + await foreach (var item in next().WithCancellation(cancellationToken)) + { + yield return item; + } } -} +} \ No newline at end of file diff --git a/src/Functions/Conventions/SerilogFunctionsConvention.cs b/src/Functions/Conventions/SerilogFunctionsConvention.cs deleted file mode 100644 index 08115e632..000000000 --- a/src/Functions/Conventions/SerilogFunctionsConvention.cs +++ /dev/null @@ -1,116 +0,0 @@ -using App.Metrics; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.LaunchPad.Serilog; -using Serilog; -using Serilog.Extensions.Logging; -using ILogger = Serilog.ILogger; - -namespace Rocket.Surgery.LaunchPad.Functions.Conventions; - -/// -/// SerilogHostingConvention. -/// Implements the -/// -/// -[PublicAPI] -[ExportConvention] -public class SerilogFunctionsConvention : IServiceConvention -{ - private readonly LaunchPadLoggingOptions _options; - - /// - /// Initializes a new instance of the class. - /// - /// The options. - public SerilogFunctionsConvention(LaunchPadLoggingOptions? options = null) - { - _options = options ?? new LaunchPadLoggingOptions(); - } - - /// - public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - // removes default console loggers and such - foreach (var item in services - .Where( - x => x.ImplementationType?.FullName?.StartsWith("Microsoft.Extensions.Logging", StringComparison.Ordinal) == true - && x.ImplementationType?.FullName?.EndsWith("Provider", StringComparison.Ordinal) == true - ) - .ToArray() - ) - { - services.Remove(item); - } - - LoggerProviderCollection? loggerProviders = null; - if (_options.WriteToProviders) - { -#pragma warning disable CA2000 - loggerProviders = new LoggerProviderCollection(); -#pragma warning restore CA2000 - } - - services.AddSingleton( - serviceProvider => - { - var log = serviceProvider.GetRequiredService(); - ILogger? registeredLogger = null; - if (_options.PreserveStaticLogger) - { - registeredLogger = log; - } - else - { - // Passing a `null` logger to `SerilogLoggerFactory` results in disposal via - // `Log.CloseAndFlush()`, which additionally replaces the static logger with a no-op. - Log.Logger = log; - } - - var factory = new SerilogLoggerFactory(registeredLogger, true, loggerProviders); - - if (_options.WriteToProviders) - { - foreach (var provider in serviceProvider.GetServices()) - factory.AddProvider(provider); - } - - return factory; - } - ); - - if (context.Get() is { } logger) - { - services.AddSingleton(logger); - } - else - { - services.AddSingleton( - serviceProvider => - { - var loggerConfiguration = new LoggerConfiguration(); - - if (loggerProviders != null) - loggerConfiguration.WriteTo.Providers(loggerProviders); - - loggerConfiguration.ApplyConventions(context, serviceProvider); - - return loggerConfiguration.CreateLogger(); - } - ); - - if (context.Get() is { } loggerFactory) - { - services.AddSingleton(loggerFactory); - } - } - } -} diff --git a/src/Functions/LaunchPadFunctionStartup.cs b/src/Functions/LaunchPadFunctionStartup.cs deleted file mode 100644 index 9ea91da6d..000000000 --- a/src/Functions/LaunchPadFunctionStartup.cs +++ /dev/null @@ -1,132 +0,0 @@ -using Microsoft.Azure.Functions.Extensions.DependencyInjection; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Hosting; -using Rocket.Surgery.Conventions; - -namespace Rocket.Surgery.LaunchPad.Functions; - -/// -/// Default startup class for interacting with Azure Functions -/// -public abstract class LaunchPadFunctionStartup : FunctionsStartup -{ - internal ConventionContextBuilder _builder; - // ReSharper disable once NullableWarningSuppressionIsUsed - internal IConventionContext _context = null!; - - /// - /// The default constuctor - /// - protected LaunchPadFunctionStartup() - { - _builder = new ConventionContextBuilder(new Dictionary()) - .UseAppDomain(AppDomain.CurrentDomain) - .Set(HostType.Live); - if (this is IConvention convention) - { - _builder.AppendConvention(convention); - } - - // TODO: Restore this sometime - // var functionsAssembly = this.GetType().Assembly; - // var location = Path.GetDirectoryName(functionsAssembly.Location); - // DependencyContext? dependencyContext = null; - // while (!string.IsNullOrEmpty(location)) - // { - // var depsFilePath = Path.Combine(location, functionsAssembly.GetName().Name + ".deps.json"); - // if (File.Exists(depsFilePath)) - // { - // using var stream = File.Open(depsFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); - // using var reader = new DependencyContextJsonReader(); - // dependencyContext = reader.Read(stream); - // break; - // } - // - // location = Path.GetDirectoryName(location); - // } - } - - /// - /// The default constructor with the given configuration method - /// - /// - protected LaunchPadFunctionStartup(Func configure) - { - _builder = configure(this).Set(HostType.Live); - if (this is IConvention convention) - { - _builder.AppendConvention(convention); - } - } - - /// - public sealed override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder) - { - Setup(_builder); - _context = ConventionContext.From(_builder); - builder.ConfigurationBuilder.ApplyConventions(_context); - ConfigureAppConfiguration(builder, _context); - } - - /// - public sealed override void Configure(IFunctionsHostBuilder builder) - { - var existingHostedServices = builder.Services.Where(x => x.ServiceType == typeof(IHostedService)).ToArray(); - var builderContext = builder.GetContext(); - - _context.Set(builderContext.Configuration); - builder.Services.ApplyConventions(_context); - - builder.Services.RemoveAll(); - builder.Services.Add(existingHostedServices); - Configure(builder, _context); - } - - /// - /// Method called to setup the conventions - /// - /// - public virtual void Setup(ConventionContextBuilder contextBuilder) - { - } - - /// - /// Method called to configure the application with the conventions - /// - /// - /// - public virtual void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder, IConventionContext context) - { - } - - /// - /// Method called to configure the services with the conventions - /// - /// - /// - public abstract void Configure(IFunctionsHostBuilder builder, IConventionContext context); - - /// - /// Use the given rocket booster - /// - /// - /// - public LaunchPadFunctionStartup UseRocketBooster(Func configure) - { - _builder = configure(this); - return this; - } - - /// - /// Use the given rocket booster - /// - /// - /// - public LaunchPadFunctionStartup LaunchWith(Func configure) - { - _builder = configure(this); - return this; - } -} diff --git a/src/Functions/Rocket.Surgery.LaunchPad.Functions.csproj b/src/Functions/Rocket.Surgery.LaunchPad.Functions.csproj deleted file mode 100644 index 1118f80c3..000000000 --- a/src/Functions/Rocket.Surgery.LaunchPad.Functions.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - netstandard2.1 - - $(PackageTags) - - - - - - - - - diff --git a/src/Functions/RocketBooster.cs b/src/Functions/RocketBooster.cs deleted file mode 100644 index decdfe287..000000000 --- a/src/Functions/RocketBooster.cs +++ /dev/null @@ -1,228 +0,0 @@ -using System.Reflection; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Rocket.Surgery.Conventions; - -//using Microsoft.Azure.WebJobs.Hosting; - -namespace Rocket.Surgery.LaunchPad.Functions; - -/// -/// Class RocketBooster. -/// -public static class RocketBooster -{ - /// - /// Fors the application domain. - /// - /// The application domain. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func ForAppDomain( - AppDomain appDomain, - Func> getConventions - ) - { - return _ => new ConventionContextBuilder(new Dictionary()) - .UseAppDomain(appDomain) - .WithConventionsFrom(getConventions); - } - - /// - /// Fors the application domain. - /// - /// The application domain. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func ForAppDomain( - AppDomain appDomain, - Action? conventionContextBuilderAction = null - ) - { - return _ => - { - var conventionContextBuilder = new ConventionContextBuilder(new Dictionary()) - .UseAppDomain(appDomain); - conventionContextBuilderAction?.Invoke(conventionContextBuilder); - return conventionContextBuilder; - }; - } - - /// - /// Fors the specified application domain. - /// - /// The application domain. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func For( - AppDomain appDomain, - Func> getConventions - ) - { - return ForAppDomain(appDomain, getConventions); - } - - /// - /// Fors the specified application domain. - /// - /// The application domain. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func For( - AppDomain appDomain, - Action? conventionContextBuilderAction = null - ) - { - return ForAppDomain(appDomain, conventionContextBuilderAction); - } - - /// - /// Fors the assemblies. - /// - /// The assemblies. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func ForAssemblies( - IEnumerable assemblies, - Func> getConventions - ) - { - return _ => new ConventionContextBuilder(new Dictionary()) - .UseAssemblies(assemblies) - .WithConventionsFrom(getConventions); - } - - /// - /// Fors the assemblies. - /// - /// The assemblies. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func ForAssemblies( - IEnumerable assemblies, - Action? conventionContextBuilderAction = null - ) - { - return _ => - { - var conventionContextBuilder = new ConventionContextBuilder(new Dictionary()).UseAssemblies(assemblies); - conventionContextBuilderAction?.Invoke(conventionContextBuilder); - return conventionContextBuilder; - }; - } - - /// - /// Fors the specified assemblies. - /// - /// The assemblies. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func For( - IEnumerable assemblies, - Func> getConventions - ) - { - return ForAssemblies(assemblies, getConventions); - } - - /// - /// Fors the specified assemblies. - /// - /// The assemblies. - /// - /// Func<IHostBuilder, ConventionContextBuilder>. - public static Func For( - IEnumerable assemblies, - Action? conventionContextBuilderAction = null - ) - { - return ForAssemblies(assemblies, conventionContextBuilderAction); - } - - // /// - // /// Use the given dependency context for resolving assemblies - // /// - // /// - // /// - // public static Func ForDependencyContext(DependencyContext dependencyContext) - // => builder => new ConventionContextBuilder(new Dictionary()).UseDependencyContext(dependencyContext); - // - // /// - // /// Use the given dependency context for resolving assemblies - // /// - // /// - // /// - // public static Func For(DependencyContext dependencyContext) => ForDependencyContext(dependencyContext); - - // /// - // /// Use the given dependency context for resolving assemblies - // /// - // /// - // /// - // public static Func ForDependencyContext(DependencyContext dependencyContext) - // => builder => new ConventionContextBuilder(new Dictionary()).UseDependencyContext(dependencyContext); - // - // /// - // /// Use the given dependency context for resolving assemblies - // /// - // /// - // /// - // public static Func For(DependencyContext dependencyContext) => ForDependencyContext(dependencyContext); - - /// - /// Uses the assembly candidate finder. - /// - /// The builder. - /// The assembly candidate finder. - /// IConventionHostBuilder. - public static LaunchPadFunctionStartup UseDiagnosticLogger( - this LaunchPadFunctionStartup builder, - ILogger logger - ) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - builder._builder.Set(logger); - return builder; - } - - /// - /// Uses the diagnostic logging. - /// - /// The builder. - /// The action. - /// LaunchPadFunctionStartup. - public static LaunchPadFunctionStartup UseDiagnosticLogging( - this LaunchPadFunctionStartup builder, - Action action - ) - { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (action == null) - { - throw new ArgumentNullException(nameof(action)); - } - - builder.UseDiagnosticLogger( - new ServiceCollection() - .AddLogging(action) - .BuildServiceProvider() - .GetRequiredService() - .CreateLogger("DiagnosticLogger") - ); - - return builder; - } -} diff --git a/src/Grpc/Rocket.Surgery.LaunchPad.Grpc.csproj b/src/Grpc/Rocket.Surgery.LaunchPad.Grpc.csproj index 704cc3fcf..0275c3a48 100644 --- a/src/Grpc/Rocket.Surgery.LaunchPad.Grpc.csproj +++ b/src/Grpc/Rocket.Surgery.LaunchPad.Grpc.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) false diff --git a/src/Grpc/Validation/ValidationInterceptor.cs b/src/Grpc/Validation/ValidationInterceptor.cs index ab6ba3d7d..774d56c41 100644 --- a/src/Grpc/Validation/ValidationInterceptor.cs +++ b/src/Grpc/Validation/ValidationInterceptor.cs @@ -13,7 +13,7 @@ private static RpcException CreateException(ValidationResult results, string? me validationMetadata.Add("title", "Unprocessable Entity"); validationMetadata.Add("link", "https://tools.ietf.org/html/rfc4918#section-11.2"); if (message is { }) validationMetadata.Add("message", message); - throw new RpcException(new Status(StatusCode.InvalidArgument, message ?? ""), validationMetadata, message ?? ""); + throw new RpcException(new(StatusCode.InvalidArgument, message ?? ""), validationMetadata, message ?? ""); } public override async Task UnaryServerHandler( @@ -26,10 +26,7 @@ UnaryServerMethod continuation { var results = await validator.ValidateAsync(request, context.CancellationToken).ConfigureAwait(false); - if (results.IsValid || !results.Errors.Any()) - { - return await continuation(request, context); - } + if (results.IsValid || !results.Errors.Any()) return await continuation(request, context); var message = await handler.HandleAsync(results.Errors); throw CreateException(results, message); @@ -48,10 +45,7 @@ AsyncUnaryCallContinuation continuation { var results = validator.Validate(request); - if (results.IsValid || !results.Errors.Any()) - { - return continuation(request, context); - } + if (results.IsValid || !results.Errors.Any()) return continuation(request, context); var message = handler.Handle(results.Errors); throw CreateException(results, message); @@ -70,10 +64,7 @@ BlockingUnaryCallContinuation continuation { var results = validator.Validate(request); - if (results.IsValid || !results.Errors.Any()) - { - return continuation(request, context); - } + if (results.IsValid || !results.Errors.Any()) return continuation(request, context); var message = handler.Handle(results.Errors); throw CreateException(results, message); @@ -81,4 +72,4 @@ BlockingUnaryCallContinuation continuation return continuation(request, context); } -} +} \ No newline at end of file diff --git a/src/Hosting/Conventions/EnvironmentLoggingConvention.cs b/src/Hosting/Conventions/EnvironmentLoggingConvention.cs index 18f2ed5b5..772e7cd5b 100644 --- a/src/Hosting/Conventions/EnvironmentLoggingConvention.cs +++ b/src/Hosting/Conventions/EnvironmentLoggingConvention.cs @@ -29,9 +29,9 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (context == null) throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(context); if (context.Get() is not { } environment) return; loggerConfiguration.Enrich.WithProperty(nameof(environment.EnvironmentName), environment.EnvironmentName); loggerConfiguration.Enrich.WithProperty(nameof(environment.ApplicationName), environment.ApplicationName); } -} +} \ No newline at end of file diff --git a/src/Hosting/Conventions/OpenTelemetryConvention.cs b/src/Hosting/Conventions/OpenTelemetryConvention.cs index 13e981af1..1bac4b438 100644 --- a/src/Hosting/Conventions/OpenTelemetryConvention.cs +++ b/src/Hosting/Conventions/OpenTelemetryConvention.cs @@ -2,26 +2,30 @@ using Microsoft.Extensions.DependencyInjection; 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; /// /// EnvironmentLoggingConvention. -/// Implements the +/// Implements the /// -/// +/// [PublicAPI] [ExportConvention] -public class OpenTelemetryConvention : IServiceConvention +public class OpenTelemetryConvention : IServiceAsyncConvention { /// - public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) + public async ValueTask Register( + IConventionContext context, + IConfiguration configuration, + IServiceCollection services, + CancellationToken cancellationToken + ) { - services - .AddOpenTelemetry() - .ApplyConventions(context) - ; + await services + .AddOpenTelemetry() + .ApplyConventionsAsync(context, cancellationToken) + .ConfigureAwait(false); } -} +} \ No newline at end of file diff --git a/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs b/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs index 9acc650e6..e5679557a 100644 --- a/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs +++ b/src/Hosting/Conventions/SerilogConsoleLoggingConvention.cs @@ -36,10 +36,7 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullException.ThrowIfNull(configuration); if (!_options.EnableConsoleLogging) return; @@ -52,4 +49,4 @@ LoggerConfiguration loggerConfiguration ) ); } -} +} \ No newline at end of file diff --git a/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs b/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs index 68c93dbec..2c0d39a49 100644 --- a/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs +++ b/src/Hosting/Conventions/SerilogDebugLoggingConvention.cs @@ -35,10 +35,7 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (configuration == null) - { - throw new ArgumentNullException(nameof(configuration)); - } + ArgumentNullException.ThrowIfNull(configuration); if (!_options.EnableDebugLogging) return; @@ -46,8 +43,8 @@ LoggerConfiguration loggerConfiguration c => c.Debug( LogEventLevel.Verbose, _options.DebugMessageTemplate, - formatProvider: CultureInfo.InvariantCulture + CultureInfo.InvariantCulture ) ); } -} +} \ No newline at end of file diff --git a/src/Hosting/Conventions/SerilogHostingConvention.cs b/src/Hosting/Conventions/SerilogHostingConvention.cs index a4befa3a5..5c9bbb0f6 100644 --- a/src/Hosting/Conventions/SerilogHostingConvention.cs +++ b/src/Hosting/Conventions/SerilogHostingConvention.cs @@ -12,12 +12,12 @@ namespace Rocket.Surgery.LaunchPad.Hosting.Conventions; /// /// SerilogHostingConvention. -/// Implements the +/// Implements the /// -/// +/// [PublicAPI] [ExportConvention] -public class SerilogHostingConvention : IHostingConvention +public class SerilogHostingConvention : IHostApplicationConvention { private readonly LaunchPadLoggingOptions _options; @@ -31,47 +31,38 @@ public SerilogHostingConvention(LaunchPadLoggingOptions? options = null) } /// - public void Register(IConventionContext context, IHostBuilder builder) + public void Register(IConventionContext context, IHostApplicationBuilder builder) { - if (context == null) + ArgumentNullException.ThrowIfNull(context); + + // removes default console loggers and such + foreach (var item in builder + .Services + .Where( + x => x.ImplementationType?.FullName?.StartsWith("Microsoft.Extensions.Logging", StringComparison.Ordinal) == true + && x.ImplementationType?.FullName.EndsWith("Provider", StringComparison.Ordinal) == true + ) + .ToArray() + ) { - throw new ArgumentNullException(nameof(context)); + builder.Services.Remove(item); } - builder.ConfigureServices( - (_, services) => - { - // removes default console loggers and such - foreach (var item in services - .Where( - x => x.ImplementationType?.FullName?.StartsWith("Microsoft.Extensions.Logging", StringComparison.Ordinal) == true - && x.ImplementationType?.FullName.EndsWith("Provider", StringComparison.Ordinal) == true - ) - .ToArray() - ) - { - services.Remove(item); - } - } - ); - if (context.Get() is { } logger) { - builder.UseSerilog(logger); + builder.Services.AddSerilog(logger); } else { - builder.UseSerilog( - (_, services, loggerConfiguration) => loggerConfiguration.ApplyConventions(context, services), + builder.Services.AddSerilog( + (services, loggerConfiguration) => loggerConfiguration.ApplyConventions(context, services), _options.PreserveStaticLogger, _options.WriteToProviders ); if (context.Get() != null) - { // ReSharper disable once NullableWarningSuppressionIsUsed - builder.ConfigureServices((_, services) => services.AddSingleton(context.Get()!)); - } + builder.Services.AddSingleton(context.Get()!); } } -} +} \ No newline at end of file diff --git a/src/Hosting/Rocket.Surgery.LaunchPad.Hosting.csproj b/src/Hosting/Rocket.Surgery.LaunchPad.Hosting.csproj index 5557d8608..aa3a2a342 100644 --- a/src/Hosting/Rocket.Surgery.LaunchPad.Hosting.csproj +++ b/src/Hosting/Rocket.Surgery.LaunchPad.Hosting.csproj @@ -1,12 +1,11 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) - diff --git a/src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs b/src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs deleted file mode 100644 index 1444eb7f1..000000000 --- a/src/Hosting/Telemetry/OpenTelemetryHostBuilderExtensions.cs +++ /dev/null @@ -1,35 +0,0 @@ -// ReSharper disable once CheckNamespace - -using Rocket.Surgery.LaunchPad.Hosting.Telemetry; - -// ReSharper disable once CheckNamespace -namespace Rocket.Surgery.Conventions; - -/// -/// Helper method for working with -/// -[PublicAPI] -public static class OpenTelemetryHostBuilderExtensions -{ - /// - /// Configure the serilog delegate to the convention scanner - /// - /// The container. - /// The delegate. - /// IConventionHostBuilder. - public static ConventionContextBuilder ConfigureOpenTelemetry(this ConventionContextBuilder container, OpenTelemetryConvention @delegate) - { - if (container == null) - { - throw new ArgumentNullException(nameof(container)); - } - - if (@delegate == null) - { - throw new ArgumentNullException(nameof(@delegate)); - } - - container.AppendDelegate(@delegate); - return container; - } -} diff --git a/src/Hosting/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs b/src/Hosting/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs deleted file mode 100644 index c9a6b8add..000000000 --- a/src/Hosting/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Microsoft.Extensions.Configuration; -using OpenTelemetry; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.LaunchPad.Telemetry; - -namespace Rocket.Surgery.LaunchPad.Hosting.Telemetry; - -/// -/// Extension method to apply configuration conventions -/// -[PublicAPI] -public static class RocketSurgeryOpenTelemetryExtensions -{ - /// - /// Apply configuration conventions - /// - /// - /// - /// - public static OpenTelemetryBuilder ApplyConventions(this OpenTelemetryBuilder builder, IConventionContext conventionContext) - { - var configuration = conventionContext.Get() - ?? throw new ArgumentException("Configuration was not found in context", nameof(conventionContext)); - - builder - .WithMetrics(z => z.ApplyConventions(conventionContext)) - .WithTracing(z => z.ApplyConventions(conventionContext)); - - foreach (var item in conventionContext.Conventions.Get()) - { - if (item is IOpenTelemetryConvention convention) - { - convention.Register(conventionContext, configuration, builder); - } - else if (item is OpenTelemetryConvention @delegate) - { - @delegate(conventionContext, configuration, builder); - } - } - - return builder; - } -} diff --git a/src/HotChocolate/Conventions/GraphqlConvention.cs b/src/HotChocolate/Conventions/GraphqlConvention.cs index 32ba61f6f..019e0e2a4 100644 --- a/src/HotChocolate/Conventions/GraphqlConvention.cs +++ b/src/HotChocolate/Conventions/GraphqlConvention.cs @@ -53,12 +53,9 @@ public void Register(IConventionContext context, IConfiguration configuration, I services.TryAddSingleton(); services.TryAddSingleton(); - if (!_rocketChocolateOptions.IncludeAssemblyInfoQuery) - { - return; - } + if (!_rocketChocolateOptions.IncludeAssemblyInfoQuery) return; services.TryAddSingleton(_foundationOptions); sb.AddType(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Conventions/InstrumentationConvention.cs b/src/HotChocolate/Conventions/InstrumentationConvention.cs index 0755e9fa2..ece094307 100644 --- a/src/HotChocolate/Conventions/InstrumentationConvention.cs +++ b/src/HotChocolate/Conventions/InstrumentationConvention.cs @@ -1,23 +1,23 @@ using Microsoft.Extensions.Configuration; +using OpenTelemetry; using OpenTelemetry.Trace; using Rocket.Surgery.Conventions; -using Rocket.Surgery.Conventions.DependencyInjection; using Rocket.Surgery.LaunchPad.Telemetry; namespace Rocket.Surgery.LaunchPad.HotChocolate.Conventions; /// /// InstrumentationConvention. -/// Implements and +/// Implements and /// -/// +/// [PublicAPI] [ExportConvention] -public class InstrumentationConvention : IOpenTelemetryTracingConvention +public class InstrumentationConvention : IOpenTelemetryConvention { /// - public void Register(IConventionContext conventionContext, IConfiguration configuration, TracerProviderBuilder builder) + public void Register(IConventionContext conventionContext, IConfiguration configuration, IOpenTelemetryBuilder builder) { - builder.AddHotChocolateInstrumentation(); + builder.WithTracing(b => b.AddHotChocolateInstrumentation()); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/GraphqlErrorFilter.cs b/src/HotChocolate/GraphqlErrorFilter.cs index 38e2a2d1e..e9e2af4ac 100644 --- a/src/HotChocolate/GraphqlErrorFilter.cs +++ b/src/HotChocolate/GraphqlErrorFilter.cs @@ -18,25 +18,24 @@ public IError OnError(IError error) if (error.Exception is ValidationException vx) { var childErrors = - vx.Errors.Select(x => new FluentValidationProblemDetail(x)) - .Select( - failure => - { - var err = new Error(failure.ErrorMessage) - .WithCode(failure.ErrorCode) - .SetExtension("attemptedValue", failure.AttemptedValue) - .SetExtension("severity", failure.Severity); - - if (!string.IsNullOrWhiteSpace(failure.PropertyName)) - { - err = err - .SetExtension("field", failure.PropertyName) - .SetExtension("propertyName", failure.PropertyName); - } - - return err; - } - ); + vx + .Errors.Select(x => new FluentValidationProblemDetail(x)) + .Select( + failure => + { + var err = new Error(failure.ErrorMessage) + .WithCode(failure.ErrorCode) + .SetExtension("attemptedValue", failure.AttemptedValue) + .SetExtension("severity", failure.Severity); + + if (!string.IsNullOrWhiteSpace(failure.PropertyName)) + err = err + .SetExtension("field", failure.PropertyName) + .SetExtension("propertyName", failure.PropertyName); + + return err; + } + ); return new AggregateError(childErrors); } @@ -48,24 +47,15 @@ public IError OnError(IError error) .SetMessage(error.Exception.Message) .WithProblemDetails(ex); - if (error.Exception is NotFoundException) - { - builder.SetCode("NOTFOUND"); - } + if (error.Exception is NotFoundException) builder.SetCode("NOTFOUND"); - if (error.Exception is NotAuthorizedException) - { - builder.SetCode("NOTAUTHORIZED"); - } + if (error.Exception is NotAuthorizedException) builder.SetCode("NOTAUTHORIZED"); - if (error.Exception is RequestFailedException) - { - builder.SetCode("FAILED"); - } + if (error.Exception is RequestFailedException) builder.SetCode("FAILED"); return builder.Build(); } return error; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/GraphqlExtensions.cs b/src/HotChocolate/GraphqlExtensions.cs index 812240ea8..f46f178ef 100644 --- a/src/HotChocolate/GraphqlExtensions.cs +++ b/src/HotChocolate/GraphqlExtensions.cs @@ -32,10 +32,7 @@ public static IErrorBuilder WithProblemDetails(this IErrorBuilder error, IProble error.SetExtension("instance", data.Instance); foreach (var property in data.Properties) { - if (property.Value is { }) - { - error.SetExtension(property.Key, property.Value); - } + if (property.Value is { }) error.SetExtension(property.Key, property.Value); } return error; @@ -53,7 +50,8 @@ public static IErrorBuilder WithProblemDetails(this IErrorBuilder error, IProble /// /// public static IRequestExecutorBuilder ConfigureStronglyTypedId< - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] TStrongType, + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] + TStrongType, TSchemaType>(this IRequestExecutorBuilder builder) where TSchemaType : INamedType { @@ -69,10 +67,10 @@ public static IRequestExecutorBuilder ConfigureStronglyTypedId< .GetMethods() .Single( z => z.Name == "AddTypeConverter" - && z.ReturnType == typeof(IRequestExecutorBuilder) - && z.IsGenericMethod - && z.GetGenericMethodDefinition().GetGenericArguments().Length == 2 - && z.GetParameters().Length == 2 + && z.ReturnType == typeof(IRequestExecutorBuilder) + && z.IsGenericMethod + && z.GetGenericMethodDefinition().GetGenericArguments().Length == 2 + && z.GetParameters().Length == 2 ); [UnconditionalSuppressMessage( @@ -81,7 +79,8 @@ public static IRequestExecutorBuilder ConfigureStronglyTypedId< Justification = "only working with public properties and constructors" )] private static void AddTypeConversion< - [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] TStrongType>( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] + TStrongType>( IRequestExecutorBuilder builder ) { @@ -92,11 +91,12 @@ IRequestExecutorBuilder builder var value = Expression.Parameter(typeof(TStrongType), "value"); var delegateType = typeof(ChangeType<,>).MakeGenericType(typeof(TStrongType), underlyingType); - AddTypeConverterMethod.MakeGenericMethod(typeof(TStrongType), underlyingType) - .Invoke( - null, - new object[] { builder, Expression.Lambda(delegateType, Expression.Property(value, "Value"), false, value).Compile() } - ); + AddTypeConverterMethod + .MakeGenericMethod(typeof(TStrongType), underlyingType) + .Invoke( + null, + new object[] { builder, Expression.Lambda(delegateType, Expression.Property(value, "Value"), false, value).Compile(), } + ); } { @@ -104,12 +104,13 @@ IRequestExecutorBuilder builder 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( - null, - new object[] { builder, Expression.Lambda(delegateType, Expression.New(constructor, value), false, value).Compile() } - ); + var constructor = typeof(TStrongType).GetConstructor(new[] { underlyingType, })!; + AddTypeConverterMethod + .MakeGenericMethod(underlyingType, typeof(TStrongType)) + .Invoke( + null, + new object[] { builder, Expression.Lambda(delegateType, Expression.New(constructor, value), false, value).Compile(), } + ); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Helpers/IntToStructBaseType.cs b/src/HotChocolate/Helpers/IntToStructBaseType.cs index 21d8ec3b1..40e36c1d2 100644 --- a/src/HotChocolate/Helpers/IntToStructBaseType.cs +++ b/src/HotChocolate/Helpers/IntToStructBaseType.cs @@ -14,9 +14,7 @@ public abstract class IntToStructBaseType : ScalarType /// - protected IntToStructBaseType(string name) : base(name, BindingBehavior.Implicit) - { - } + protected IntToStructBaseType(string name) : base(name, BindingBehavior.Implicit) { } /// /// Method to try and serialize @@ -37,10 +35,7 @@ protected IntToStructBaseType(string name) : base(name, BindingBehavior.Implicit /// protected override TRuntimeType ParseLiteral(IntValueNode valueSyntax) { - if (TryDeserialize(valueSyntax.ToInt32(), out var value)) - { - return value.Value; - } + if (TryDeserialize(valueSyntax.ToInt32(), out var value)) return value.Value; throw new SerializationException( $"Unable to deserialize integer to {Name}", @@ -51,10 +46,7 @@ protected override TRuntimeType ParseLiteral(IntValueNode valueSyntax) /// protected override IntValueNode ParseValue(TRuntimeType runtimeValue) { - if (TrySerialize(runtimeValue, out var val)) - { - return new IntValueNode(val.Value); - } + if (TrySerialize(runtimeValue, out var val)) return new(val.Value); throw new SerializationException( $"Unable to deserialize integer to {Name}", @@ -65,20 +57,11 @@ protected override IntValueNode ParseValue(TRuntimeType runtimeValue) /// public override IValueNode ParseResult(object? resultValue) { - if (resultValue is null) - { - return NullValueNode.Default; - } + if (resultValue is null) return NullValueNode.Default; - if (resultValue is int s) - { - return new IntValueNode(s); - } + if (resultValue is int s) return new IntValueNode(s); - if (resultValue is TRuntimeType v) - { - return ParseValue(v); - } + if (resultValue is TRuntimeType v) return ParseValue(v); throw new SerializationException( $"Unable to deserialize integer to {Name}", @@ -123,4 +106,4 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu runtimeValue = null; return false; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Helpers/StringToClassBaseType.cs b/src/HotChocolate/Helpers/StringToClassBaseType.cs index 5a5a3d181..1b52d2a4a 100644 --- a/src/HotChocolate/Helpers/StringToClassBaseType.cs +++ b/src/HotChocolate/Helpers/StringToClassBaseType.cs @@ -14,9 +14,7 @@ public abstract class StringToClassBaseType : ScalarType /// - protected StringToClassBaseType(string name) : base(name, BindingBehavior.Implicit) - { - } + protected StringToClassBaseType(string name) : base(name, BindingBehavior.Implicit) { } /// /// Method to serialize @@ -36,10 +34,7 @@ protected StringToClassBaseType(string name) : base(name, BindingBehavior.Implic /// protected override TRuntimeType ParseLiteral(StringValueNode valueSyntax) { - if (TryDeserialize(valueSyntax.Value, out var value)) - { - return value; - } + if (TryDeserialize(valueSyntax.Value, out var value)) return value; throw new SerializationException( $"Unable to deserialize string to {Name}", @@ -50,26 +45,17 @@ protected override TRuntimeType ParseLiteral(StringValueNode valueSyntax) /// protected override StringValueNode ParseValue(TRuntimeType runtimeValue) { - return new StringValueNode(Serialize(runtimeValue)); + return new(Serialize(runtimeValue)); } /// public override IValueNode ParseResult(object? resultValue) { - if (resultValue is null) - { - return NullValueNode.Default; - } + if (resultValue is null) return NullValueNode.Default; - if (resultValue is string s) - { - return new StringValueNode(s); - } + if (resultValue is string s) return new StringValueNode(s); - if (resultValue is TRuntimeType v) - { - return ParseValue(v); - } + if (resultValue is TRuntimeType v) return ParseValue(v); throw new SerializationException( $"Unable to deserialize string to {Name}", @@ -114,4 +100,4 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu runtimeValue = null; return false; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Helpers/StringToStructBaseType.cs b/src/HotChocolate/Helpers/StringToStructBaseType.cs index 14b5a474e..336383337 100644 --- a/src/HotChocolate/Helpers/StringToStructBaseType.cs +++ b/src/HotChocolate/Helpers/StringToStructBaseType.cs @@ -14,9 +14,7 @@ public abstract class StringToStructBaseType : ScalarType /// - protected StringToStructBaseType(string name) : base(name, BindingBehavior.Implicit) - { - } + protected StringToStructBaseType(string name) : base(name, BindingBehavior.Implicit) { } /// /// Method to serialize @@ -36,10 +34,7 @@ protected StringToStructBaseType(string name) : base(name, BindingBehavior.Impli /// protected override TRuntimeType ParseLiteral(StringValueNode valueSyntax) { - if (TryDeserialize(valueSyntax.Value, out var value)) - { - return value.Value; - } + if (TryDeserialize(valueSyntax.Value, out var value)) return value.Value; throw new SerializationException( $"Unable to deserialize string to {Name}", @@ -50,26 +45,17 @@ protected override TRuntimeType ParseLiteral(StringValueNode valueSyntax) /// protected override StringValueNode ParseValue(TRuntimeType runtimeValue) { - return new StringValueNode(Serialize(runtimeValue)); + return new(Serialize(runtimeValue)); } /// public override IValueNode ParseResult(object? resultValue) { - if (resultValue is null) - { - return NullValueNode.Default; - } + if (resultValue is null) return NullValueNode.Default; - if (resultValue is string s) - { - return new StringValueNode(s); - } + if (resultValue is string s) return new StringValueNode(s); - if (resultValue is TRuntimeType v) - { - return ParseValue(v); - } + if (resultValue is TRuntimeType v) return ParseValue(v); throw new SerializationException( $"Unable to deserialize string to {Name}", @@ -114,4 +100,4 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu runtimeValue = null; return false; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/NestedTypeNameTypeInterceptor.cs b/src/HotChocolate/NestedTypeNameTypeInterceptor.cs index c2013337e..e49c29756 100644 --- a/src/HotChocolate/NestedTypeNameTypeInterceptor.cs +++ b/src/HotChocolate/NestedTypeNameTypeInterceptor.cs @@ -16,29 +16,25 @@ public override void OnBeforeCompleteName( DefinitionBase? definition ) { - if (definition is IFilterInputTypeDefinition { EntityType: { IsNested: true, DeclaringType: { } } } ft) + if (definition is IFilterInputTypeDefinition { EntityType: { IsNested: true, DeclaringType: { }, }, } ft) { definition.Name = $"{ft.EntityType.DeclaringType.Name}{definition.Name}"; } - else if (definition is ISortInputTypeDefinition { EntityType: { IsNested: true, DeclaringType: { } } } st) + else if (definition is ISortInputTypeDefinition { EntityType: { IsNested: true, DeclaringType: { }, }, } st) { definition.Name = $"{st.EntityType.DeclaringType.Name}{definition.Name}"; } - else if (definition is IComplexOutputTypeDefinition { RuntimeType: { IsNested: true, DeclaringType: { } } } cot) + else if (definition is IComplexOutputTypeDefinition { RuntimeType: { IsNested: true, DeclaringType: { }, }, } cot) { definition.Name = $"{cot.RuntimeType.DeclaringType.Name}{cot.Name}"; if (definition.Name.EndsWith("Input", StringComparison.OrdinalIgnoreCase) && cot.RuntimeType.Name == "Request") - { definition.Name = $"{cot.RuntimeType.DeclaringType.Name}{cot.RuntimeType.Name}"; - } } - else if (definition is ITypeDefinition { RuntimeType: { IsNested: true, DeclaringType: { } } } ot) + else if (definition is ITypeDefinition { RuntimeType: { IsNested: true, DeclaringType: { }, }, } ot) { definition.Name = $"{ot.RuntimeType.DeclaringType.Name}{ot.Name}"; if (definition.Name.EndsWith("Input", StringComparison.OrdinalIgnoreCase) && ot.RuntimeType.Name == "Request") - { definition.Name = $"{ot.RuntimeType.DeclaringType.Name}{ot.RuntimeType.Name}"; - } } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Rocket.Surgery.LaunchPad.HotChocolate.csproj b/src/HotChocolate/Rocket.Surgery.LaunchPad.HotChocolate.csproj index 7c05935c1..2f9019730 100644 --- a/src/HotChocolate/Rocket.Surgery.LaunchPad.HotChocolate.csproj +++ b/src/HotChocolate/Rocket.Surgery.LaunchPad.HotChocolate.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs b/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs index 4b85c5d0a..1d7453400 100644 --- a/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs +++ b/src/HotChocolate/Validation/CustomValidationMiddlewareInjector.cs @@ -17,10 +17,7 @@ ArgumentDefinition argDef ) { // If validation is explicitly disabled, return none so validation middleware won't be added - if (argDef.ContextData.ContainsKey(WellKnownContextData.DontValidate)) - { - return new List(0); - } + if (argDef.ContextData.ContainsKey(WellKnownContextData.DontValidate)) return new(0); var validators = new List(); @@ -29,31 +26,21 @@ ArgumentDefinition argDef { // And if we can figure out the arg's runtime type var argRuntimeType = TryGetArgRuntimeType(argDef); - if (argRuntimeType is not null) - { + if (argRuntimeType is { }) if (validatorRegistry.TryGetValidator(argRuntimeType, out var validatorDescriptor)) - { validators.Add(validatorDescriptor); - } - } } // Include explicit validator/s (that aren't already added implicitly) - if (argDef.ContextData.TryGetValue(WellKnownContextData.ExplicitValidatorTypes, out var explicitValidatorTypesRaw) && - explicitValidatorTypesRaw is IEnumerable explicitValidatorTypes) - { + if (argDef.ContextData.TryGetValue(WellKnownContextData.ExplicitValidatorTypes, out var explicitValidatorTypesRaw) + && explicitValidatorTypesRaw is IEnumerable explicitValidatorTypes) // TODO: Potentially check and throw if there's a validator being explicitly applied for the wrong runtime type - foreach (var validatorType in explicitValidatorTypes) { - if (validators.Any(v => v.ValidatorType == validatorType)) - { - continue; - } + if (validators.Any(v => v.ValidatorType == validatorType)) continue; - validators.Add(new ValidatorDescriptor(validatorType)); + validators.Add(new(validatorType)); } - } return validators; } @@ -62,15 +49,9 @@ ArgumentDefinition argDef ArgumentDefinition argDef ) { - if (argDef.Parameter?.ParameterType is { } argRuntimeType) - { - return argRuntimeType; - } + if (argDef.Parameter?.ParameterType is { } argRuntimeType) return argRuntimeType; - if (argDef.Type is ExtendedTypeReference extTypeRef) - { - return TryGetRuntimeType(extTypeRef.Type); - } + if (argDef.Type is ExtendedTypeReference extTypeRef) return TryGetRuntimeType(extTypeRef.Type); return null; } @@ -78,24 +59,15 @@ ArgumentDefinition argDef private static Type? TryGetRuntimeType(IExtendedType extType) { // It's already a runtime type, .Type(typeof(int)) - if (extType.Kind == ExtendedTypeKind.Runtime) - { - return extType.Source; - } + if (extType.Kind == ExtendedTypeKind.Runtime) return extType.Source; // Array (though not sure what produces this scenario as seems to always be list) if (extType.IsArray) { - if (extType.ElementType is null) - { - return null; - } + if (extType.ElementType is null) return null; var elementRuntimeType = TryGetRuntimeType(extType.ElementType); - if (elementRuntimeType is null) - { - return null; - } + if (elementRuntimeType is null) return null; return Array.CreateInstance(elementRuntimeType, 0).GetType(); } @@ -103,16 +75,10 @@ ArgumentDefinition argDef // List if (extType.IsList) { - if (extType.ElementType is null) - { - return null; - } + if (extType.ElementType is null) return null; var elementRuntimeType = TryGetRuntimeType(extType.ElementType); - if (elementRuntimeType is null) - { - return null; - } + if (elementRuntimeType is null) return null; return typeof(List<>).MakeGenericType(elementRuntimeType); } @@ -121,17 +87,13 @@ ArgumentDefinition argDef if (typeof(InputObjectType).IsAssignableFrom(extType)) { var currBaseType = extType.Type.BaseType; - while (currBaseType is not null && - ( !currBaseType.IsGenericType || - currBaseType.GetGenericTypeDefinition() != typeof(InputObjectType<>) )) + while (currBaseType is { } + && ( !currBaseType.IsGenericType || currBaseType.GetGenericTypeDefinition() != typeof(InputObjectType<>) )) { currBaseType = currBaseType.BaseType; } - if (currBaseType is null) - { - return null; - } + if (currBaseType is null) return null; return currBaseType.GenericTypeArguments[0]; } @@ -140,23 +102,16 @@ ArgumentDefinition argDef if (typeof(ScalarType).IsAssignableFrom(extType)) { var currBaseType = extType.Type.BaseType; - while (currBaseType is not null && - ( !currBaseType.IsGenericType || - currBaseType.GetGenericTypeDefinition() != typeof(ScalarType<>) )) + while (currBaseType is { } + && ( !currBaseType.IsGenericType || currBaseType.GetGenericTypeDefinition() != typeof(ScalarType<>) )) { currBaseType = currBaseType.BaseType; } - if (currBaseType is null) - { - return null; - } + if (currBaseType is null) return null; var argRuntimeType = currBaseType.GenericTypeArguments[0]; - if (argRuntimeType.IsValueType && extType.IsNullable) - { - return typeof(Nullable<>).MakeGenericType(argRuntimeType); - } + if (argRuntimeType.IsValueType && extType.IsNullable) return typeof(Nullable<>).MakeGenericType(argRuntimeType); return argRuntimeType; } @@ -171,10 +126,7 @@ public override void OnBeforeCompleteType( DefinitionBase definition ) { - if (definition is not ObjectTypeDefinition objTypeDef) - { - return; - } + if (definition is not ObjectTypeDefinition objTypeDef) return; var validatorRegistry = completionContext.Services.GetRequiredService(); @@ -191,29 +143,22 @@ DefinitionBase definition try { validatorDescs = DetermineValidatorsForArg(validatorRegistry, argDef); - if (validatorDescs.Count < 1) - { - continue; - } + if (validatorDescs.Count < 1) continue; } 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}'.", + #pragma warning disable CA2201 + throw new( + $"Problem getting runtime type for argument '{argDef.Name}' " + $"in field '{fieldDef.Name}' on object type '{objTypeDef.Name}'.", ex ); -#pragma warning restore CA2201 + #pragma warning restore CA2201 } // Cleanup context now we're done with these foreach (var key in argDef.ContextData.Keys) { - if (key.StartsWith(WellKnownContextData.Prefix, StringComparison.OrdinalIgnoreCase)) - { - argDef.ContextData.Remove(key); - } + if (key.StartsWith(WellKnownContextData.Prefix, StringComparison.OrdinalIgnoreCase)) argDef.ContextData.Remove(key); } validatorDescs.TrimExcess(); @@ -224,11 +169,9 @@ DefinitionBase definition if (needsValidationMiddleware) { if (_validationFieldMiddlewareDef is null) - { - _validationFieldMiddlewareDef = new FieldMiddlewareDefinition( + _validationFieldMiddlewareDef = new( FieldClassMiddlewareFactory.Create() ); - } fieldDef.MiddlewareDefinitions.Insert(0, _validationFieldMiddlewareDef); } @@ -251,4 +194,4 @@ internal static class WellKnownContextData public const string ValidatorDescriptors = Prefix + ".Validators"; -} +} \ No newline at end of file diff --git a/src/HotChocolate/Validation/ValidationMiddleware.cs b/src/HotChocolate/Validation/ValidationMiddleware.cs index 6e6381b44..1e10b51c4 100644 --- a/src/HotChocolate/Validation/ValidationMiddleware.cs +++ b/src/HotChocolate/Validation/ValidationMiddleware.cs @@ -5,7 +5,8 @@ namespace Rocket.Surgery.LaunchPad.HotChocolate.Validation; [UsedImplicitly] -internal class ValidationMiddleware( +internal class ValidationMiddleware +( FieldDelegate next, IValidatorProvider validatorProvider, IValidationErrorsHandler validationErrorsHandler @@ -23,14 +24,10 @@ public async Task InvokeAsync(IMiddlewareContext context) .GetValidators(context, argument) .ToArray(); if (resolvedValidators.Length > 0) - { try { var value = context.ArgumentValue(argument.Name); - if (value == null) - { - continue; - } + if (value == null) continue; foreach (var resolvedValidator in resolvedValidators) { @@ -39,16 +36,14 @@ public async Task InvokeAsync(IMiddlewareContext context) validationContext, context.RequestAborted ); - if (validationResult is { IsValid: false }) - { + if (validationResult is { IsValid: false, }) invalidResults.Add( - new ArgumentValidationResult( + new( argument.Name, resolvedValidator.Validator, validationResult ) ); - } } } finally @@ -58,7 +53,6 @@ public async Task InvokeAsync(IMiddlewareContext context) resolvedValidator.Scope?.Dispose(); } } - } } if (invalidResults.Any()) @@ -69,4 +63,4 @@ public async Task InvokeAsync(IMiddlewareContext context) await next(context); } -} +} \ No newline at end of file diff --git a/src/Mapping.NewtonsoftJson/AutoMapperNewtonsoftJsonConvention.cs b/src/Mapping.NewtonsoftJson/AutoMapperNewtonsoftJsonConvention.cs index d0ace2847..95ff1f843 100644 --- a/src/Mapping.NewtonsoftJson/AutoMapperNewtonsoftJsonConvention.cs +++ b/src/Mapping.NewtonsoftJson/AutoMapperNewtonsoftJsonConvention.cs @@ -23,9 +23,6 @@ public class AutoMapperNewtonsoftJsonConvention : IServiceConvention /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); } -} +} \ No newline at end of file diff --git a/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj b/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj index dda7b4b82..f7fd4b507 100644 --- a/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj +++ b/src/Mapping.NewtonsoftJson/Rocket.Surgery.LaunchPad.Mapping.NewtonsoftJson.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) Rocket.Surgery.LaunchPad.Mapping diff --git a/src/Mapping/AutoMapperConvention.cs b/src/Mapping/AutoMapperConvention.cs index 1ddf010a6..7f232c9dc 100644 --- a/src/Mapping/AutoMapperConvention.cs +++ b/src/Mapping/AutoMapperConvention.cs @@ -1,5 +1,7 @@ +using AutoMapper; 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.Conventions.Reflection; @@ -34,7 +36,39 @@ public AutoMapperConvention(AutoMapperOptions? options = null) /// public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) { - var assemblies = context.AssemblyCandidateFinder.GetCandidateAssemblies(nameof(AutoMapper)).ToArray(); - services.AddAutoMapper(assemblies, _options.ServiceLifetime); + var provider = context.AssemblyProvider; + var autoMapperTypes = provider.GetTypes( + t => t + .FromAssemblyDependenciesOf() + .GetTypes( + f => f + .AssignableToAny( + typeof(IValueResolver<,,>), + typeof(IMemberValueResolver<,,,>), + typeof(ITypeConverter<,>), + typeof(IValueConverter<,>), + typeof(IMappingAction<,>) + ) + .NotInfoOf(TypeInfoFilter.Abstract) + ) + ); + // TODO: does not do the auto map properties + var profiles = provider + .GetTypes(t => t.FromAssemblyDependenciesOf().GetTypes(f => f.AssignableTo().NotInfoOf(TypeInfoFilter.Abstract))) + .ToArray(); + foreach (var type in autoMapperTypes) + { + services.TryAdd(new ServiceDescriptor(type, type, _options.ServiceLifetime)); + } + + services.AddAutoMapper( + config => + { + foreach (var profile in profiles) + { + config.AddProfile(profile); + } + } + ); } -} +} \ No newline at end of file diff --git a/src/Mapping/AutoMapperHostBuilderExtensions.cs b/src/Mapping/AutoMapperHostBuilderExtensions.cs index 2ad9730f9..fff728d82 100644 --- a/src/Mapping/AutoMapperHostBuilderExtensions.cs +++ b/src/Mapping/AutoMapperHostBuilderExtensions.cs @@ -17,12 +17,9 @@ public static class AutoMapperHostBuilderExtensions /// IConventionHostBuilder. public static ConventionContextBuilder UseAutoMapper(this ConventionContextBuilder container, AutoMapperOptions? options = null) { - if (container == null) - { - throw new ArgumentNullException(nameof(container)); - } + ArgumentNullException.ThrowIfNull(container); container.PrependConvention(); return container; } -} +} \ No newline at end of file diff --git a/src/Mapping/OnlyDefinedPropertiesMethods.cs b/src/Mapping/OnlyDefinedPropertiesMethods.cs index f92425193..20f9b1ecd 100644 --- a/src/Mapping/OnlyDefinedPropertiesMethods.cs +++ b/src/Mapping/OnlyDefinedPropertiesMethods.cs @@ -15,10 +15,7 @@ internal static class OnlyDefinedPropertiesMethods /// true if XXXX, false otherwise. public static bool ForStrings(PropertyMap map) { - if (map.SourceType == typeof(string) && map.DestinationType == typeof(string)) - { - return true; - } + if (map.SourceType == typeof(string) && map.DestinationType == typeof(string)) return true; return false; } @@ -33,10 +30,7 @@ public static void StringCondition(PropertyMap map, IMemberConfigurationExpressi expression.Condition( (_, _, sourceValue, _, _) => { - if (!string.IsNullOrWhiteSpace((string)sourceValue)) - { - return true; - } + if (!string.IsNullOrWhiteSpace((string)sourceValue)) return true; return false; } @@ -50,17 +44,11 @@ public static void StringCondition(PropertyMap map, IMemberConfigurationExpressi /// true if XXXX, false otherwise. public static bool ForValueTypes(PropertyMap map) { - if (map.SourceType == null) - { - return false; - } + if (map.SourceType == null) return false; var source = map.SourceType.GetTypeInfo(); var destination = map.DestinationType.GetTypeInfo(); - if (!source.IsEnum && source.IsValueType && destination.IsValueType) - { - return true; - } + if (!source.IsEnum && source.IsValueType && destination.IsValueType) return true; return false; } @@ -76,10 +64,7 @@ public static void ValueTypeCondition(PropertyMap map, IMemberConfigurationExpre expression.Condition( (_, _, sourceValue, _, _) => { - if (!Equals(defaultValue, sourceValue)) - { - return true; - } + if (!Equals(defaultValue, sourceValue)) return true; return false; } @@ -93,22 +78,13 @@ public static void ValueTypeCondition(PropertyMap map, IMemberConfigurationExpre /// true if XXXX, false otherwise. public static bool ForNullableValueTypes(PropertyMap map) { - if (map.SourceType == null) - { - return false; - } + if (map.SourceType == null) return false; var source = Nullable.GetUnderlyingType(map.SourceType)?.GetTypeInfo(); var destination = Nullable.GetUnderlyingType(map.DestinationType)?.GetTypeInfo(); - if (source == null || destination == null) - { - return false; - } + if (source == null || destination == null) return false; - if (!source.IsEnum && source.IsValueType && destination.IsValueType) - { - return true; - } + if (!source.IsEnum && source.IsValueType && destination.IsValueType) return true; return false; } @@ -123,13 +99,10 @@ public static void NullableValueTypeCondition(PropertyMap map, IMemberConfigurat expression.Condition( (_, _, sourceValue, _, _) => { - if (sourceValue != null) - { - return true; - } + if (sourceValue != null) return true; return false; } ); } -} +} \ No newline at end of file diff --git a/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj b/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj index 142d5b83f..d4f55aef0 100644 --- a/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj +++ b/src/Mapping/Rocket.Surgery.LaunchPad.Mapping.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) false diff --git a/src/Metadata/GitVersion.cs b/src/Metadata/GitVersion.cs index 72e8a4bd7..1af1903f2 100644 --- a/src/Metadata/GitVersion.cs +++ b/src/Metadata/GitVersion.cs @@ -16,7 +16,7 @@ public sealed class GitVersion : IEquatable /// GitVersion. public static GitVersion For(Assembly assembly) { - return new GitVersion(assembly); + return new(assembly); } /// @@ -46,7 +46,7 @@ public static IDictionary For(params Assembly[] assemblies /// GitVersion. public static GitVersion For(Type type) { - return new GitVersion(type.GetTypeInfo().Assembly); + return new(type.GetTypeInfo().Assembly); } /// @@ -76,12 +76,9 @@ public static IDictionary For(params Type[] types) /// GitVersion. public static GitVersion For(TypeInfo typeInfo) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } + ArgumentNullException.ThrowIfNull(typeInfo); - return new GitVersion(typeInfo.Assembly); + return new(typeInfo.Assembly); } /// @@ -134,7 +131,7 @@ public static IDictionary For(params TypeInfo[] typeInfos) /// The assembly. private GitVersion(Assembly assembly) { - _assemblyMetadata = new AssemblyMetadataProvider(assembly); + _assemblyMetadata = new(assembly); _assemblyMetadata.Infer(this); } @@ -150,7 +147,12 @@ private GitVersion(Assembly assembly) /// The major. [Prefix("GitVersion_")] [UsedImplicitly] - public int Major { get; [UsedImplicitly] private set; } + public int Major + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the minor. @@ -158,7 +160,12 @@ private GitVersion(Assembly assembly) /// The minor. [Prefix("GitVersion_")] [UsedImplicitly] - public int Minor { get; [UsedImplicitly] private set; } + public int Minor + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the patch. @@ -166,7 +173,12 @@ private GitVersion(Assembly assembly) /// The patch. [Prefix("GitVersion_")] [UsedImplicitly] - public int Patch { get; [UsedImplicitly] private set; } + public int Patch + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the pre release tag. @@ -174,7 +186,12 @@ private GitVersion(Assembly assembly) /// The pre release tag. [Prefix("GitVersion_")] [UsedImplicitly] - public string? PreReleaseTag { get; [UsedImplicitly] private set; } + public string? PreReleaseTag + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the pre release tag with dash. @@ -182,7 +199,12 @@ private GitVersion(Assembly assembly) /// The pre release tag with dash. [Prefix("GitVersion_")] [UsedImplicitly] - public string? PreReleaseTagWithDash { get; [UsedImplicitly] private set; } + public string? PreReleaseTagWithDash + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the build meta data. @@ -190,7 +212,12 @@ private GitVersion(Assembly assembly) /// The build meta data. [Prefix("GitVersion_")] [UsedImplicitly] - public string? BuildMetaData { get; [UsedImplicitly] private set; } + public string? BuildMetaData + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the build meta data padded. @@ -198,7 +225,12 @@ private GitVersion(Assembly assembly) /// The build meta data padded. [Prefix("GitVersion_")] [UsedImplicitly] - public string? BuildMetaDataPadded { get; [UsedImplicitly] private set; } + public string? BuildMetaDataPadded + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the full build meta data. @@ -206,7 +238,12 @@ private GitVersion(Assembly assembly) /// The full build meta data. [Prefix("GitVersion_")] [UsedImplicitly] - public string? FullBuildMetaData { get; [UsedImplicitly] private set; } + public string? FullBuildMetaData + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the major minor patch. @@ -214,7 +251,12 @@ private GitVersion(Assembly assembly) /// The major minor patch. [Prefix("GitVersion_")] [UsedImplicitly] - public string? MajorMinorPatch { get; [UsedImplicitly] private set; } + public string? MajorMinorPatch + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the sem ver. @@ -222,7 +264,12 @@ private GitVersion(Assembly assembly) /// The sem ver. [Prefix("GitVersion_")] [UsedImplicitly] - public string? SemVer { get; [UsedImplicitly] private set; } + public string? SemVer + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the legacy sem ver. @@ -230,7 +277,12 @@ private GitVersion(Assembly assembly) /// The legacy sem ver. [Prefix("GitVersion_")] [UsedImplicitly] - public string? LegacySemVer { get; [UsedImplicitly] private set; } + public string? LegacySemVer + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the legacy sem ver padded. @@ -238,7 +290,12 @@ private GitVersion(Assembly assembly) /// The legacy sem ver padded. [Prefix("GitVersion_")] [UsedImplicitly] - public string? LegacySemVerPadded { get; [UsedImplicitly] private set; } + public string? LegacySemVerPadded + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the assembly sem ver. @@ -246,7 +303,12 @@ private GitVersion(Assembly assembly) /// The assembly sem ver. [Prefix("GitVersion_")] [UsedImplicitly] - public string? AssemblySemVer { get; [UsedImplicitly] private set; } + public string? AssemblySemVer + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the full sem ver. @@ -254,7 +316,12 @@ private GitVersion(Assembly assembly) /// The full sem ver. [Prefix("GitVersion_")] [UsedImplicitly] - public string? FullSemVer { get; [UsedImplicitly] private set; } + public string? FullSemVer + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the informational version. @@ -262,7 +329,12 @@ private GitVersion(Assembly assembly) /// The informational version. [Prefix("GitVersion_")] [UsedImplicitly] - public string? InformationalVersion { get; [UsedImplicitly] private set; } + public string? InformationalVersion + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the name of the branch. @@ -270,7 +342,12 @@ private GitVersion(Assembly assembly) /// The name of the branch. [Prefix("GitVersion_")] [UsedImplicitly] - public string? BranchName { get; [UsedImplicitly] private set; } + public string? BranchName + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the sha. @@ -278,7 +355,12 @@ private GitVersion(Assembly assembly) /// The sha. [Prefix("GitVersion_")] [UsedImplicitly] - public string? Sha { get; [UsedImplicitly] private set; } + public string? Sha + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the nu get version v2. @@ -286,7 +368,12 @@ private GitVersion(Assembly assembly) /// The nu get version v2. [Prefix("GitVersion_")] [UsedImplicitly] - public string? NuGetVersionV2 { get; [UsedImplicitly] private set; } + public string? NuGetVersionV2 + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the nu get version. @@ -294,7 +381,12 @@ private GitVersion(Assembly assembly) /// The nu get version. [Prefix("GitVersion_")] [UsedImplicitly] - public string? NuGetVersion { get; [UsedImplicitly] private set; } + public string? NuGetVersion + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the commits since version source. @@ -302,7 +394,12 @@ private GitVersion(Assembly assembly) /// The commits since version source. [Prefix("GitVersion_")] [UsedImplicitly] - public int CommitsSinceVersionSource { get; [UsedImplicitly] private set; } + public int CommitsSinceVersionSource + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the commits since version source padded. @@ -310,7 +407,12 @@ private GitVersion(Assembly assembly) /// The commits since version source padded. [Prefix("GitVersion_")] [UsedImplicitly] - public string? CommitsSinceVersionSourcePadded { get; [UsedImplicitly] private set; } + public string? CommitsSinceVersionSourcePadded + { + get; + [UsedImplicitly] + private set; + } /// /// Gets the commit date. @@ -318,16 +420,26 @@ private GitVersion(Assembly assembly) /// The commit date. [Prefix("GitVersion_")] [UsedImplicitly] - public string? CommitDate { get; [UsedImplicitly] private set; } + public string? CommitDate + { + get; + [UsedImplicitly] + private set; + } -#pragma warning disable CA1056 // Uri properties should not be strings + #pragma warning disable CA1056 // Uri properties should not be strings /// /// Gets the repository url. /// /// The repository URL. [UsedImplicitly] - public string? RepositoryUrl { get; [UsedImplicitly] private set; } -#pragma warning restore CA1056 // Uri properties should not be strings + public string? RepositoryUrl + { + get; + [UsedImplicitly] + private set; + } + #pragma warning restore CA1056 // Uri properties should not be strings /// /// Determines whether the specified is equal to this instance. @@ -369,14 +481,14 @@ public bool Equals(GitVersion? other) { // ReSharper disable NullableWarningSuppressionIsUsed return other! != null! - && Major == other.Major - && Minor == other.Minor - && Patch == other.Patch - && PreReleaseTag == other.PreReleaseTag - && PreReleaseTagWithDash == other.PreReleaseTagWithDash - && InformationalVersion == other.InformationalVersion - && BranchName == other.BranchName - && Sha == other.Sha - && CommitDate == other.CommitDate; - } -} + && Major == other.Major + && Minor == other.Minor + && Patch == other.Patch + && PreReleaseTag == other.PreReleaseTag + && PreReleaseTagWithDash == other.PreReleaseTagWithDash + && InformationalVersion == other.InformationalVersion + && BranchName == other.BranchName + && Sha == other.Sha + && CommitDate == other.CommitDate; + } +} \ No newline at end of file diff --git a/src/Metadata/PrefixExtensions.cs b/src/Metadata/PrefixExtensions.cs index 538c4df0a..2b1daebf9 100644 --- a/src/Metadata/PrefixExtensions.cs +++ b/src/Metadata/PrefixExtensions.cs @@ -27,10 +27,8 @@ internal static void Infer(this AssemblyMetadataProvider provider, T instance var prefix = property.GetCustomAttribute()?.Key ?? string.Empty; var value = provider.GetValue(prefix + property.Name).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(value)) - { property.SetValue(instance, Convert.ChangeType(value, property.PropertyType, CultureInfo.InvariantCulture)); - } } } } -} +} \ No newline at end of file diff --git a/src/Metadata/Rocket.Surgery.LaunchPad.Metadata.csproj b/src/Metadata/Rocket.Surgery.LaunchPad.Metadata.csproj index 8b7ae7346..8f9444ce7 100644 --- a/src/Metadata/Rocket.Surgery.LaunchPad.Metadata.csproj +++ b/src/Metadata/Rocket.Surgery.LaunchPad.Metadata.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/Serilog/Conventions/ConfigureOptionsLoggingConvention.cs b/src/Serilog/Conventions/ConfigureOptionsLoggingConvention.cs index 6b359f890..ddaf14538 100644 --- a/src/Serilog/Conventions/ConfigureOptionsLoggingConvention.cs +++ b/src/Serilog/Conventions/ConfigureOptionsLoggingConvention.cs @@ -29,21 +29,14 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var setup in services.GetServices>()) { if (setup is IConfigureNamedOptions namedSetup) - { namedSetup.Configure(Options.DefaultName, loggerConfiguration); - } else - { setup.Configure(loggerConfiguration); - } } foreach (var post in services.GetServices>()) @@ -51,4 +44,4 @@ LoggerConfiguration loggerConfiguration post.PostConfigure(Options.DefaultName, loggerConfiguration); } } -} +} \ No newline at end of file diff --git a/src/Serilog/Conventions/SerilogEnrichEnvironmentLoggingConvention.cs b/src/Serilog/Conventions/SerilogEnrichEnvironmentLoggingConvention.cs index aadabbee7..adf2c72b6 100644 --- a/src/Serilog/Conventions/SerilogEnrichEnvironmentLoggingConvention.cs +++ b/src/Serilog/Conventions/SerilogEnrichEnvironmentLoggingConvention.cs @@ -27,10 +27,7 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); loggerConfiguration .Enrich.WithEnvironmentUserName() @@ -39,4 +36,4 @@ LoggerConfiguration loggerConfiguration .Enrich.WithProcessName() .Enrich.WithThreadId(); } -} +} \ No newline at end of file diff --git a/src/Serilog/Conventions/SerilogEnrichLoggingConvention.cs b/src/Serilog/Conventions/SerilogEnrichLoggingConvention.cs index a56e293a8..ed088f958 100644 --- a/src/Serilog/Conventions/SerilogEnrichLoggingConvention.cs +++ b/src/Serilog/Conventions/SerilogEnrichLoggingConvention.cs @@ -28,13 +28,10 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); loggerConfiguration .Enrich.FromLogContext() .Enrich.WithExceptionDetails(); } -} +} \ No newline at end of file diff --git a/src/Serilog/Conventions/SerilogEnrichSpansConvention.cs b/src/Serilog/Conventions/SerilogEnrichSpansConvention.cs index 8e246b235..ac34afded 100644 --- a/src/Serilog/Conventions/SerilogEnrichSpansConvention.cs +++ b/src/Serilog/Conventions/SerilogEnrichSpansConvention.cs @@ -28,13 +28,10 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); loggerConfiguration.Enrich.WithSpan( - new SpanOptions + new() { IncludeBaggage = true, IncludeTags = true, @@ -43,4 +40,4 @@ LoggerConfiguration loggerConfiguration } ); } -} +} \ No newline at end of file diff --git a/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs b/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs index 54cf4b935..2657e3b4d 100644 --- a/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs +++ b/src/Serilog/Conventions/SerilogReadFromConfigurationConvention.cs @@ -32,14 +32,10 @@ public class SerilogReadFromConfigurationConvention : ISerilogConvention, IConfi #endif public void Register(IConventionContext context, IConfiguration configuration, IConfigurationBuilder builder) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); var applicationLogLevel = configuration.GetValue("ApplicationState:LogLevel"); if (applicationLogLevel.HasValue) - { builder.AddInMemoryCollection( new Dictionary { @@ -49,7 +45,6 @@ public void Register(IConventionContext context, IConfiguration configuration, I }, } ); - } } /// @@ -60,10 +55,7 @@ public void Register( LoggerConfiguration loggerConfiguration ) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); loggerConfiguration.ReadFrom.Configuration(configuration); } diff --git a/src/Serilog/Rocket.Surgery.LaunchPad.Serilog.csproj b/src/Serilog/Rocket.Surgery.LaunchPad.Serilog.csproj index 84c0db30f..fd08d87af 100644 --- a/src/Serilog/Rocket.Surgery.LaunchPad.Serilog.csproj +++ b/src/Serilog/Rocket.Surgery.LaunchPad.Serilog.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/Serilog/RocketSurgerySerilogExtensions.cs b/src/Serilog/RocketSurgerySerilogExtensions.cs index 87266991f..63aeb6e28 100644 --- a/src/Serilog/RocketSurgerySerilogExtensions.cs +++ b/src/Serilog/RocketSurgerySerilogExtensions.cs @@ -19,23 +19,20 @@ public static class RocketSurgerySerilogExtensions /// /// public static LoggerConfiguration ApplyConventions( - this LoggerConfiguration configurationBuilder, IConventionContext conventionContext, IServiceProvider services + this LoggerConfiguration configurationBuilder, + IConventionContext conventionContext, + IServiceProvider services ) { var configuration = conventionContext.Get() - ?? throw new ArgumentException("Configuration was not found in context", nameof(conventionContext)); + ?? throw new ArgumentException("Configuration was not found in context", nameof(conventionContext)); foreach (var item in conventionContext.Conventions.Get()) { if (item is ISerilogConvention convention) - { convention.Register(conventionContext, services, configuration, configurationBuilder); - } - else if (item is SerilogConvention @delegate) - { - @delegate(conventionContext, services, configuration, configurationBuilder); - } + else if (item is SerilogConvention @delegate) @delegate(conventionContext, services, configuration, configurationBuilder); } return configurationBuilder; } -} +} \ No newline at end of file diff --git a/src/Serilog/SerilogAbstractionsHostBuilderExtensions.cs b/src/Serilog/SerilogAbstractionsHostBuilderExtensions.cs index 7ae675df1..1e228babe 100644 --- a/src/Serilog/SerilogAbstractionsHostBuilderExtensions.cs +++ b/src/Serilog/SerilogAbstractionsHostBuilderExtensions.cs @@ -19,17 +19,11 @@ public static class SerilogAbstractionsHostBuilderExtensions /// IConventionHostBuilder. public static ConventionContextBuilder ConfigureSerilog(this ConventionContextBuilder container, SerilogConvention @delegate) { - if (container == null) - { - throw new ArgumentNullException(nameof(container)); - } + ArgumentNullException.ThrowIfNull(container); - if (@delegate == null) - { - throw new ArgumentNullException(nameof(@delegate)); - } + ArgumentNullException.ThrowIfNull(@delegate); container.AppendDelegate(@delegate); return container; } -} +} \ No newline at end of file diff --git a/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs b/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs index 0bd891db9..c08e44445 100644 --- a/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs +++ b/src/Spatial.NewtonsoftJson/NetTopologySuiteSerializationExtensions.cs @@ -107,7 +107,11 @@ private static void ApplyGeoJsonConverters(GeometryFactory factory, int dimensio .OfType() .Cast() .ToList(); - foreach (var converter in convertersToRemove) converters.Remove(converter); + foreach (var converter in convertersToRemove) + { + converters.Remove(converter); + } + converters.Add(new GeometryConverter(factory, dimension)); ApplyConverters(factory, dimension, converters); } @@ -118,8 +122,12 @@ private static void ApplyWellKnownTextConverters(GeometryFactory factory, int di .OfType() .Cast() .ToList(); - foreach (var converter in convertersToRemove) converters.Remove(converter); + foreach (var converter in convertersToRemove) + { + converters.Remove(converter); + } + converters.Add(new WktGeometryConverter(factory, dimension)); ApplyConverters(factory, dimension, converters); } -} +} \ No newline at end of file diff --git a/src/Spatial.NewtonsoftJson/Rocket.Surgery.LaunchPad.Spatial.NewtonsoftJson.csproj b/src/Spatial.NewtonsoftJson/Rocket.Surgery.LaunchPad.Spatial.NewtonsoftJson.csproj index 73d5f81f7..d1ac69456 100644 --- a/src/Spatial.NewtonsoftJson/Rocket.Surgery.LaunchPad.Spatial.NewtonsoftJson.csproj +++ b/src/Spatial.NewtonsoftJson/Rocket.Surgery.LaunchPad.Spatial.NewtonsoftJson.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) Rocket.Surgery.LaunchPad.Spatial diff --git a/src/Spatial/NetTopologySuiteDestructuringPolicy.cs b/src/Spatial/NetTopologySuiteDestructuringPolicy.cs index 6a00a5384..5fa3106a3 100644 --- a/src/Spatial/NetTopologySuiteDestructuringPolicy.cs +++ b/src/Spatial/NetTopologySuiteDestructuringPolicy.cs @@ -24,7 +24,7 @@ public static LogEventPropertyValue WriteGeometry(Geometry value) if (geometry is Point) return null; - return new LogEventProperty( + return new( "bbox", value.IsNull ? new ScalarValue(null) @@ -40,7 +40,7 @@ public static LogEventPropertyValue WriteGeometry(Geometry value) ); } - private static readonly HashSet GeometryTypes = new HashSet + private static readonly HashSet GeometryTypes = new() { typeof(Geometry), typeof(Point), @@ -54,16 +54,16 @@ public static LogEventPropertyValue WriteGeometry(Geometry value) private static LogEventPropertyValue WriteFeatureCollection(ILogEventPropertyValueFactory propertyValueFactory, FeatureCollection value) { - var props = new List { new("type", new ScalarValue("FeatureCollection")) }; - if (WriteBBox(value.BoundingBox, null) is { } bBox) - { - props.Add(bBox); - } + var props = new List { new("type", new ScalarValue("FeatureCollection")), }; + if (WriteBBox(value.BoundingBox, null) is { } bBox) props.Add(bBox); var values = new List(); foreach (var feature in value) + { values.Add(propertyValueFactory.CreatePropertyValue(feature, true)); - props.Add(new LogEventProperty("features", new SequenceValue(values))); + } + + props.Add(new("features", new SequenceValue(values))); return new StructureValue(props); } @@ -71,36 +71,22 @@ private static LogEventPropertyValue WriteFeatureCollection(ILogEventPropertyVal private readonly string _idPropertyName = idPropertyName ?? defaultIdPropertyName; public NetTopologySuiteDestructuringPolicy() - : this(defaultIdPropertyName) - { - } + : this(defaultIdPropertyName) { } private LogEventPropertyValue WriteFeature(ILogEventPropertyValueFactory propertyValueFactory, IFeature value) { - var props = new List { new("type", new ScalarValue("Feature")) }; + var props = new List { new("type", new ScalarValue("Feature")), }; // Add the id here if present. - if (value.GetOptionalId(_idPropertyName) is { } id) - { - props.Add(new LogEventProperty("id", propertyValueFactory.CreatePropertyValue(id, true))); - } + if (value.GetOptionalId(_idPropertyName) is { } id) props.Add(new("id", propertyValueFactory.CreatePropertyValue(id, true))); // bbox (optional) - if (WriteBBox(value.BoundingBox, value.Geometry) is { } bBox) - { - props.Add(bBox); - } + if (WriteBBox(value.BoundingBox, value.Geometry) is { } bBox) props.Add(bBox); // geometry - if (value.Geometry != null) - { - props.Add(new LogEventProperty("geometry", propertyValueFactory.CreatePropertyValue(value.Geometry, true))); - } + if (value.Geometry != null) props.Add(new("geometry", propertyValueFactory.CreatePropertyValue(value.Geometry, true))); // properties - if (value.Attributes != null) - { - props.Add(new LogEventProperty("properties", propertyValueFactory.CreatePropertyValue(value.Attributes, true))); - } + if (value.Attributes != null) props.Add(new("properties", propertyValueFactory.CreatePropertyValue(value.Attributes, true))); return new StructureValue(props); } @@ -111,10 +97,7 @@ private LogEventPropertyValue WriteAttributes(ILogEventPropertyValueFactory prop foreach (var propertyName in value.GetNames()) { // skip id - if (propertyName != _idPropertyName) - { - props.Add(new LogEventProperty(propertyName, propertyValueFactory.CreatePropertyValue(value[propertyName], true))); - } + if (propertyName != _idPropertyName) props.Add(new(propertyName, propertyValueFactory.CreatePropertyValue(value[propertyName], true))); } return new StructureValue(props); @@ -149,7 +132,4 @@ public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyV result = null; return false; } -} - - - +} \ No newline at end of file diff --git a/src/Spatial/NetTopologySuiteSystemTextJsonSerializationExtensions.cs b/src/Spatial/NetTopologySuiteSystemTextJsonSerializationExtensions.cs index 6d4e5d18d..7274f6845 100644 --- a/src/Spatial/NetTopologySuiteSystemTextJsonSerializationExtensions.cs +++ b/src/Spatial/NetTopologySuiteSystemTextJsonSerializationExtensions.cs @@ -33,7 +33,11 @@ public static JsonSerializerOptions ConfigureGeoJsonForLaunchPad(this JsonSerial { factory ??= NtsGeometryServices.Instance.CreateGeometryFactory(4326); var existingConverters = options.Converters.OfType().ToArray(); - foreach (var converter in existingConverters) options.Converters.Remove(converter); + foreach (var converter in existingConverters) + { + options.Converters.Remove(converter); + } + options.Converters.Add(new GeoJsonConverterFactory(factory)); return options; } @@ -48,8 +52,12 @@ public static JsonSerializerOptions ConfigureWellKnownTextForLaunchPad(this Json { factory ??= NtsGeometryServices.Instance.CreateGeometryFactory(4326); var existingConverters = options.Converters.OfType().ToArray(); - foreach (var converter in existingConverters) options.Converters.Remove(converter); + foreach (var converter in existingConverters) + { + options.Converters.Remove(converter); + } + options.Converters.Add(new WktConverterFactory(factory)); return options; } -} +} \ No newline at end of file diff --git a/src/Spatial/Rocket.Surgery.LaunchPad.Spatial.csproj b/src/Spatial/Rocket.Surgery.LaunchPad.Spatial.csproj index 6e1338895..70fd7c23d 100644 --- a/src/Spatial/Rocket.Surgery.LaunchPad.Spatial.csproj +++ b/src/Spatial/Rocket.Surgery.LaunchPad.Spatial.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/StrawberryShake.Spatial/Rocket.Surgery.LaunchPad.StrawberryShake.Spatial.csproj b/src/StrawberryShake.Spatial/Rocket.Surgery.LaunchPad.StrawberryShake.Spatial.csproj index cd839c44a..07cb0c62d 100644 --- a/src/StrawberryShake.Spatial/Rocket.Surgery.LaunchPad.StrawberryShake.Spatial.csproj +++ b/src/StrawberryShake.Spatial/Rocket.Surgery.LaunchPad.StrawberryShake.Spatial.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj b/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj index 095fc0cb1..f6d5febb5 100644 --- a/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj +++ b/src/StrawberryShake/Rocket.Surgery.LaunchPad.StrawberryShake.csproj @@ -1,6 +1,6 @@  - net6.0;net8.0 + net8.0 $(PackageTags) false diff --git a/src/Telemetry/IOpenTelemetryAsyncConvention.cs b/src/Telemetry/IOpenTelemetryAsyncConvention.cs new file mode 100644 index 000000000..0c05c3f07 --- /dev/null +++ b/src/Telemetry/IOpenTelemetryAsyncConvention.cs @@ -0,0 +1,22 @@ +using Microsoft.Extensions.Configuration; +using OpenTelemetry; +using Rocket.Surgery.Conventions; + +namespace Rocket.Surgery.LaunchPad.Telemetry; + +/// +/// IMetricsConvention +/// Implements the +/// +/// +public interface IOpenTelemetryAsyncConvention : IConvention +{ + /// + /// Register metrics + /// + /// + /// + /// + /// + ValueTask Register(IConventionContext conventionContext, IConfiguration configuration, IOpenTelemetryBuilder builder, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/Hosting/Telemetry/IOpenTelemetryMetricsConvention.cs b/src/Telemetry/IOpenTelemetryConvention.cs similarity index 83% rename from src/Hosting/Telemetry/IOpenTelemetryMetricsConvention.cs rename to src/Telemetry/IOpenTelemetryConvention.cs index b898f0549..22a63e84a 100644 --- a/src/Hosting/Telemetry/IOpenTelemetryMetricsConvention.cs +++ b/src/Telemetry/IOpenTelemetryConvention.cs @@ -2,7 +2,7 @@ using OpenTelemetry; using Rocket.Surgery.Conventions; -namespace Rocket.Surgery.LaunchPad.Hosting.Telemetry; +namespace Rocket.Surgery.LaunchPad.Telemetry; /// /// IMetricsConvention @@ -17,5 +17,5 @@ public interface IOpenTelemetryConvention : IConvention /// /// /// - void Register(IConventionContext conventionContext, IConfiguration configuration, OpenTelemetryBuilder builder); -} + void Register(IConventionContext conventionContext, IConfiguration configuration, IOpenTelemetryBuilder builder); +} \ No newline at end of file diff --git a/src/Telemetry/IOpenTelemetryMetricsConvention.cs b/src/Telemetry/IOpenTelemetryMetricsConvention.cs index 5a27d90bb..f5d0994db 100644 --- a/src/Telemetry/IOpenTelemetryMetricsConvention.cs +++ b/src/Telemetry/IOpenTelemetryMetricsConvention.cs @@ -1,38 +1 @@ -using Microsoft.Extensions.Configuration; -using OpenTelemetry.Metrics; -using OpenTelemetry.Trace; -using Rocket.Surgery.Conventions; - -namespace Rocket.Surgery.LaunchPad.Telemetry; - -/// -/// IOpenTelemetryMetricsConvention -/// Implements the -/// -/// -public interface IOpenTelemetryMetricsConvention : IConvention -{ - /// - /// Register metrics - /// - /// - /// - /// - void Register(IConventionContext conventionContext, IConfiguration configuration, MeterProviderBuilder builder); -} - -/// -/// IOpenTelemetryTracingConvention -/// Implements the -/// -/// -public interface IOpenTelemetryTracingConvention : IConvention -{ - /// - /// Register tracing - /// - /// - /// - /// - void Register(IConventionContext conventionContext, IConfiguration configuration, TracerProviderBuilder builder); -} +namespace Rocket.Surgery.LaunchPad.Telemetry; \ No newline at end of file diff --git a/src/Telemetry/OpenTelemetryAsyncConvention.cs b/src/Telemetry/OpenTelemetryAsyncConvention.cs new file mode 100644 index 000000000..dde1c3104 --- /dev/null +++ b/src/Telemetry/OpenTelemetryAsyncConvention.cs @@ -0,0 +1,19 @@ +using Microsoft.Extensions.Configuration; +using OpenTelemetry; +using Rocket.Surgery.Conventions; + +namespace Rocket.Surgery.LaunchPad.Telemetry; + +/// +/// Delegate OpenTelemetryAsyncConvention +/// +/// +/// +/// +/// +public delegate ValueTask OpenTelemetryAsyncConvention( + IConventionContext conventionContext, + IConfiguration configuration, + IOpenTelemetryBuilder builder, + CancellationToken cancellationToken +); \ No newline at end of file diff --git a/src/Hosting/Telemetry/OpenTelemetryMetricsConvention.cs b/src/Telemetry/OpenTelemetryConvention.cs similarity index 63% rename from src/Hosting/Telemetry/OpenTelemetryMetricsConvention.cs rename to src/Telemetry/OpenTelemetryConvention.cs index 35dec1a9d..282679ef8 100644 --- a/src/Hosting/Telemetry/OpenTelemetryMetricsConvention.cs +++ b/src/Telemetry/OpenTelemetryConvention.cs @@ -2,12 +2,12 @@ using OpenTelemetry; using Rocket.Surgery.Conventions; -namespace Rocket.Surgery.LaunchPad.Hosting.Telemetry; +namespace Rocket.Surgery.LaunchPad.Telemetry; /// -/// Delegate OpenTelemetryMetricsConvention +/// Delegate OpenTelemetryConvention /// /// /// /// -public delegate void OpenTelemetryConvention(IConventionContext conventionContext, IConfiguration configuration, OpenTelemetryBuilder builder); +public delegate void OpenTelemetryConvention(IConventionContext conventionContext, IConfiguration configuration, IOpenTelemetryBuilder builder); \ No newline at end of file diff --git a/src/Telemetry/OpenTelemetryHostBuilderExtensions.cs b/src/Telemetry/OpenTelemetryHostBuilderExtensions.cs deleted file mode 100644 index cb79a6171..000000000 --- a/src/Telemetry/OpenTelemetryHostBuilderExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -// ReSharper disable once CheckNamespace - -using Rocket.Surgery.LaunchPad.Telemetry; - -// ReSharper disable once CheckNamespace -namespace Rocket.Surgery.Conventions; - -/// -/// Helper method for working with -/// -[PublicAPI] -public static class OpenTelemetryHostBuilderExtensions -{ - /// - /// Configure the serilog delegate to the convention scanner - /// - /// The container. - /// The delegate. - /// IConventionHostBuilder. - public static ConventionContextBuilder ConfigureOpenTelemetryMetrics(this ConventionContextBuilder container, OpenTelemetryMetricsConvention @delegate) - { - if (container == null) - { - throw new ArgumentNullException(nameof(container)); - } - - if (@delegate == null) - { - throw new ArgumentNullException(nameof(@delegate)); - } - - container.AppendDelegate(@delegate); - return container; - } - - /// - /// Configure the serilog delegate to the convention scanner - /// - /// The container. - /// The delegate. - /// IConventionHostBuilder. - public static ConventionContextBuilder ConfigureOpenTelemetryTracing(this ConventionContextBuilder container, OpenTelemetryTracingConvention @delegate) - { - if (container == null) - { - throw new ArgumentNullException(nameof(container)); - } - - if (@delegate == null) - { - throw new ArgumentNullException(nameof(@delegate)); - } - - container.AppendDelegate(@delegate); - return container; - } -} diff --git a/src/Telemetry/Rocket.Surgery.LaunchPad.Telemetry.csproj b/src/Telemetry/Rocket.Surgery.LaunchPad.Telemetry.csproj index a7ed8c48e..d4194ba25 100644 --- a/src/Telemetry/Rocket.Surgery.LaunchPad.Telemetry.csproj +++ b/src/Telemetry/Rocket.Surgery.LaunchPad.Telemetry.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) diff --git a/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs b/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs index 7cd74d170..8458d2093 100644 --- a/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs +++ b/src/Telemetry/RocketSurgeryOpenTelemetryExtensions.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.Configuration; -using OpenTelemetry.Metrics; -using OpenTelemetry.Trace; +using OpenTelemetry; using Rocket.Surgery.Conventions; namespace Rocket.Surgery.LaunchPad.Telemetry; @@ -16,20 +15,35 @@ public static class RocketSurgeryOpenTelemetryExtensions /// /// /// + /// /// - public static MeterProviderBuilder ApplyConventions(this MeterProviderBuilder builder, IConventionContext conventionContext) + public static async ValueTask ApplyConventionsAsync( + this IOpenTelemetryBuilder builder, + IConventionContext conventionContext, + CancellationToken cancellationToken = default + ) { var configuration = conventionContext.Get() - ?? throw new ArgumentException("Configuration was not found in context", nameof(conventionContext)); - foreach (var item in conventionContext.Conventions.Get()) + ?? throw new ArgumentException("Configuration was not found in context", nameof(conventionContext)); + + foreach (var item in conventionContext.Conventions + .Get()) { - if (item is IOpenTelemetryMetricsConvention convention) - { - convention.Register(conventionContext, configuration, builder); - } - else if (item is OpenTelemetryMetricsConvention @delegate) + switch (item) { - @delegate(conventionContext, configuration, builder); + case IOpenTelemetryConvention convention: + convention.Register(conventionContext, configuration, builder); + break; + case OpenTelemetryConvention @delegate: + @delegate(conventionContext, configuration, builder); + break; + case IOpenTelemetryAsyncConvention convention: + await convention.Register(conventionContext, configuration, builder, cancellationToken); + break; + case OpenTelemetryAsyncConvention @delegate: + await @delegate(conventionContext, configuration, builder, cancellationToken); + break; } } @@ -37,27 +51,86 @@ public static MeterProviderBuilder ApplyConventions(this MeterProviderBuilder bu } /// - /// Apply configuration conventions + /// Configure the serilog delegate to the convention scanner /// - /// - /// - /// - public static TracerProviderBuilder ApplyConventions(this TracerProviderBuilder builder, IConventionContext conventionContext) + /// The container. + /// The delegate. + /// IConventionHostBuilder. + public static ConventionContextBuilder ConfigureOpenTelemetry(this ConventionContextBuilder container, OpenTelemetryConvention @delegate) { - var configuration = conventionContext.Get() - ?? throw new ArgumentException("Configuration was not found in context", nameof(conventionContext)); - foreach (var item in conventionContext.Conventions.Get()) - { - if (item is IOpenTelemetryTracingConvention convention) - { - convention.Register(conventionContext, configuration, builder); - } - else if (item is OpenTelemetryTracingConvention @delegate) - { - @delegate(conventionContext, configuration, builder); - } - } + ArgumentNullException.ThrowIfNull(container); - return builder; + ArgumentNullException.ThrowIfNull(@delegate); + + container.AppendDelegate(@delegate); + return container; + } + + + /// + /// Configure the serilog delegate to the convention scanner + /// + /// The container. + /// The delegate. + /// IConventionHostBuilder. + public static ConventionContextBuilder ConfigureOpenTelemetry(this ConventionContextBuilder container, Action @delegate) + { + ArgumentNullException.ThrowIfNull(container); + + ArgumentNullException.ThrowIfNull(@delegate); + + container.AppendDelegate(@delegate); + return container; + } + + /// + /// Configure the serilog delegate to the convention scanner + /// + /// The container. + /// The delegate. + /// IConventionHostBuilder. + public static ConventionContextBuilder ConfigureOpenTelemetry(this ConventionContextBuilder container, OpenTelemetryAsyncConvention @delegate) + { + ArgumentNullException.ThrowIfNull(container); + + ArgumentNullException.ThrowIfNull(@delegate); + + container.AppendDelegate(@delegate); + return container; + } + + /// + /// Configure the serilog delegate to the convention scanner + /// + /// The container. + /// The delegate. + /// IConventionHostBuilder. + public static ConventionContextBuilder ConfigureOpenTelemetry(this ConventionContextBuilder container, Func @delegate) + { + ArgumentNullException.ThrowIfNull(container); + + ArgumentNullException.ThrowIfNull(@delegate); + + container.AppendDelegate(new OpenTelemetryAsyncConvention((_, _, builder, _) => @delegate(builder))); + return container; + } + + /// + /// Configure the serilog delegate to the convention scanner + /// + /// The container. + /// The delegate. + /// IConventionHostBuilder. + public static ConventionContextBuilder ConfigureOpenTelemetry( + this ConventionContextBuilder container, + Func @delegate + ) + { + ArgumentNullException.ThrowIfNull(container); + + ArgumentNullException.ThrowIfNull(@delegate); + + container.AppendDelegate(new OpenTelemetryAsyncConvention((_, _, builder, token) => @delegate(builder, token))); + return container; } -} +} \ No newline at end of file diff --git a/src/Testing/FakeClockConvention.cs b/src/Testing/FakeClockConvention.cs index 1ccb73bff..df77a64fc 100644 --- a/src/Testing/FakeClockConvention.cs +++ b/src/Testing/FakeClockConvention.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using NodaTime; using NodaTime.Testing; using Rocket.Surgery.Conventions; @@ -35,7 +34,7 @@ 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(provider => provider.GetRequiredService()); + services.AddSingleton(new FakeClock(Instant.FromUnixTimeSeconds(_unixTimeSeconds), _advanceBy)); + services.AddSingleton(provider => provider.GetRequiredService()); } -} +} \ No newline at end of file diff --git a/src/Testing/Rocket.Surgery.LaunchPad.Testing.csproj b/src/Testing/Rocket.Surgery.LaunchPad.Testing.csproj index d633ae8de..33c5901f3 100644 --- a/src/Testing/Rocket.Surgery.LaunchPad.Testing.csproj +++ b/src/Testing/Rocket.Surgery.LaunchPad.Testing.csproj @@ -1,6 +1,6 @@  - netstandard2.1;net6.0;net8.0 + net8.0 $(PackageTags) @@ -9,9 +9,11 @@ - + + + diff --git a/src/Web.Hosting/Rocket.Surgery.LaunchPad.Web.Hosting.csproj b/src/Web.Hosting/Rocket.Surgery.LaunchPad.Web.Hosting.csproj index 7fdc5e295..423ae61cc 100644 --- a/src/Web.Hosting/Rocket.Surgery.LaunchPad.Web.Hosting.csproj +++ b/src/Web.Hosting/Rocket.Surgery.LaunchPad.Web.Hosting.csproj @@ -1,11 +1,11 @@  - net6.0;net8.0 + net8.0 $(PackageTags) - + diff --git a/test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj b/test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj deleted file mode 100644 index b528e9a5b..000000000 --- a/test/Analyzers.Tests.roslyn4.0/Analyzers.Tests.roslyn4.0.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - net8.0 - <_Analyzer_Roslyn_Version_>$(MSBuildProjectName.Replace("Analyzers.Tests.", "")) - $(DefineConstants);ROSLYN4_0 - Analyzers.Tests - Analyzers.Tests - - - - - - - - - - - - - - - - - diff --git a/test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj b/test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj deleted file mode 100644 index e12879fa0..000000000 --- a/test/Analyzers.Tests.roslyn4.4/Analyzers.Tests.roslyn4.4.csproj +++ /dev/null @@ -1,24 +0,0 @@ - - - net8.0 - <_Analyzer_Roslyn_Version_>$(MSBuildProjectName.Replace("Analyzers.Tests.", "")) - $(DefineConstants);ROSLYN4_4 - Analyzers.Tests - Analyzers.Tests - - - - - - - - - - - - - - - - - diff --git a/test/Analyzers.Tests.roslyn4.6/Analyzers.Tests.roslyn4.6.csproj b/test/Analyzers.Tests.roslyn4.6/Analyzers.Tests.roslyn4.6.csproj index fafcb5b55..d448a7c3a 100644 --- a/test/Analyzers.Tests.roslyn4.6/Analyzers.Tests.roslyn4.6.csproj +++ b/test/Analyzers.Tests.roslyn4.6/Analyzers.Tests.roslyn4.6.csproj @@ -1,6 +1,6 @@ - net8.0 + net8.0 <_Analyzer_Roslyn_Version_>$(MSBuildProjectName.Replace("Analyzers.Tests.", "")) $(DefineConstants);ROSLYN4_6 Analyzers.Tests diff --git a/test/Analyzers.Tests/Analyzers.Tests.csproj b/test/Analyzers.Tests/Analyzers.Tests.csproj index 4d79fdabf..d085ea6f6 100644 --- a/test/Analyzers.Tests/Analyzers.Tests.csproj +++ b/test/Analyzers.Tests/Analyzers.Tests.csproj @@ -1,6 +1,6 @@ - net8.0 + net8.0 $(DefineConstants);ROSLYN_CURRENT;ROSLYN4_8 diff --git a/test/Analyzers.Tests/GeneratorTest.cs b/test/Analyzers.Tests/GeneratorTest.cs index eb15c7e86..aa2e35b22 100644 --- a/test/Analyzers.Tests/GeneratorTest.cs +++ b/test/Analyzers.Tests/GeneratorTest.cs @@ -39,7 +39,6 @@ public virtual Task InitializeAsync() .WithAssemblyLoadContext(AssemblyLoadContext) .AddReferences( typeof(ActivatorUtilities).Assembly, - typeof(ConventionAttribute).Assembly, typeof(ConventionContext).Assembly, typeof(IConventionContext).Assembly ); @@ -49,10 +48,7 @@ public virtual Task InitializeAsync() public virtual Task DisposeAsync() { - if (AssemblyLoadContext is IDisposable disposable) - { - Disposables.Add(disposable); - } + if (AssemblyLoadContext is IDisposable disposable) Disposables.Add(disposable); Disposables.Dispose(); return Task.CompletedTask; diff --git a/test/Analyzers.Tests/GraphqlOptionalPropertyTrackingGeneratorTests.cs b/test/Analyzers.Tests/GraphqlOptionalPropertyTrackingGeneratorTests.cs index a71f10f7f..8cc5a7793 100644 --- a/test/Analyzers.Tests/GraphqlOptionalPropertyTrackingGeneratorTests.cs +++ b/test/Analyzers.Tests/GraphqlOptionalPropertyTrackingGeneratorTests.cs @@ -426,10 +426,7 @@ public partial class Request : IRequest public async Task Should_Generate_Record_With_Underlying_Properties_And_Create(string property, object value, PropertyTracking propertyTracking) { var valueType = value.GetType(); - if (value.GetType().IsValueType) - { - valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); - } + if (value.GetType().IsValueType) valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); var result = await AddPatchRocketModel(RocketModelType.Record, propertyTracking) .AddSources( @@ -475,10 +472,7 @@ public record Request : IRequest public async Task Should_Generate_Class_With_Underlying_Properties_And_Create(string property, object value, PropertyTracking propertyTracking) { var valueType = value.GetType(); - if (value.GetType().IsValueType) - { - valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); - } + if (value.GetType().IsValueType) valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); var result = await AddPatchRocketModel(RocketModelType.Class, propertyTracking) .AddSources( @@ -528,10 +522,7 @@ PropertyTracking propertyTracking ) { var valueType = value.GetType(); - if (value.GetType().IsValueType) - { - valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); - } + if (value.GetType().IsValueType) valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); var result = await AddPatchRocketModel(RocketModelType.Record, propertyTracking) .AddSources( @@ -585,10 +576,7 @@ PropertyTracking propertyTracking ) { var valueType = value.GetType(); - if (value.GetType().IsValueType) - { - valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); - } + if (value.GetType().IsValueType) valueType = typeof(Nullable<>).MakeGenericType(value.GetType()); var result = await AddPatchRocketModel(modelType, propertyTracking) .AddSources( diff --git a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator.verified.txt b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator.verified.txt index 324340c2c..5a48cfb22 100644 --- a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator.verified.txt +++ b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator.verified.txt @@ -14,7 +14,6 @@ netstandard.dll, NodaTime.dll, Rocket.Surgery.Conventions.Abstractions.dll, - Rocket.Surgery.Conventions.Attributes.dll, Rocket.Surgery.Conventions.dll, Rocket.Surgery.LaunchPad.Foundation.dll, Rocket.Surgery.LaunchPad.Foundation.dll, diff --git a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=OtherAssembly.verified.txt b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=OtherAssembly.verified.txt index 15661dec8..550da3229 100644 --- a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=OtherAssembly.verified.txt +++ b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=OtherAssembly.verified.txt @@ -13,7 +13,6 @@ netstandard.dll, NodaTime.dll, Rocket.Surgery.Conventions.Abstractions.dll, - Rocket.Surgery.Conventions.Attributes.dll, Rocket.Surgery.Conventions.dll, Rocket.Surgery.LaunchPad.Foundation.dll, Rocket.Surgery.LaunchPad.Foundation.dll, diff --git a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=SameAssembly.verified.txt b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=SameAssembly.verified.txt index 324340c2c..5a48cfb22 100644 --- a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=SameAssembly.verified.txt +++ b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute2_propertyTracking=SameAssembly.verified.txt @@ -14,7 +14,6 @@ netstandard.dll, NodaTime.dll, Rocket.Surgery.Conventions.Abstractions.dll, - Rocket.Surgery.Conventions.Attributes.dll, Rocket.Surgery.Conventions.dll, Rocket.Surgery.LaunchPad.Foundation.dll, Rocket.Surgery.LaunchPad.Foundation.dll, diff --git a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=OtherAssembly.verified.txt b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=OtherAssembly.verified.txt index 15661dec8..550da3229 100644 --- a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=OtherAssembly.verified.txt +++ b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=OtherAssembly.verified.txt @@ -13,7 +13,6 @@ netstandard.dll, NodaTime.dll, Rocket.Surgery.Conventions.Abstractions.dll, - Rocket.Surgery.Conventions.Attributes.dll, Rocket.Surgery.Conventions.dll, Rocket.Surgery.LaunchPad.Foundation.dll, Rocket.Surgery.LaunchPad.Foundation.dll, diff --git a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=SameAssembly.verified.txt b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=SameAssembly.verified.txt index 324340c2c..5a48cfb22 100644 --- a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=SameAssembly.verified.txt +++ b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_Attribute_propertyTracking=SameAssembly.verified.txt @@ -14,7 +14,6 @@ netstandard.dll, NodaTime.dll, Rocket.Surgery.Conventions.Abstractions.dll, - Rocket.Surgery.Conventions.Attributes.dll, Rocket.Surgery.Conventions.dll, Rocket.Surgery.LaunchPad.Foundation.dll, Rocket.Surgery.LaunchPad.Foundation.dll, diff --git a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=OtherAssembly.verified.txt b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=OtherAssembly.verified.txt index a0bfbea87..9f5ebe93a 100644 --- a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=OtherAssembly.verified.txt +++ b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=OtherAssembly.verified.txt @@ -30,7 +30,6 @@ netstandard.dll, NodaTime.dll, Rocket.Surgery.Conventions.Abstractions.dll, - Rocket.Surgery.Conventions.Attributes.dll, Rocket.Surgery.Conventions.dll, Rocket.Surgery.LaunchPad.Foundation.dll, Rocket.Surgery.LaunchPad.Foundation.dll, diff --git a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=SameAssembly.verified.txt b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=SameAssembly.verified.txt index 324340c2c..5a48cfb22 100644 --- a/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=SameAssembly.verified.txt +++ b/test/Analyzers.Tests/snapshots/GraphqlOptionalPropertyTrackingGeneratorTests.Should_Generate_Class_With_Underlying_IPropertyTracking_Properties_When_Using_InheritsFromGenerator_Exclude_propertyTracking=SameAssembly.verified.txt @@ -14,7 +14,6 @@ netstandard.dll, NodaTime.dll, Rocket.Surgery.Conventions.Abstractions.dll, - Rocket.Surgery.Conventions.Attributes.dll, Rocket.Surgery.Conventions.dll, Rocket.Surgery.LaunchPad.Foundation.dll, Rocket.Surgery.LaunchPad.Foundation.dll, diff --git a/test/AspNetCore.Tests/AspNetCore.Tests.csproj b/test/AspNetCore.Tests/AspNetCore.Tests.csproj index 30632d5ce..0dcffc9ef 100644 --- a/test/AspNetCore.Tests/AspNetCore.Tests.csproj +++ b/test/AspNetCore.Tests/AspNetCore.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Extensions.Tests/ConventionFakeTest.cs b/test/Extensions.Tests/ConventionFakeTest.cs index cb3a31321..319309b24 100644 --- a/test/Extensions.Tests/ConventionFakeTest.cs +++ b/test/Extensions.Tests/ConventionFakeTest.cs @@ -1,5 +1,5 @@ +using System.Runtime.Loader; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyModel; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.Testing; using Rocket.Surgery.Extensions.Testing; @@ -8,14 +8,16 @@ namespace Extensions.Tests; public abstract class ConventionFakeTest(ITestOutputHelper testOutputHelper) : AutoFakeTest(testOutputHelper) { - protected void Init(Action? action = null) + protected async Task Init(Action? action = null) { - var conventionContextBuilder = ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) - .WithLogger(Logger); + var conventionContextBuilder = ConventionContextBuilder + .Create() + .ForTesting(Imports.Instance, LoggerFactory) + .Set(AssemblyLoadContext.Default) + .WithLogger(Logger); action?.Invoke(conventionContextBuilder); - var context = ConventionContext.From(conventionContextBuilder); + var context = await ConventionContext.FromAsync(conventionContextBuilder); - Populate(new ServiceCollection().ApplyConventions(context)); + Populate(await new ServiceCollection().ApplyConventionsAsync(context)); } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Extensions.Tests.csproj b/test/Extensions.Tests/Extensions.Tests.csproj index d6c0f94b9..9158f4084 100644 --- a/test/Extensions.Tests/Extensions.Tests.csproj +++ b/test/Extensions.Tests/Extensions.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Extensions.Tests/FakeClockConventionTests.cs b/test/Extensions.Tests/FakeClockConventionTests.cs index a9d915e44..f7b50c735 100644 --- a/test/Extensions.Tests/FakeClockConventionTests.cs +++ b/test/Extensions.Tests/FakeClockConventionTests.cs @@ -9,11 +9,9 @@ namespace Extensions.Tests; public class FakeClockConventionTests(ITestOutputHelper testOutputHelper) : ConventionFakeTest(testOutputHelper) { [Fact] - public void Clock_Convention_Default() + public async Task Clock_Convention_Default() { - Init( - x => { x.Set(HostType.UnitTest); } - ); + await Init(x => { x.Set(HostType.UnitTest); }); var clock = Container.GetRequiredService(); clock.Should().BeOfType(); clock.GetCurrentInstant().Should().Be(Instant.FromUnixTimeSeconds(1577836800)); @@ -21,15 +19,13 @@ public void Clock_Convention_Default() } [Fact] - public void Clock_Convention_Override() + public async Task Clock_Convention_Override() { - Init( - x => { x.AppendConvention(new FakeClockConvention(0, Duration.FromMinutes(1))); } - ); + await Init(x => { x.AppendConvention(new FakeClockConvention(0, Duration.FromMinutes(1))); }); var clock = ServiceProvider.GetRequiredService(); clock.Should().BeOfType(); clock.GetCurrentInstant().Should().Be(Instant.FromUnixTimeSeconds(0)); clock.GetCurrentInstant().Should().Be(Instant.FromUnixTimeSeconds(0) + Duration.FromMinutes(1)); } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/FeatureFactory.cs b/test/Extensions.Tests/FeatureFactory.cs index 7dae6c59a..768e521ac 100644 --- a/test/Extensions.Tests/FeatureFactory.cs +++ b/test/Extensions.Tests/FeatureFactory.cs @@ -17,10 +17,10 @@ public static IFeature Create(OgcGeometryType geometryType, in bool threeD = fal } private const int PrecisionScale = 100; - private static readonly PrecisionModel PM = new PrecisionModel(PrecisionScale); - private static readonly GeometryFactory GF = new GeometryFactory(PM, 4326); - private static readonly string[] RNDNames = { "Random", "Zufall", "Hasard", "Caso", "Azar" }; - private static readonly Geometry Bounds = GF.ToGeometry(new Envelope(-BoundX, BoundX, -BoundY, BoundY)); + private static readonly PrecisionModel PM = new(PrecisionScale); + private static readonly GeometryFactory GF = new(PM, 4326); + private static readonly string[] RNDNames = { "Random", "Zufall", "Hasard", "Caso", "Azar", }; + private static readonly Geometry Bounds = GF.ToGeometry(new(-BoundX, BoundX, -BoundY, BoundY)); private const int BoundX = 180 * PrecisionScale; private const int BoundY = 90 * PrecisionScale; @@ -57,27 +57,27 @@ private static void SetCoordinate(CoordinateSequence cs, int index, Coordinate c public FeatureFactory() { - _random = new Random(17); + _random = new(17); } public IAttributesTable CreateRandomAttributes(params (string, TypeCode)[] properties) { var res = new AttributesTable(); - foreach (var (name, type) in properties) + foreach (( var name, var type ) in properties) { var value = type switch - { - TypeCode.Boolean => _random.NextDouble() > 0.5d, - TypeCode.Double => 500d * _random.NextDouble(), - TypeCode.Single => 500f * (float)_random.NextDouble(), - TypeCode.Empty => null, - TypeCode.Int16 => _random.Next(short.MinValue, short.MaxValue), - TypeCode.Int32 => _random.Next(int.MinValue, int.MaxValue), - TypeCode.Int64 => 5L * _random.Next(int.MinValue, int.MaxValue), - TypeCode.String => RandomString(), - TypeCode.Object => Guid.NewGuid(), - _ => _random.NextDouble() > 0.5d ? RandomString() : null - }; + { + TypeCode.Boolean => _random.NextDouble() > 0.5d, + TypeCode.Double => 500d * _random.NextDouble(), + TypeCode.Single => 500f * (float)_random.NextDouble(), + TypeCode.Empty => null, + TypeCode.Int16 => _random.Next(short.MinValue, short.MaxValue), + TypeCode.Int32 => _random.Next(int.MinValue, int.MaxValue), + TypeCode.Int64 => 5L * _random.Next(int.MinValue, int.MaxValue), + TypeCode.String => RandomString(), + TypeCode.Object => Guid.NewGuid(), + _ => _random.NextDouble() > 0.5d ? RandomString() : null, + }; res.Add(name, value); } @@ -153,7 +153,7 @@ public LineString CreateLineString(bool threeD) if (threeD) pt = new CoordinateZ(pt.X + tmp.X, pt.Y + tmp.Y, start.Z + ( dz * pointsAt[i] )); else - pt = new Coordinate(pt.X + tmp.X, pt.Y + tmp.Y); + pt = new(pt.X + tmp.X, pt.Y + tmp.Y); Clamp(pt); PM.MakePrecise(pt); @@ -196,7 +196,10 @@ private MultiPoint CreateMultiPoint(in bool threeD) { var geoms = new Point[_random.Next(2, 10)]; for (var i = 0; i < geoms.Length; i++) + { geoms[i] = CreatePoint(threeD); + } + return GF.CreateMultiPoint(geoms); } @@ -204,7 +207,10 @@ private MultiLineString CreateMultiLineString(in bool threeD) { var geoms = new LineString[_random.Next(2, 10)]; for (var i = 0; i < geoms.Length; i++) + { geoms[i] = CreateLineString(threeD); + } + return GF.CreateMultiLineString(geoms); } @@ -212,7 +218,10 @@ private MultiPolygon CreateMultiPolygon(in bool threeD) { var geoms = new Polygon[_random.Next(2, 10)]; for (var i = 0; i < geoms.Length; i++) + { geoms[i] = CreatePolygon(threeD); + } + return GF.CreateMultiPolygon(geoms); } @@ -242,9 +251,12 @@ private double[] CreatePositions(int num) { var tmp = new List(num); for (var i = 0; i < num; i++) + { tmp.Add(_random.NextDouble()); + } + tmp.Sort(); return tmp.ToArray(); } } -#endif +#endif \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/AutoMapperProfile.cs b/test/Extensions.Tests/Mapping/AutoMapperProfile.cs index b4a8ae9f8..4ee1d8634 100644 --- a/test/Extensions.Tests/Mapping/AutoMapperProfile.cs +++ b/test/Extensions.Tests/Mapping/AutoMapperProfile.cs @@ -1,4 +1,6 @@ +using System.Runtime.Loader; using AutoMapper; +using Rocket.Surgery.Conventions; using Rocket.Surgery.Extensions.Testing; using Rocket.Surgery.LaunchPad.Mapping; @@ -10,42 +12,86 @@ public static class AutoMapperProfile { private class ParentModel { - [UsedImplicitly] public int Integer { get; set; } - [UsedImplicitly] public int? NullableInteger { get; set; } - [UsedImplicitly] public string? String { get; set; } - [UsedImplicitly] public decimal Decimal { get; set; } - [UsedImplicitly] public decimal? NullableDecimal { get; set; } - [UsedImplicitly] public ChildModel? Child { get; set; } + [UsedImplicitly] + public int Integer { get; set; } + + [UsedImplicitly] + public int? NullableInteger { get; set; } + + [UsedImplicitly] + public string? String { get; set; } + + [UsedImplicitly] + public decimal Decimal { get; set; } + + [UsedImplicitly] + public decimal? NullableDecimal { get; set; } + + [UsedImplicitly] + public ChildModel? Child { get; set; } } private class ParentDto { - [UsedImplicitly] public int Integer { get; set; } - [UsedImplicitly] public int Version { get; set; } - [UsedImplicitly] public int? NullableInteger { get; set; } - [UsedImplicitly] public string? String { get; set; } - [UsedImplicitly] public decimal Decimal { get; set; } - [UsedImplicitly] public decimal? NullableDecimal { get; set; } - [UsedImplicitly] public ChildDto? Child { get; set; } + [UsedImplicitly] + public int Integer { get; set; } + + [UsedImplicitly] + public int Version { get; set; } + + [UsedImplicitly] + public int? NullableInteger { get; set; } + + [UsedImplicitly] + public string? String { get; set; } + + [UsedImplicitly] + public decimal Decimal { get; set; } + + [UsedImplicitly] + public decimal? NullableDecimal { get; set; } + + [UsedImplicitly] + public ChildDto? Child { get; set; } } private class ChildModel { - [UsedImplicitly] public int Integer { get; set; } - [UsedImplicitly] public int? NullableInteger { get; set; } - [UsedImplicitly] public string? String { get; set; } - [UsedImplicitly] public decimal Decimal { get; set; } - [UsedImplicitly] public decimal? NullableDecimal { get; set; } + [UsedImplicitly] + public int Integer { get; set; } + + [UsedImplicitly] + public int? NullableInteger { get; set; } + + [UsedImplicitly] + public string? String { get; set; } + + [UsedImplicitly] + public decimal Decimal { get; set; } + + [UsedImplicitly] + public decimal? NullableDecimal { get; set; } } private class ChildDto { - [UsedImplicitly] public int Integer { get; set; } - [UsedImplicitly] public int Version { get; set; } - [UsedImplicitly] public int? NullableInteger { get; set; } - [UsedImplicitly] public string? String { get; set; } - [UsedImplicitly] public decimal Decimal { get; set; } - [UsedImplicitly] public decimal? NullableDecimal { get; set; } + [UsedImplicitly] + public int Integer { get; set; } + + [UsedImplicitly] + public int Version { get; set; } + + [UsedImplicitly] + public int? NullableInteger { get; set; } + + [UsedImplicitly] + public string? String { get; set; } + + [UsedImplicitly] + public decimal Decimal { get; set; } + + [UsedImplicitly] + public decimal? NullableDecimal { get; set; } } public class OnlyDefinedPropertiesTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper) @@ -56,9 +102,11 @@ public void ConfigurationIsValid() var mapper = new MapperConfiguration( cfg => { - cfg.CreateMap() + cfg + .CreateMap() .ForMember(x => x.Version, x => x.Ignore()); - cfg.CreateMap() + cfg + .CreateMap() .ForMember(x => x.Version, x => x.Ignore()); cfg.OnlyDefinedProperties(); } @@ -112,14 +160,14 @@ public void MapOnlyPropertiesThatWereSetOnTheLeftHandSide() NullableInteger = 1337, Decimal = 13.37M, NullableDecimal = 13.37M, - String = "123" + String = "123", }; mapper.Map( new ParentModel { Decimal = 2.2M, - NullableInteger = 123 + NullableInteger = 123, }, destination ); @@ -151,14 +199,14 @@ public void MapOnlyPropertiesThatWereSetOnTheLeftHandSide_WithChildren() Decimal = 13.37M, NullableDecimal = 13.37M, String = "123", - Child = new ChildDto + Child = new() { Integer = 1337, NullableInteger = 1337, Decimal = 13.37M, NullableDecimal = 13.37M, - String = "123" - } + String = "123", + }, }; mapper.Map( @@ -166,11 +214,11 @@ public void MapOnlyPropertiesThatWereSetOnTheLeftHandSide_WithChildren() { Decimal = 2.2M, NullableInteger = 123, - Child = new ChildModel + Child = new() { NullableDecimal = 2.2M, - Integer = 123 - } + Integer = 123, + }, }, destination ); @@ -197,3 +245,81 @@ protected MyProfile() } } } + +public class AutoMapperConventionTests +{ + [Fact] + public async Task ShouldRegisterAutoMapperTypes() + { + var conventionBuilder = new ConventionContextBuilder(new Dictionary()) + .UseConventionFactory(Imports.Instance) + .Set(AssemblyLoadContext.Default); + var context = await ConventionContext.FromAsync(conventionBuilder); + var types = context + .AssemblyProvider.GetTypes( + x => x + .FromAssemblyDependenciesOf(typeof(IMapper)) + .GetTypes( + f => f.AssignableToAny( + typeof(IValueResolver<,,>), + typeof(IMemberValueResolver<,,,>), + typeof(ITypeConverter<,>), + typeof(IValueConverter<,>), + typeof(IMappingAction<,>) + ) + ) + ) + .ToArray(); + types.Should().NotBeEmpty(); + } + + private class Source + { + public string? Name { get; set; } + } + + private class Destination + { + public string? Name { get; set; } + } + + private class A : IValueResolver + { + public string Resolve(Source source, Destination destination, string destMember, ResolutionContext context) + { + throw new NotImplementedException(); + } + } + + private class B : IMemberValueResolver + { + public string Resolve(Source source, Destination destination, string sourceMember, string destMember, ResolutionContext context) + { + throw new NotImplementedException(); + } + } + + private class C : ITypeConverter + { + public Destination Convert(Source source, Destination destination, ResolutionContext context) + { + throw new NotImplementedException(); + } + } + + private class D : IValueConverter + { + public string Convert(string sourceMember, ResolutionContext context) + { + throw new NotImplementedException(); + } + } + + private class E : IMappingAction + { + public void Process(Source source, Destination destination, ResolutionContext context) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/DurationTests.cs b/test/Extensions.Tests/Mapping/DurationTests.cs index 7d9bba7f9..de10606ee 100644 --- a/test/Extensions.Tests/Mapping/DurationTests.cs +++ b/test/Extensions.Tests/Mapping/DurationTests.cs @@ -17,7 +17,7 @@ public void ValidateMapping() [Fact] public void CanConvertDurationToMinutes() { - var foo = new Foo1 { Bar = Duration.FromMinutes(300) }; + var foo = new Foo1 { Bar = Duration.FromMinutes(300), }; var o = Mapper.Map(foo); @@ -27,7 +27,7 @@ public void CanConvertDurationToMinutes() [Fact] public void CanConvertMinutesToDuration() { - var foo = new Foo7 { Bar = 300 }; + var foo = new Foo7 { Bar = 300, }; var o = Mapper.Map(foo); @@ -41,7 +41,7 @@ public void MapsFrom_TimeSpan() var foo = new Foo1 { - Bar = Duration.FromDays(1) + Bar = Duration.FromDays(1), }; var result = mapper.Map(foo).Bar; @@ -55,7 +55,7 @@ public void MapsTo_TimeSpan() var foo = new Foo3 { - Bar = TimeSpan.FromDays(1) + Bar = TimeSpan.FromDays(1), }; var result = mapper.Map(foo).Bar; @@ -69,7 +69,7 @@ public void MapsFrom_Int64() var foo = new Foo1 { - Bar = Duration.FromDays(1) + Bar = Duration.FromDays(1), }; var result = mapper.Map(foo).Bar; @@ -83,7 +83,7 @@ public void MapsTo_Int64() var foo = new Foo5 { - Bar = 10000L + Bar = 10000L, }; var result = mapper.Map(foo).Bar; @@ -97,7 +97,7 @@ public void MapsFrom_Int32() var foo = new Foo1 { - Bar = Duration.FromDays(1) + Bar = Duration.FromDays(1), }; var result = mapper.Map(foo).Bar; @@ -111,7 +111,7 @@ public void MapsTo_Int32() var foo = new Foo7 { - Bar = 10000 + Bar = 10000, }; var result = mapper.Map(foo).Bar; @@ -125,7 +125,7 @@ public void MapsFrom_Double() var foo = new Foo1 { - Bar = Duration.FromDays(1) + Bar = Duration.FromDays(1), }; var result = mapper.Map(foo).Bar; @@ -139,7 +139,7 @@ public void MapsTo_Double() var foo = new Foo8 { - Bar = 10000.1256d + Bar = 10000.1256d, }; var result = mapper.Map(foo).Bar; @@ -153,7 +153,7 @@ public void MapsFrom_Decimal() var foo = new Foo1 { - Bar = Duration.FromDays(1) + Bar = Duration.FromDays(1), }; var result = mapper.Map(foo).Bar; @@ -167,7 +167,7 @@ public void MapsTo_Decimal() var foo = new Foo9 { - Bar = 10000.125M + Bar = 10000.125M, }; var result = mapper.Map(foo).Bar; @@ -178,30 +178,25 @@ public void MapsTo_Decimal() [ClassData(typeof(TypeConverterData))] public void AutomatedTests(Type source, Type destination, object? sourceValue) { - var method = typeof(IMapperBase).GetMethods(BindingFlags.Public | BindingFlags.Instance) - .First( - x => x.ContainsGenericParameters && x.IsGenericMethodDefinition && - x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 && - x.GetParameters().Length == 1 - ); - var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue }); + var method = typeof(IMapperBase) + .GetMethods(BindingFlags.Public | BindingFlags.Instance) + .First( + x => x.ContainsGenericParameters + && x.IsGenericMethodDefinition + && x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 + && x.GetParameters().Length == 1 + ); + var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue, }); if (sourceValue == null) - { result.Should().BeNull(); - } else - { result.Should().BeOfType(Nullable.GetUnderlyingType(destination) ?? destination).And.NotBeNull(); - } } protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); expression.CreateMap().ReverseMap(); @@ -266,4 +261,4 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/InstantTests.cs b/test/Extensions.Tests/Mapping/InstantTests.cs index d52af5c47..a30671ccd 100644 --- a/test/Extensions.Tests/Mapping/InstantTests.cs +++ b/test/Extensions.Tests/Mapping/InstantTests.cs @@ -19,7 +19,7 @@ public void MapsFrom_DateTime() var foo = new Foo1 { - Bar = Instant.FromDateTimeOffset(DateTimeOffset.Now) + Bar = Instant.FromDateTimeOffset(DateTimeOffset.Now), }; var result = mapper.Map(foo).Bar; @@ -33,7 +33,7 @@ public void MapsTo_DateTime() var foo = new Foo3 { - Bar = DateTime.UtcNow + Bar = DateTime.UtcNow, }; var result = mapper.Map(foo).Bar; @@ -47,7 +47,7 @@ public void MapsFrom_DateTimeOffset() var foo = new Foo1 { - Bar = Instant.FromDateTimeOffset(DateTimeOffset.Now) + Bar = Instant.FromDateTimeOffset(DateTimeOffset.Now), }; var result = mapper.Map(foo).Bar; @@ -61,7 +61,7 @@ public void MapsTo_DateTimeOffset() var foo = new Foo5 { - Bar = DateTimeOffset.Now + Bar = DateTimeOffset.Now, }; var result = mapper.Map(foo).Bar; @@ -72,30 +72,25 @@ public void MapsTo_DateTimeOffset() [ClassData(typeof(TypeConverterData))] public void AutomatedTests(Type source, Type destination, object? sourceValue) { - var method = typeof(IMapperBase).GetMethods(BindingFlags.Public | BindingFlags.Instance) - .First( - x => x.ContainsGenericParameters && x.IsGenericMethodDefinition && - x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 && - x.GetParameters().Length == 1 - ); - var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue }); + var method = typeof(IMapperBase) + .GetMethods(BindingFlags.Public | BindingFlags.Instance) + .First( + x => x.ContainsGenericParameters + && x.IsGenericMethodDefinition + && x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 + && x.GetParameters().Length == 1 + ); + var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue, }); if (sourceValue == null) - { result.Should().BeNull(); - } else - { result.Should().BeOfType(Nullable.GetUnderlyingType(destination) ?? destination).And.NotBeNull(); - } } protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); expression.CreateMap().ReverseMap(); @@ -130,4 +125,4 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/LocalDateTests.cs b/test/Extensions.Tests/Mapping/LocalDateTests.cs index 3493fbf0a..61fab4057 100644 --- a/test/Extensions.Tests/Mapping/LocalDateTests.cs +++ b/test/Extensions.Tests/Mapping/LocalDateTests.cs @@ -19,7 +19,7 @@ public void MapsFrom() var foo = new Foo1 { - Bar = LocalDate.FromDateTime(DateTime.Now) + Bar = LocalDate.FromDateTime(DateTime.Now), }; var result = mapper.Map(foo).Bar; @@ -33,7 +33,7 @@ public void MapsTo() var foo = new Foo3 { - Bar = DateTime.Now + Bar = DateTime.Now, }; var result = mapper.Map(foo).Bar; @@ -44,30 +44,25 @@ public void MapsTo() [ClassData(typeof(TypeConverterData))] public void AutomatedTests(Type source, Type destination, object? sourceValue) { - var method = typeof(IMapperBase).GetMethods(BindingFlags.Public | BindingFlags.Instance) - .First( - x => x.ContainsGenericParameters && x.IsGenericMethodDefinition && - x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 && - x.GetParameters().Length == 1 - ); - var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue }); + var method = typeof(IMapperBase) + .GetMethods(BindingFlags.Public | BindingFlags.Instance) + .First( + x => x.ContainsGenericParameters + && x.IsGenericMethodDefinition + && x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 + && x.GetParameters().Length == 1 + ); + var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue, }); if (sourceValue == null) - { result.Should().BeNull(); - } else - { result.Should().BeOfType(Nullable.GetUnderlyingType(destination) ?? destination).And.NotBeNull(); - } } protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); } @@ -90,12 +85,12 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); -#if NET6_0_OR_GREATER + #if NET6_0_OR_GREATER yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); -#endif + #endif } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs b/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs index b07637d8d..fb6673d98 100644 --- a/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs +++ b/test/Extensions.Tests/Mapping/LocalDateTimeTests.cs @@ -21,7 +21,7 @@ public void MapsFrom() var foo = new Foo1 { - Bar = LocalDateTime.FromDateTime(DateTime.Now) + Bar = LocalDateTime.FromDateTime(DateTime.Now), }; var result = mapper.Map(foo).Bar; @@ -35,7 +35,7 @@ public void MapsTo() var foo = new Foo3 { - Bar = DateTime.Now + Bar = DateTime.Now, }; var result = mapper.Map(foo).Bar; @@ -46,30 +46,25 @@ public void MapsTo() [ClassData(typeof(TypeConverterData))] public void AutomatedTests(Type source, Type destination, object? sourceValue) { - var method = typeof(IMapperBase).GetMethods(BindingFlags.Public | BindingFlags.Instance) - .First( - x => x.ContainsGenericParameters && x.IsGenericMethodDefinition && - x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 && - x.GetParameters().Length == 1 - ); - var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue }); + var method = typeof(IMapperBase) + .GetMethods(BindingFlags.Public | BindingFlags.Instance) + .First( + x => x.ContainsGenericParameters + && x.IsGenericMethodDefinition + && x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 + && x.GetParameters().Length == 1 + ); + var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue, }); if (sourceValue == null) - { result.Should().BeNull(); - } else - { result.Should().BeOfType(Nullable.GetUnderlyingType(destination) ?? destination).And.NotBeNull(); - } } protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); } @@ -94,4 +89,4 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/LocalTimeTests.cs b/test/Extensions.Tests/Mapping/LocalTimeTests.cs index a9cf28dc6..78b1f85b2 100644 --- a/test/Extensions.Tests/Mapping/LocalTimeTests.cs +++ b/test/Extensions.Tests/Mapping/LocalTimeTests.cs @@ -22,11 +22,11 @@ public void MapsFrom_DateTime() var foo = new Foo1 { - Bar = LocalTime.FromTicksSinceMidnight(10000) + Bar = LocalTime.FromTicksSinceMidnight(10000), }; var result = mapper.Map(foo).Bar; - result.Should().Be(new TimeSpan(foo.Bar.TickOfDay)); + result.Should().Be(new(foo.Bar.TickOfDay)); } [Fact] @@ -36,46 +36,41 @@ public void MapsTo_DateTime() var foo = new Foo3 { - Bar = TimeSpan.FromMinutes(502) + Bar = TimeSpan.FromMinutes(502), }; var result = mapper.Map(foo).Bar; - result.Should().Be(new LocalTime(502 / 60, 502 % 60)); + result.Should().Be(new(502 / 60, 502 % 60)); } [Theory] [ClassData(typeof(TypeConverterData))] public void AutomatedTests(Type source, Type destination, object? sourceValue) { - var method = typeof(IMapperBase).GetMethods(BindingFlags.Public | BindingFlags.Instance) - .First( - x => x.ContainsGenericParameters && x.IsGenericMethodDefinition && - x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 && - x.GetParameters().Length == 1 - ); - var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue }); + var method = typeof(IMapperBase) + .GetMethods(BindingFlags.Public | BindingFlags.Instance) + .First( + x => x.ContainsGenericParameters + && x.IsGenericMethodDefinition + && x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 + && x.GetParameters().Length == 1 + ); + var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue, }); if (sourceValue == null) - { result.Should().BeNull(); - } else - { result.Should().BeOfType(Nullable.GetUnderlyingType(destination) ?? destination).And.NotBeNull(); - } } protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); -#if NET6_0_OR_GREATER + #if NET6_0_OR_GREATER expression.CreateMap().ReverseMap(); -#endif + #endif } private class Foo1 @@ -88,12 +83,12 @@ private class Foo3 public TimeSpan Bar { get; set; } } -#if NET6_0_OR_GREATER + #if NET6_0_OR_GREATER private class Foo5 { public TimeOnly Bar { get; set; } } -#endif + #endif public class Converters : TypeConverterFactory { @@ -103,16 +98,16 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); -#if NET6_0_OR_GREATER + #if NET6_0_OR_GREATER yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); yield return typeof(ITypeConverter); -#endif + #endif } } -#if NET6_0_OR_GREATER + #if NET6_0_OR_GREATER [Fact] public void MapsFrom_DateTimeOffset() { @@ -120,7 +115,7 @@ public void MapsFrom_DateTimeOffset() var foo = new Foo1 { - Bar = LocalTime.FromTicksSinceMidnight(10000) + Bar = LocalTime.FromTicksSinceMidnight(10000), }; var result = mapper.Map(foo).Bar; @@ -134,11 +129,11 @@ public void MapsTo_DateTimeOffset() var foo = new Foo5 { - Bar = TimeOnly.FromDateTime(DateTime.Now) + Bar = TimeOnly.FromDateTime(DateTime.Now), }; var result = mapper.Map(foo).Bar; result.Should().Be(foo.Bar.ToLocalTime()); } -#endif -} + #endif +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs b/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs index 439155e21..40c81ab83 100644 --- a/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs +++ b/test/Extensions.Tests/Mapping/OffsetDateTimeTests.cs @@ -19,7 +19,7 @@ public void MapsFrom() var foo = new Foo1 { - Bar = OffsetDateTime.FromDateTimeOffset(DateTimeOffset.Now) + Bar = OffsetDateTime.FromDateTimeOffset(DateTimeOffset.Now), }; var result = mapper.Map(foo).Bar; @@ -33,7 +33,7 @@ public void MapsTo() var foo = new Foo3 { - Bar = DateTimeOffset.Now + Bar = DateTimeOffset.Now, }; var result = mapper.Map(foo).Bar; @@ -44,30 +44,25 @@ public void MapsTo() [ClassData(typeof(TypeConverterData))] public void AutomatedTests(Type source, Type destination, object? sourceValue) { - var method = typeof(IMapperBase).GetMethods(BindingFlags.Public | BindingFlags.Instance) - .First( - x => x.ContainsGenericParameters && x.IsGenericMethodDefinition && - x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 && - x.GetParameters().Length == 1 - ); - var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue }); + var method = typeof(IMapperBase) + .GetMethods(BindingFlags.Public | BindingFlags.Instance) + .First( + x => x.ContainsGenericParameters + && x.IsGenericMethodDefinition + && x.GetGenericMethodDefinition().GetGenericArguments().Length == 2 + && x.GetParameters().Length == 1 + ); + var result = method.MakeGenericMethod(source, destination).Invoke(Mapper, new[] { sourceValue, }); if (sourceValue == null) - { result.Should().BeNull(); - } else - { result.Should().BeOfType(Nullable.GetUnderlyingType(destination) ?? destination).And.NotBeNull(); - } } protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); } @@ -92,4 +87,4 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/OffsetTests.cs b/test/Extensions.Tests/Mapping/OffsetTests.cs index 8f33dfdc7..ab140787e 100644 --- a/test/Extensions.Tests/Mapping/OffsetTests.cs +++ b/test/Extensions.Tests/Mapping/OffsetTests.cs @@ -18,7 +18,7 @@ public void MapsFrom() var foo = new Foo1 { - Bar = Offset.FromHours(11) + Bar = Offset.FromHours(11), }; var result = mapper.Map(foo).Bar; @@ -32,7 +32,7 @@ public void MapsTo() var foo = new Foo3 { - Bar = TimeSpan.FromHours(10) + Bar = TimeSpan.FromHours(10), }; var result = mapper.Map(foo).Bar; @@ -41,10 +41,7 @@ public void MapsTo() protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); } @@ -69,4 +66,4 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/PeriodTests.cs b/test/Extensions.Tests/Mapping/PeriodTests.cs index dde22ef02..f3ff07a20 100644 --- a/test/Extensions.Tests/Mapping/PeriodTests.cs +++ b/test/Extensions.Tests/Mapping/PeriodTests.cs @@ -19,7 +19,7 @@ public void MapsFrom() var foo = new Foo1 { - Bar = Period.FromMonths(10) + Bar = Period.FromMonths(10), }; var result = mapper.Map(foo).Bar; @@ -33,7 +33,7 @@ public void MapsTo() var foo = new Foo3 { - Bar = "P5M" + Bar = "P5M", }; var result = mapper.Map(foo).Bar; @@ -42,10 +42,7 @@ public void MapsTo() protected override void Configure(IMapperConfigurationExpression expression) { - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + ArgumentNullException.ThrowIfNull(expression); expression.CreateMap().ReverseMap(); } @@ -68,4 +65,4 @@ public override IEnumerable GetTypeConverters() yield return typeof(ITypeConverter); } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Mapping/TypeConverterTest.cs b/test/Extensions.Tests/Mapping/TypeConverterTest.cs index 1eb8fc75e..33c1a600f 100644 --- a/test/Extensions.Tests/Mapping/TypeConverterTest.cs +++ b/test/Extensions.Tests/Mapping/TypeConverterTest.cs @@ -37,96 +37,42 @@ internal abstract class TypeConverterData : TheoryData private static object GetRandomValue(Type type) { type = Nullable.GetUnderlyingType(type) ?? type; - if (type == typeof(int)) - { - return Faker.Random.Int(); - } + if (type == typeof(int)) return Faker.Random.Int(); - if (type == typeof(long)) - { - return Faker.Random.Long(); - } + if (type == typeof(long)) return Faker.Random.Long(); - if (type == typeof(short)) - { - return Faker.Random.Short(); - } + if (type == typeof(short)) return Faker.Random.Short(); - if (type == typeof(float)) - { - return Faker.Random.Float(); - } + if (type == typeof(float)) return Faker.Random.Float(); - if (type == typeof(double)) - { - return Faker.Random.Double(); - } + if (type == typeof(double)) return Faker.Random.Double(); - if (type == typeof(decimal)) - { - return Faker.Random.Decimal(); - } + if (type == typeof(decimal)) return Faker.Random.Decimal(); - if (type == typeof(Duration)) - { - return Duration.FromTimeSpan(Faker.Date.Timespan()); - } + if (type == typeof(Duration)) return Duration.FromTimeSpan(Faker.Date.Timespan()); - if (type == typeof(TimeSpan)) - { - return Faker.Date.Timespan(TimeSpan.FromDays(1)); - } + if (type == typeof(TimeSpan)) return Faker.Date.Timespan(TimeSpan.FromDays(1)); - if (type == typeof(Instant)) - { - return Instant.FromDateTimeOffset(Faker.Date.RecentOffset()); - } + if (type == typeof(Instant)) return Instant.FromDateTimeOffset(Faker.Date.RecentOffset()); - if (type == typeof(LocalDateTime)) - { - return LocalDateTime.FromDateTime(Faker.Date.Recent()); - } + if (type == typeof(LocalDateTime)) return LocalDateTime.FromDateTime(Faker.Date.Recent()); - if (type == typeof(OffsetDateTime)) - { - return OffsetDateTime.FromDateTimeOffset(Faker.Date.RecentOffset()); - } + if (type == typeof(OffsetDateTime)) return OffsetDateTime.FromDateTimeOffset(Faker.Date.RecentOffset()); - if (type == typeof(LocalTime)) - { - return LocalTime.FromTicksSinceMidnight(Faker.Date.Timespan(TimeSpan.FromDays(1)).Ticks); - } + if (type == typeof(LocalTime)) return LocalTime.FromTicksSinceMidnight(Faker.Date.Timespan(TimeSpan.FromDays(1)).Ticks); - if (type == typeof(LocalDate)) - { - return LocalDate.FromDateTime(Faker.Date.Recent()); - } + if (type == typeof(LocalDate)) return LocalDate.FromDateTime(Faker.Date.Recent()); - if (type == typeof(Offset)) - { - return Offset.FromTimeSpan(Faker.Date.Timespan(TimeSpan.FromHours(12))); - } + if (type == typeof(Offset)) return Offset.FromTimeSpan(Faker.Date.Timespan(TimeSpan.FromHours(12))); - if (type == typeof(DateTime)) - { - return Faker.Date.Recent(); - } + if (type == typeof(DateTime)) return Faker.Date.Recent(); - if (type == typeof(DateTimeOffset)) - { - return Faker.Date.RecentOffset(); - } -#if NET6_0_OR_GREATER - if (type == typeof(DateOnly)) - { - return Faker.Date.RecentDateOnly(); - } + if (type == typeof(DateTimeOffset)) return Faker.Date.RecentOffset(); + #if NET6_0_OR_GREATER + if (type == typeof(DateOnly)) return Faker.Date.RecentDateOnly(); - if (type == typeof(TimeOnly)) - { - return Faker.Date.RecentTimeOnly(); - } -#endif + if (type == typeof(TimeOnly)) return Faker.Date.RecentTimeOnly(); + #endif throw new NotSupportedException($"type {type.FullName} is not supported"); } @@ -135,7 +81,7 @@ protected TypeConverterData(Func> typeConverterFactory) { static (Type source, Type sourceClass, Type destination, Type destinationClass) GetWrappedClasses((Type source, Type destination) item) { - var (source, destination) = item; + ( var source, var destination ) = item; var sourceFoo = typeof(Foo<>).MakeGenericType(source); var destinationFoo = typeof(Foo<>).MakeGenericType(destination); return ( source, sourceFoo, destination, destinationFoo ); @@ -143,27 +89,25 @@ protected TypeConverterData(Func> typeConverterFactory) static object CreateValue(Type type, object value) { - return typeof(Foo).GetMethod(nameof(Foo.Create))!.MakeGenericMethod(type).Invoke(null, new[] { value })!; + return typeof(Foo).GetMethod(nameof(Foo.Create))!.MakeGenericMethod(type).Invoke(null, new[] { value, })!; } - foreach (var (source, sourceClass, _, destinationClass) in GetValueTypePairs(typeConverterFactory()) - .SelectMany( - item => new[] - { - item, - ( typeof(Nullable<>).MakeGenericType(item.source), - typeof(Nullable<>).MakeGenericType(item.destination) ), - ( item.source, typeof(Nullable<>).MakeGenericType(item.destination) ) - } - ).Select(GetWrappedClasses)) + foreach (( var source, var sourceClass, _, var destinationClass ) in GetValueTypePairs(typeConverterFactory()) + .SelectMany( + item => new[] + { + item, + ( typeof(Nullable<>).MakeGenericType(item.source), + typeof(Nullable<>).MakeGenericType(item.destination) ), + ( item.source, typeof(Nullable<>).MakeGenericType(item.destination) ), + } + ) + .Select(GetWrappedClasses)) { var sourceValue = CreateValue(source, GetRandomValue(source)); Add(sourceClass, destinationClass, sourceValue); - if (Nullable.GetUnderlyingType(source) == null) - { - continue; - } + if (Nullable.GetUnderlyingType(source) == null) continue; foreach (var item in Faker.Make(3, () => CreateValue(source, GetRandomValue(source).OrNull(Faker)))) { @@ -177,7 +121,7 @@ public abstract class TypeConverterTest : AutoFakeTest { protected TypeConverterTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper, LogEventLevel.Debug) { - Config = new MapperConfiguration( + Config = new( x => { x.AddProfile(); @@ -199,19 +143,21 @@ public abstract class TypeConverterTest : AutoFakeTest // TODO: Refactor this to forward parent class constructor values protected TypeConverterTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper, LogEventLevel.Debug) { - Config = new MapperConfiguration( + Config = new( x => { x.AddProfile(); - foreach (var (source, destination) in TypeConverterData.GetValueTypePairs(new T().GetTypeConverters()).SelectMany( - item => new[] - { - item, - ( typeof(Nullable<>).MakeGenericType(item.source), - typeof(Nullable<>).MakeGenericType(item.destination) ), - ( item.source, typeof(Nullable<>).MakeGenericType(item.destination) ) - } - )) + foreach (( var source, var destination ) in TypeConverterData + .GetValueTypePairs(new T().GetTypeConverters()) + .SelectMany( + item => new[] + { + item, + ( typeof(Nullable<>).MakeGenericType(item.source), + typeof(Nullable<>).MakeGenericType(item.destination) ), + ( item.source, typeof(Nullable<>).MakeGenericType(item.destination) ), + } + )) { x.CreateMap(typeof(Foo<>).MakeGenericType(source), typeof(Foo<>).MakeGenericType(destination)); } @@ -227,4 +173,4 @@ protected TypeConverterTest(ITestOutputHelper testOutputHelper) : base(testOutpu protected MapperConfiguration Config { get; } protected abstract void Configure(IMapperConfigurationExpression expression); -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/MediatRTests.cs b/test/Extensions.Tests/MediatRTests.cs index 5e94fb707..91713c297 100644 --- a/test/Extensions.Tests/MediatRTests.cs +++ b/test/Extensions.Tests/MediatRTests.cs @@ -6,7 +6,6 @@ using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.Reflection; using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.Foundation; using Rocket.Surgery.LaunchPad.Foundation.Conventions; namespace Extensions.Tests; @@ -16,11 +15,11 @@ public class MediatRTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputH [Fact] public async Task Test1() { -#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. + #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. + #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 context = await ConventionContext.FromAsync(builder); var services = new ServiceCollection(); new MediatRConvention().Register(context, new ConfigurationBuilder().Build(), services); @@ -35,23 +34,24 @@ public async Task Test1() await mediator.Send(new Request()); - A.CallTo(() => sub.Handle(A._, A>._, A._)) - .MustHaveHappenedOnceExactly(); + A + .CallTo(() => sub.Handle(A._, A>._, A._)) + .MustHaveHappenedOnceExactly(); } [Fact] public async Task Test2() { -#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. + #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. + #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 context = await ConventionContext.FromAsync(builder); var services = new ServiceCollection(); new MediatRConvention( - new FoundationOptions + new() { - MediatorLifetime = ServiceLifetime.Singleton + MediatorLifetime = ServiceLifetime.Singleton, } ).Register(context, new ConfigurationBuilder().Build(), services); @@ -59,9 +59,11 @@ public async Task Test2() services.AddSingleton(sub); - services.Should().Contain( - x => x.ServiceType == typeof(IMediator) && x.Lifetime == ServiceLifetime.Singleton - ); + services + .Should() + .Contain( + x => x.ServiceType == typeof(IMediator) && x.Lifetime == ServiceLifetime.Singleton + ); var r = services.BuildServiceProvider(); @@ -69,8 +71,9 @@ public async Task Test2() await mediator.Send(new Request()); - A.CallTo(() => sub.Handle(A._, A>._, A._)) - .MustHaveHappenedOnceExactly(); + A + .CallTo(() => sub.Handle(A._, A>._, A._)) + .MustHaveHappenedOnceExactly(); } private class TestAssemblyProvider : IAssemblyProvider @@ -80,21 +83,33 @@ public IEnumerable GetAssemblies() return new[] { typeof(TestAssemblyProvider).GetTypeInfo().Assembly, - typeof(MediatRConvention).GetTypeInfo().Assembly + typeof(MediatRConvention).GetTypeInfo().Assembly, }; } - } - private class TestAssemblyCandidateFinder : IAssemblyCandidateFinder - { - public IEnumerable GetCandidateAssemblies(IEnumerable candidates) + public IEnumerable GetAssemblies( + Action action, + string filePath = "", + string memberName = "", + int lineNumber = 0 + ) { return new[] { typeof(TestAssemblyProvider).GetTypeInfo().Assembly, - typeof(MediatRConvention).GetTypeInfo().Assembly + typeof(MediatRConvention).GetTypeInfo().Assembly, }; } + + public IEnumerable GetTypes( + Func> selector, + string filePath = "", + string memberName = "", + int lineNumber = 0 + ) + { + return Enumerable.Empty(); + } } public class Request : IRequest; @@ -106,4 +121,4 @@ public Task Handle(Request message, CancellationToken token) return Task.FromResult(Unit.Value); } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/StringInValidatorTests.cs b/test/Extensions.Tests/StringInValidatorTests.cs index 006c6a56f..6bda48b1f 100644 --- a/test/Extensions.Tests/StringInValidatorTests.cs +++ b/test/Extensions.Tests/StringInValidatorTests.cs @@ -8,20 +8,20 @@ public class StringInValidatorTests(ITestOutputHelper testOutputHelper) : Conven [Fact] public async Task Should_Validate_Invalid() { - Init(); + await Init(); var data = new Target { Type = "NotTruck", - TypeIgnoreCase = "nottruck" + TypeIgnoreCase = "nottruck", }; var validator = ServiceProvider.GetRequiredService>(); var result = await validator.ValidateAsync(data); -#pragma warning disable CA1849 + #pragma warning disable CA1849 // ReSharper disable once MethodHasAsyncOverload var result2 = validator.Validate(data); -#pragma warning restore CA1849 + #pragma warning restore CA1849 result.Should().BeEquivalentTo(result2); result.IsValid.Should().BeFalse(); @@ -32,20 +32,20 @@ public async Task Should_Validate_Invalid() [Fact] public async Task Should_Validate_CaseSensitive() { - Init(); + await Init(); var data = new Target { Type = "truck", - TypeIgnoreCase = "truck" + TypeIgnoreCase = "truck", }; var validator = ServiceProvider.GetRequiredService>(); var result = await validator.ValidateAsync(data); -#pragma warning disable CA1849 + #pragma warning disable CA1849 // ReSharper disable once MethodHasAsyncOverload var result2 = validator.Validate(data); -#pragma warning restore CA1849 + #pragma warning restore CA1849 result.Should().BeEquivalentTo(result2); result.IsValid.Should().BeFalse(); @@ -55,20 +55,20 @@ public async Task Should_Validate_CaseSensitive() [Fact] public async Task Should_Validate_CaseInsensitive() { - Init(); + await Init(); var data = new Target { Type = "Truck", - TypeIgnoreCase = "nottruck" + TypeIgnoreCase = "nottruck", }; var validator = ServiceProvider.GetRequiredService>(); var result = await validator.ValidateAsync(data); -#pragma warning disable CA1849 + #pragma warning disable CA1849 // ReSharper disable once MethodHasAsyncOverload var result2 = validator.Validate(data); -#pragma warning restore CA1849 + #pragma warning restore CA1849 result.Should().BeEquivalentTo(result2); result.IsValid.Should().BeFalse(); @@ -77,8 +77,11 @@ public async Task Should_Validate_CaseInsensitive() private class Target { - [UsedImplicitly] public string Type { get; set; } = null!; - [UsedImplicitly] public string TypeIgnoreCase { get; set; } = null!; + [UsedImplicitly] + public string Type { get; set; } = null!; + + [UsedImplicitly] + public string TypeIgnoreCase { get; set; } = null!; [UsedImplicitly] private class Validator : AbstractValidator @@ -92,4 +95,4 @@ public Validator() } } } -} +} \ No newline at end of file diff --git a/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs b/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs index baa2fb010..203252675 100644 --- a/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs +++ b/test/Extensions.Tests/Validation/HealthCheckOptionsValidationTests.cs @@ -2,7 +2,6 @@ using DryIoc; using FluentValidation; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.Options; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.Testing; @@ -142,11 +141,11 @@ public Validator() } } - public Task InitializeAsync() + public async Task InitializeAsync() { var conventionContextBuilder = ConventionContextBuilder .Create() - .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) + .ForTesting(Imports.Instance, LoggerFactory) .Set( new FoundationOptions { @@ -155,10 +154,8 @@ public Task InitializeAsync() ) .WithLogger(Logger); - var context = ConventionContext.From(conventionContextBuilder); - Populate(new ServiceCollection().ApplyConventions(context)); - - return Task.CompletedTask; + var context = await ConventionContext.FromAsync(conventionContextBuilder); + Populate(await new ServiceCollection().ApplyConventionsAsync(context)); } public Task DisposeAsync() diff --git a/test/Extensions.Tests/Validation/OptionsValidationTests.cs b/test/Extensions.Tests/Validation/OptionsValidationTests.cs index 8fbfcaa83..1fa4eb037 100644 --- a/test/Extensions.Tests/Validation/OptionsValidationTests.cs +++ b/test/Extensions.Tests/Validation/OptionsValidationTests.cs @@ -1,8 +1,8 @@ #if NET6_0_OR_GREATER +using System.Runtime.Loader; using DryIoc; using FluentValidation; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.Options; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.Testing; @@ -88,11 +88,12 @@ public Validator() } } - public Task InitializeAsync() + public async Task InitializeAsync() { var conventionContextBuilder = ConventionContextBuilder .Create() - .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) + .ForTesting(Imports.Instance, LoggerFactory) + .Set(AssemblyLoadContext.Default) .Set( new FoundationOptions { @@ -101,10 +102,8 @@ public Task InitializeAsync() ) .WithLogger(Logger); - var context = ConventionContext.From(conventionContextBuilder); - Populate(new ServiceCollection().ApplyConventions(context)); - - return Task.CompletedTask; + var context = await ConventionContext.FromAsync(conventionContextBuilder); + Populate(await new ServiceCollection().ApplyConventionsAsync(context)); } public Task DisposeAsync() diff --git a/test/Functions.Tests/Functions.Tests.csproj b/test/Functions.Tests/Functions.Tests.csproj deleted file mode 100644 index e8aab044b..000000000 --- a/test/Functions.Tests/Functions.Tests.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - net8.0 - - - - - - diff --git a/test/Functions.Tests/RocketHostBuilderTests.cs b/test/Functions.Tests/RocketHostBuilderTests.cs deleted file mode 100644 index a1e6c1960..000000000 --- a/test/Functions.Tests/RocketHostBuilderTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -using FakeItEasy; -using Microsoft.Azure.Functions.Extensions.DependencyInjection; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.Conventions.DependencyInjection; -using Rocket.Surgery.Extensions.Testing; -using Rocket.Surgery.LaunchPad.Functions; - -namespace Functions.Tests; - -internal sealed class Startup : LaunchPadFunctionStartup, IServiceConvention -{ - public Startup() - { - } - - public Startup(Func configure) : base(configure) - { - } - - public override void Configure(IFunctionsHostBuilder builder, IConventionContext context) - { - } - - public void Register(IConventionContext context, IConfiguration configuration, IServiceCollection services) - { - services.AddSingleton(new object()); - } -} - -public class RocketHostBuilderTests(ITestOutputHelper outputHelper) : AutoFakeTest(outputHelper) -{ - [Fact] - public void Should_UseAssemblies() - { - var startup = new Startup(RocketBooster.ForAssemblies(AppDomain.CurrentDomain.GetAssemblies())); - var configBuilder = new ConfigurationBuilder(); - var functionsConfigurationBuilder = ConfigureConfiguration(configBuilder); - var functionsHostBuilder = ConfigureHost(); - startup.ConfigureAppConfiguration(functionsConfigurationBuilder); - var services = new ServiceCollection(); - startup.Configure(functionsHostBuilder); - - var sp = services.BuildServiceProvider(); - sp.Should().NotBeNull(); - } - - [Fact] - public void Should_UseRocketBooster() - { - var startup = new Startup(RocketBooster.ForAssemblies(AppDomain.CurrentDomain.GetAssemblies())); - var configBuilder = new ConfigurationBuilder(); - var functionsConfigurationBuilder = ConfigureConfiguration(configBuilder); - var functionsHostBuilder = ConfigureHost(); - startup.ConfigureAppConfiguration(functionsConfigurationBuilder); - var services = new ServiceCollection(); - startup.Configure(functionsHostBuilder); - - var sp = services.BuildServiceProvider(); - sp.Should().NotBeNull(); - } - - [Fact] - public void Should_Build_The_Host_Correctly() - { - var startup = new Startup(RocketBooster.ForAssemblies(AppDomain.CurrentDomain.GetAssemblies())); - var configBuilder = new ConfigurationBuilder(); - var functionsConfigurationBuilder = ConfigureConfiguration(configBuilder); - var functionsHostBuilder = ConfigureHost(); - startup.ConfigureAppConfiguration(functionsConfigurationBuilder); - var services = new ServiceCollection(); - startup.Configure(functionsHostBuilder); - - var sp = services.BuildServiceProvider(); - sp.Should().NotBeNull(); - } - - private static IFunctionsConfigurationBuilder ConfigureConfiguration(IConfigurationBuilder configurationBuilder) - { - var functionsConfigurationBuilder = A.Fake(); - A.CallTo(() => functionsConfigurationBuilder.ConfigurationBuilder).Returns(configurationBuilder); - return functionsConfigurationBuilder; - } - - private static IFunctionsHostBuilder ConfigureHost() - { - var functionsHostBuilder = A.Fake(); - return functionsHostBuilder; - } -} diff --git a/test/Functions.Tests/TestAssemblyProvider.cs b/test/Functions.Tests/TestAssemblyProvider.cs deleted file mode 100644 index b2f178752..000000000 --- a/test/Functions.Tests/TestAssemblyProvider.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Reflection; -using Rocket.Surgery.Conventions.Reflection; -using Rocket.Surgery.LaunchPad.Functions; - -namespace Functions.Tests; - -internal sealed class TestAssemblyProvider : IAssemblyProvider -{ - public IEnumerable GetAssemblies() - { - return new[] - { - typeof(LaunchPadFunctionStartup).GetTypeInfo().Assembly, - typeof(TestAssemblyProvider).GetTypeInfo().Assembly - }; - } -} diff --git a/test/Metadata.Tests/Metadata.Tests.csproj b/test/Metadata.Tests/Metadata.Tests.csproj index 111fcd5d4..7da054fed 100644 --- a/test/Metadata.Tests/Metadata.Tests.csproj +++ b/test/Metadata.Tests/Metadata.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs b/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs index 9ea895f6f..61452d786 100644 --- a/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.BlazorServer.Tests/Helpers/SqliteExtension.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Rocket.Surgery.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.BlazorServer.Tests.Helpers; @@ -15,14 +16,14 @@ public void Reset(IServiceProvider serviceProvider) { _connection.Close(); _connection.Open(); - serviceProvider.GetRequiredService().Database.EnsureCreated(); + serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreated()); } public async Task ResetAsync(IServiceProvider serviceProvider) { await _connection.CloseAsync(); await _connection.OpenAsync(); - await serviceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + await serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreatedAsync()); } public void Dispose() diff --git a/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs index 8fe8ca992..cf280153b 100644 --- a/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.BlazorServer.Tests/Helpers/TestWebAppFixture.cs @@ -3,4 +3,4 @@ namespace Sample.BlazorServer.Tests.Helpers; -public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; \ No newline at end of file diff --git a/test/Sample.BlazorServer.Tests/Sample.BlazorServer.Tests.csproj b/test/Sample.BlazorServer.Tests/Sample.BlazorServer.Tests.csproj index 023a48adc..9f704ccc9 100644 --- a/test/Sample.BlazorServer.Tests/Sample.BlazorServer.Tests.csproj +++ b/test/Sample.BlazorServer.Tests/Sample.BlazorServer.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.BlazorWasm.Tests/HandleTestHostBase.cs b/test/Sample.BlazorWasm.Tests/HandleTestHostBase.cs index 629d0d196..217487ccf 100644 --- a/test/Sample.BlazorWasm.Tests/HandleTestHostBase.cs +++ b/test/Sample.BlazorWasm.Tests/HandleTestHostBase.cs @@ -7,24 +7,30 @@ namespace Sample.BlazorWasm.Tests; -public abstract class HandleTestHostBase : AutoFakeTest +public abstract class HandleTestHostBase(ITestOutputHelper outputHelper, LogLevel logLevel = LogLevel.Information) : AutoFakeTest( + outputHelper, + logLevel, + "[{Timestamp:HH:mm:ss} {Level:w4}] {Message} <{SourceContext}>{NewLine}{Exception}" +), IAsyncLifetime { - private readonly IConventionContext _hostBuilder; + private IConventionContext _hostBuilder = null!; - protected HandleTestHostBase(ITestOutputHelper outputHelper, LogLevel logLevel = LogLevel.Information) : base( - outputHelper, - logLevel, - "[{Timestamp:HH:mm:ss} {Level:w4}] {Message} <{SourceContext}>{NewLine}{Exception}" - ) + public async Task InitializeAsync() { _hostBuilder = - ConventionContext.From( - ConventionContextBuilder.Create() - .ForTesting(AppDomain.CurrentDomain, LoggerFactory) - .WithLogger(Logger) + await ConventionContext.FromAsync( + ConventionContextBuilder + .Create() + .ForTesting(AppDomain.CurrentDomain, LoggerFactory) + .WithLogger(Logger) ); ExcludeSourceContext(nameof(WebAssemblyHostBuilder)); ExcludeSourceContext(nameof(WebAssemblyHost)); - Populate(new ServiceCollection().ApplyConventions(_hostBuilder)); + Populate(await new ServiceCollection().ApplyConventionsAsync(_hostBuilder)); } -} + + public Task DisposeAsync() + { + return Task.CompletedTask; + } +} \ No newline at end of file diff --git a/test/Sample.Classic.Restful.Tests/Helpers/SqliteExtension.cs b/test/Sample.Classic.Restful.Tests/Helpers/SqliteExtension.cs index 9ac684865..684517f6d 100644 --- a/test/Sample.Classic.Restful.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.Classic.Restful.Tests/Helpers/SqliteExtension.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Rocket.Surgery.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Classic.Restful.Tests.Helpers; @@ -13,21 +14,21 @@ public sealed class SqliteExtension : IResettableAlbaExtension where public SqliteExtension() { - _connection = new SqliteConnection("DataSource=:memory:"); + _connection = new("DataSource=:memory:"); } public void Reset(IServiceProvider serviceProvider) { _connection.Close(); _connection.Open(); - serviceProvider.GetRequiredService().Database.EnsureCreated(); + serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreated()); } public async Task ResetAsync(IServiceProvider serviceProvider) { await _connection.CloseAsync(); await _connection.OpenAsync(); - await serviceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + await serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreatedAsync()); } public void Dispose() diff --git a/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs index ebadef84d..b42896ecb 100644 --- a/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.Classic.Restful.Tests/Helpers/TestWebAppFixture.cs @@ -3,4 +3,4 @@ namespace Sample.Classic.Restful.Tests.Helpers; -public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; \ No newline at end of file diff --git a/test/Sample.Classic.Restful.Tests/Sample.Classic.Restful.Tests.csproj b/test/Sample.Classic.Restful.Tests/Sample.Classic.Restful.Tests.csproj index 458084285..afe297663 100644 --- a/test/Sample.Classic.Restful.Tests/Sample.Classic.Restful.Tests.csproj +++ b/test/Sample.Classic.Restful.Tests/Sample.Classic.Restful.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.Command.Tests/Sample.Command.Tests.csproj b/test/Sample.Command.Tests/Sample.Command.Tests.csproj index 349cd27f5..77972d30a 100644 --- a/test/Sample.Command.Tests/Sample.Command.Tests.csproj +++ b/test/Sample.Command.Tests/Sample.Command.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.Core.Tests/HandleTestHostBase.cs b/test/Sample.Core.Tests/HandleTestHostBase.cs index b3e9c738d..cf681380b 100644 --- a/test/Sample.Core.Tests/HandleTestHostBase.cs +++ b/test/Sample.Core.Tests/HandleTestHostBase.cs @@ -1,7 +1,7 @@ -using Microsoft.Data.Sqlite; +using System.Runtime.Loader; +using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.Logging; using Rocket.Surgery.Conventions; using Rocket.Surgery.Conventions.Testing; @@ -23,15 +23,17 @@ protected HandleTestHostBase(ITestOutputHelper outputHelper, LogLevel logLevel = ) { _context = - ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) - .WithLogger(LoggerFactory.CreateLogger(nameof(AutoFakeTest))); + ConventionContextBuilder + .Create() + .ForTesting(Imports.Instance, LoggerFactory) + .Set(AssemblyLoadContext.Default) + .WithLogger(LoggerFactory.CreateLogger(nameof(AutoFakeTest))); ExcludeSourceContext(nameof(AutoFakeTest)); } public async Task InitializeAsync() { - _connection = new SqliteConnection("DataSource=:memory:"); + _connection = new("DataSource=:memory:"); await _connection.OpenAsync(); _context @@ -41,14 +43,15 @@ public async Task InitializeAsync() services.AddDbContextPool( z => z .EnableDetailedErrors() - .EnableSensitiveDataLogging().UseSqlite( + .EnableSensitiveDataLogging() + .UseSqlite( _connection ) ); } ); - Populate(new ServiceCollection().ApplyConventions(ConventionContext.From(_context))); + Populate(await new ServiceCollection().ApplyConventionsAsync(await ConventionContext.FromAsync(_context))); await ServiceProvider.WithScoped().Invoke(context => context.Database.EnsureCreatedAsync()); } @@ -57,4 +60,4 @@ public async Task DisposeAsync() { await _connection!.DisposeAsync(); } -} +} \ No newline at end of file diff --git a/test/Sample.Core.Tests/Sample.Core.Tests.csproj b/test/Sample.Core.Tests/Sample.Core.Tests.csproj index 81bb91a78..71806a311 100644 --- a/test/Sample.Core.Tests/Sample.Core.Tests.csproj +++ b/test/Sample.Core.Tests/Sample.Core.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs b/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs index a532658cf..de6d90af4 100644 --- a/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.Graphql.Tests/Helpers/SqliteExtension.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Rocket.Surgery.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Graphql.Tests.Helpers; @@ -13,21 +14,21 @@ public sealed class SqliteExtension : IResettableAlbaExtension where public SqliteExtension() { - _connection = new SqliteConnection("DataSource=:memory:"); + _connection = new("DataSource=:memory:"); } public void Reset(IServiceProvider serviceProvider) { _connection.Close(); _connection.Open(); - serviceProvider.GetRequiredService().Database.EnsureCreated(); + serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreated()); } public async Task ResetAsync(IServiceProvider serviceProvider) { await _connection.CloseAsync(); await _connection.OpenAsync(); - await serviceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + await serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreatedAsync()); } public void Dispose() @@ -64,4 +65,4 @@ public IHostBuilder Configure(IHostBuilder builder) return builder; } -} +} \ No newline at end of file diff --git a/test/Sample.Graphql.Tests/NamedSchemaTests.cs b/test/Sample.Graphql.Tests/NamedSchemaTests.cs deleted file mode 100644 index 1f2477d47..000000000 --- a/test/Sample.Graphql.Tests/NamedSchemaTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyModel; -using Rocket.Surgery.Conventions; -using Rocket.Surgery.Conventions.Testing; -using Rocket.Surgery.Extensions.Testing; - -namespace Sample.Graphql.Tests; - -public class NamedSchemaTests : LoggerTest, IAsyncLifetime -{ - private readonly IConventionContext _context; - - public NamedSchemaTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) - { - _context = ConventionContext.From( - ConventionContextBuilder.Create() - .ForTesting(DependencyContext.Load(GetType().Assembly)!, LoggerFactory) - .WithLogger(LoggerFactory.CreateLogger(nameof(AutoFakeTest))) - .ConfigureServices( - (_, collection) => - { - collection.AddGraphQL(); - collection.AddGraphQL("Named"); - } - ) - ); - ExcludeSourceContext(nameof(NamedSchemaTests)); - } - - public Task InitializeAsync() - { - return Task.CompletedTask; - } - - public Task DisposeAsync() - { - return Task.CompletedTask; - } -} diff --git a/test/Sample.Graphql.Tests/Sample.Graphql.Tests.csproj b/test/Sample.Graphql.Tests/Sample.Graphql.Tests.csproj index cf5fad77a..177037591 100644 --- a/test/Sample.Graphql.Tests/Sample.Graphql.Tests.csproj +++ b/test/Sample.Graphql.Tests/Sample.Graphql.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 true diff --git a/test/Sample.Grpc.Tests/Helpers/SqliteExtension.cs b/test/Sample.Grpc.Tests/Helpers/SqliteExtension.cs index 796759190..1f71febeb 100644 --- a/test/Sample.Grpc.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.Grpc.Tests/Helpers/SqliteExtension.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Rocket.Surgery.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Grpc.Tests.Helpers; @@ -13,21 +14,21 @@ public sealed class SqliteExtension : IResettableAlbaExtension where public SqliteExtension() { - _connection = new SqliteConnection("DataSource=:memory:"); + _connection = new("DataSource=:memory:"); } public void Reset(IServiceProvider serviceProvider) { _connection.Close(); _connection.Open(); - serviceProvider.GetRequiredService().Database.EnsureCreated(); + serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreated()); } public async Task ResetAsync(IServiceProvider serviceProvider) { await _connection.CloseAsync(); await _connection.OpenAsync(); - await serviceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + await serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreatedAsync()); } public void Dispose() @@ -64,4 +65,4 @@ public IHostBuilder Configure(IHostBuilder builder) return builder; } -} +} \ No newline at end of file diff --git a/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs index faa222d1e..745d1c3eb 100644 --- a/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.Grpc.Tests/Helpers/TestWebAppFixture.cs @@ -3,4 +3,4 @@ namespace Sample.Grpc.Tests.Helpers; -public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; \ No newline at end of file diff --git a/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs b/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs index 94a695f3d..f163f1d88 100644 --- a/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs +++ b/test/Sample.Grpc.Tests/LaunchRecords/GetLaunchRecordTests.cs @@ -1,5 +1,4 @@ -using Google.Protobuf.WellKnownTypes; -using NodaTime; +using NodaTime; using Rocket.Surgery.DependencyInjection; using Sample.Core.Domain; using Sample.Core.Models; @@ -12,45 +11,46 @@ namespace Sample.Grpc.Tests.LaunchRecords; public class GetLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppFixture testWebAppFixture) : WebAppFixtureTest(outputHelper, testWebAppFixture) { - private static readonly Faker Faker = new(); - [Fact] public async Task Should_Get_A_LaunchRecord() { var client = new LR.LaunchRecordsClient(AlbaHost.CreateGrpcChannel()); - var record = await ServiceProvider.WithScoped() - .Invoke( - async (context, clock) => - { - var rocket = new ReadyRocket - { - Id = RocketId.New(), - Type = Core.Domain.RocketType.Falcon9, - SerialNumber = "12345678901234" - }; + var record = await ServiceProvider + .WithScoped() + .Invoke( + async (context, clock) => + { + var rocket = new ReadyRocket + { + Id = RocketId.New(), + Type = Core.Domain.RocketType.Falcon9, + SerialNumber = "12345678901234", + }; - var record = new LaunchRecord - { - Partner = "partner", - Payload = "geo-fence-ftl", - RocketId = rocket.Id, - ScheduledLaunchDate = clock.GetCurrentInstant().ToDateTimeOffset(), - PayloadWeightKg = 100, - }; - context.Add(rocket); - context.Add(record); + var record = new LaunchRecord + { + Partner = "partner", + Payload = "geo-fence-ftl", + RocketId = rocket.Id, + ScheduledLaunchDate = clock.GetCurrentInstant().ToDateTimeOffset(), + PayloadWeightKg = 100, + }; + context.Add(rocket); + context.Add(record); - await context.SaveChangesAsync(); - return record; - } - ); + await context.SaveChangesAsync(); + return record; + } + ); - var response = await client.GetLaunchRecordsAsync(new GetLaunchRecordRequest { Id = record.Id.ToString() }); + var response = await client.GetLaunchRecordsAsync(new() { Id = record.Id.ToString(), }); response.Partner.Should().Be("partner"); response.Payload.Should().Be("geo-fence-ftl"); response.RocketType.Should().Be(RocketType.Falcon9); response.RocketSerialNumber.Should().Be("12345678901234"); - response.ScheduledLaunchDate.Should().Be(record.ScheduledLaunchDate.ToTimestamp()); + response.ScheduledLaunchDate.ToDateTimeOffset().Should().BeCloseTo(record.ScheduledLaunchDate, TimeSpan.FromMilliseconds(1)); } -} + + private static readonly Faker Faker = new(); +} \ No newline at end of file diff --git a/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs b/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs index ea2428397..b63c0c2e7 100644 --- a/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs +++ b/test/Sample.Grpc.Tests/LaunchRecords/UpdateLaunchRecordTests.cs @@ -16,37 +16,38 @@ public class UpdateLaunchRecordTests(ITestOutputHelper outputHelper, TestWebAppF public async Task Should_Update_A_LaunchRecord() { var client = new LR.LaunchRecordsClient(AlbaHost.CreateGrpcChannel()); - var record = await ServiceProvider.WithScoped() - .Invoke( - async (context, clk) => - { - var rocket = new ReadyRocket - { - Id = RocketId.New(), - Type = Core.Domain.RocketType.Falcon9, - SerialNumber = "12345678901234" - }; - context.Add(rocket); + var record = await ServiceProvider + .WithScoped() + .Invoke( + async (context, clk) => + { + var rocket = new ReadyRocket + { + Id = RocketId.New(), + Type = Core.Domain.RocketType.Falcon9, + SerialNumber = "12345678901234", + }; + context.Add(rocket); - var record = new LaunchRecord - { - Partner = "partner", - Payload = "geo-fence-ftl", - RocketId = rocket.Id, - Rocket = rocket, - ScheduledLaunchDate = clk.GetCurrentInstant().ToDateTimeOffset(), - PayloadWeightKg = 100, - }; - context.Add(record); + var record = new LaunchRecord + { + Partner = "partner", + Payload = "geo-fence-ftl", + RocketId = rocket.Id, + Rocket = rocket, + ScheduledLaunchDate = clk.GetCurrentInstant().ToDateTimeOffset(), + PayloadWeightKg = 100, + }; + context.Add(record); - await context.SaveChangesAsync(); - return record; - } - ); + await context.SaveChangesAsync(); + return record; + } + ); var launchDate = record.ScheduledLaunchDate.AddSeconds(1).ToTimestamp(); await client.EditLaunchRecordAsync( - new UpdateLaunchRecordRequest + new() { Id = record.Id.ToString(), Partner = "partner", @@ -57,11 +58,11 @@ await client.EditLaunchRecordAsync( } ); - var response = await client.GetLaunchRecordsAsync(new GetLaunchRecordRequest { Id = record.Id.ToString() }); + var response = await client.GetLaunchRecordsAsync(new() { Id = record.Id.ToString(), }); - response.ScheduledLaunchDate.Should().Be(launchDate); + response.ScheduledLaunchDate.ToDateTimeOffset().Should().BeCloseTo(launchDate.ToDateTimeOffset(), TimeSpan.FromMilliseconds(1)); response.PayloadWeightKg.Should().Be(200); } private static readonly Faker Faker = new(); -} +} \ No newline at end of file diff --git a/test/Sample.Grpc.Tests/Sample.Grpc.Tests.csproj b/test/Sample.Grpc.Tests/Sample.Grpc.Tests.csproj index 6e162b528..00e479cc2 100644 --- a/test/Sample.Grpc.Tests/Sample.Grpc.Tests.csproj +++ b/test/Sample.Grpc.Tests/Sample.Grpc.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.Pages.Tests/Helpers/SqliteExtension.cs b/test/Sample.Pages.Tests/Helpers/SqliteExtension.cs index 3b5d29ac9..b44524335 100644 --- a/test/Sample.Pages.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.Pages.Tests/Helpers/SqliteExtension.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Rocket.Surgery.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Pages.Tests.Helpers; @@ -13,21 +14,21 @@ public sealed class SqliteExtension : IResettableAlbaExtension where public SqliteExtension() { - _connection = new SqliteConnection("DataSource=:memory:"); + _connection = new("DataSource=:memory:"); } public void Reset(IServiceProvider serviceProvider) { _connection.Close(); _connection.Open(); - serviceProvider.GetRequiredService().Database.EnsureCreated(); + serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreated()); } public async Task ResetAsync(IServiceProvider serviceProvider) { await _connection.CloseAsync(); await _connection.OpenAsync(); - await serviceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + await serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreatedAsync()); } public void Dispose() diff --git a/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs b/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs index 892a273c3..3c241722a 100644 --- a/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs +++ b/test/Sample.Pages.Tests/Helpers/TestWebAppFixture.cs @@ -3,4 +3,4 @@ namespace Sample.Pages.Tests.Helpers; -public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; +public class TestWebAppFixture() : LaunchPadWebAppFixture(new SqliteExtension()), IAsyncLifetime; \ No newline at end of file diff --git a/test/Sample.Pages.Tests/Sample.Pages.Tests.csproj b/test/Sample.Pages.Tests/Sample.Pages.Tests.csproj index 25bd7c6bb..e41c7997d 100644 --- a/test/Sample.Pages.Tests/Sample.Pages.Tests.csproj +++ b/test/Sample.Pages.Tests/Sample.Pages.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs b/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs index ab05c9ac3..662a08d20 100644 --- a/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs +++ b/test/Sample.Restful.Tests/Helpers/SqliteExtension.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Rocket.Surgery.DependencyInjection; using Rocket.Surgery.LaunchPad.AspNetCore.Testing; namespace Sample.Restful.Tests.Helpers; @@ -13,21 +14,21 @@ public sealed class SqliteExtension : IResettableAlbaExtension where public SqliteExtension() { - _connection = new SqliteConnection("DataSource=:memory:"); + _connection = new("DataSource=:memory:"); } public void Reset(IServiceProvider serviceProvider) { _connection.Close(); _connection.Open(); - serviceProvider.GetRequiredService().Database.EnsureCreated(); + serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreated()); } public async Task ResetAsync(IServiceProvider serviceProvider) { await _connection.CloseAsync(); await _connection.OpenAsync(); - await serviceProvider.GetRequiredService().Database.EnsureCreatedAsync(); + await serviceProvider.WithScoped().Invoke(c => c.Database.EnsureCreatedAsync()); } public void Dispose() @@ -64,4 +65,4 @@ public IHostBuilder Configure(IHostBuilder builder) return builder; } -} +} \ No newline at end of file diff --git a/test/Sample.Restful.Tests/Sample.Restful.Tests.csproj b/test/Sample.Restful.Tests/Sample.Restful.Tests.csproj index f5a60c7e5..687aa52eb 100644 --- a/test/Sample.Restful.Tests/Sample.Restful.Tests.csproj +++ b/test/Sample.Restful.Tests/Sample.Restful.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0 diff --git a/test/Sample.Worker.Tests/Sample.Worker.Tests.csproj b/test/Sample.Worker.Tests/Sample.Worker.Tests.csproj index 8361e7f2c..39a936dc7 100644 --- a/test/Sample.Worker.Tests/Sample.Worker.Tests.csproj +++ b/test/Sample.Worker.Tests/Sample.Worker.Tests.csproj @@ -1,6 +1,6 @@  - net8.0 + net8.0