From 937ca06b6ed8832dd2a9d664c30b53c9d2392e91 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Wed, 17 Jul 2024 16:50:25 +0200 Subject: [PATCH 01/30] Trim trailing whitespace --- .github/ISSUE_TEMPLATE/bug_report.md | 8 ++++---- .github/ISSUE_TEMPLATE/question.md | 2 +- build/pr-code-cleanup.yml | 4 ++-- build/sign-packages.ps1 | 2 +- build/templates/consolidate-coverage.yaml | 2 +- build/verify-code-style.yml | 4 ++-- coverlet.runsettings | 4 ++-- src/Configuration/src/ConfigServer/README.md | 2 +- src/Configuration/src/Placeholder/README.md | 2 +- src/Configuration/src/RandomValue/README.md | 2 +- src/Configuration/src/SpringBoot/README.md | 6 +++--- ...nfigServerConfigurationBuilderExtensionsCoreTest.cs | 10 +++++----- src/Connectors/src/Connectors/README.md | 2 +- src/Discovery/src/Eureka/README.md | 2 +- src/Security/src/DataProtection.Redis/Readme.md | 2 +- .../DiagnosticDescriptors.cs | 2 +- src/testenvironments.json | 2 +- 17 files changed, 29 insertions(+), 29 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index aa1e50789f..ec1d87a7df 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -8,9 +8,9 @@ assignees: '' --- ## Describe the bug -A clear and concise description of the bug. +A clear and concise description of the bug. -## Steps to reproduce +## Steps to reproduce Steps to reproduce the behavior: 1. 2. @@ -20,9 +20,9 @@ A clear and concise description of what you expected to happen. ## Environment (please complete the following information): - Steeltoe Version [e.g. 2.3.0] - - Platform: [e.g. Cloud Foundry, Azure, etc.) + - Platform: [e.g. Cloud Foundry, Azure, etc.) - OS: [e.g. Windows, Linux, Mac OSX] - - .NET Version [e.g. .NET Core 2.1.0, .NET Framework 4.7.1, etc.] + - .NET Version [e.g. .NET Core 2.1.0, .NET Framework 4.7.1, etc.] - Any other library versions to note ## Screenshots diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index 45ca9e5c24..d10452a60b 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -11,7 +11,7 @@ assignees: '' _Enter your question or feedback here_ ## Environment (please complete the following information): - - .NET Version [e.g. .NET Core 3.1.4, .NET Framework 4.7.1, etc.] + - .NET Version [e.g. .NET Core 3.1.4, .NET Framework 4.7.1, etc.] - Steeltoe Version [e.g. 3.0.1] ## Additional context or links diff --git a/build/pr-code-cleanup.yml b/build/pr-code-cleanup.yml index 499a479db6..53cd4fabb7 100644 --- a/build/pr-code-cleanup.yml +++ b/build/pr-code-cleanup.yml @@ -82,7 +82,7 @@ jobs: displayName: Push changes condition: and(succeeded(), eq(variables['hasChangesToCommit'], 'True')) env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) + SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: targetType: 'inline' script: | @@ -112,7 +112,7 @@ jobs: $statusMessage = "Code cleanup was canceled, no changes were pushed." } elseif ($env:AGENT_JOBSTATUS -eq "Failed") { - $url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)" + $url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)" $statusMessage = "Code cleanup failed to reformat and push changes.

View details [here]($url).

" } else { diff --git a/build/sign-packages.ps1 b/build/sign-packages.ps1 index 4a502eed12..e848c3ebac 100644 --- a/build/sign-packages.ps1 +++ b/build/sign-packages.ps1 @@ -16,7 +16,7 @@ $appSettings = Join-Path $currentDirectory 'appsettings.json' $nupkgs = Get-ChildItem $env:ArtifactDirectory/Steeltoe*.*nupkg -recurse | Select-Object -ExpandProperty FullName foreach ($nupkg in $nupkgs) { - ./SignClient 'sign' -c $appSettings -i $nupkg -r $env:SignClientUser -s $env:SignClientSecret -n 'Steeltoe' -d 'Steeltoe' -u 'https://github.com/SteeltoeOSS' + ./SignClient 'sign' -c $appSettings -i $nupkg -r $env:SignClientUser -s $env:SignClientSecret -n 'Steeltoe' -d 'Steeltoe' -u 'https://github.com/SteeltoeOSS' } Write-Host "Sign-packages completed." diff --git a/build/templates/consolidate-coverage.yaml b/build/templates/consolidate-coverage.yaml index 039cc26d29..5bd92d306f 100644 --- a/build/templates/consolidate-coverage.yaml +++ b/build/templates/consolidate-coverage.yaml @@ -28,4 +28,4 @@ jobs: displayName: Publish code coverage to Azure DevOps inputs: codeCoverageTool: Cobertura - summaryFileLocation: $(Build.ArtifactStagingDirectory)/CodeCoverage/Cobertura.xml \ No newline at end of file + summaryFileLocation: $(Build.ArtifactStagingDirectory)/CodeCoverage/Cobertura.xml diff --git a/build/verify-code-style.yml b/build/verify-code-style.yml index a13359d835..5d15c477e3 100644 --- a/build/verify-code-style.yml +++ b/build/verify-code-style.yml @@ -51,10 +51,10 @@ jobs: # We are in detached head (the merge result), so there's no need to account for an out-of-date PR. $baseCommitHash = git rev-parse origin/$env:SYSTEM_PULLREQUEST_TARGETBRANCH if ($LastExitCode -ne 0) { throw "Command 'git rev-parse (1)' failed with exit code $LastExitCode." } - + $headCommitHash = git rev-parse HEAD if ($LastExitCode -ne 0) { throw "Command 'git rev-parse (2)' failed with exit code $LastExitCode." } - + Write-Output "Running code cleanup on commit range $baseCommitHash..$headCommitHash in pull request." dotnet regitlint -s src/Steeltoe.All.sln --print-command --skip-tool-check --max-runs=5 --jb --dotnetcoresdk=$(dotnet --version) --jb-profile="Steeltoe Full Cleanup" --jb --properties:Configuration=Release --jb --properties:NuGetAudit=false --jb --verbosity=WARN --fail-on-diff --print-diff -f commits -a $headCommitHash -b $baseCommitHash } diff --git a/coverlet.runsettings b/coverlet.runsettings index 477dc9aab1..16d10b5dd8 100644 --- a/coverlet.runsettings +++ b/coverlet.runsettings @@ -4,7 +4,7 @@ - opencover + opencover [*.Test*]*,[*]Microsoft.Diagnostics* [Steeltoe.*]* Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute @@ -15,4 +15,4 @@ - \ No newline at end of file + diff --git a/src/Configuration/src/ConfigServer/README.md b/src/Configuration/src/ConfigServer/README.md index 4b05d76c4e..e43e965674 100644 --- a/src/Configuration/src/ConfigServer/README.md +++ b/src/Configuration/src/ConfigServer/README.md @@ -2,4 +2,4 @@ This project contains the [Spring Cloud Config Server](https://projects.spring.io/spring-cloud/docs/1.0.3/spring-cloud.html#_spring_cloud_config) client configuration provider. By acting as a client to the Spring Cloud Config Server, this provider enables the Config Server to become a source of configuration data for a .NET application. You can learn more about Cloud Native Applications and the Spring Cloud Config Server at [Spring Cloud](https://projects.spring.io/spring-cloud/docs/1.0.3/spring-cloud.html). -For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). \ No newline at end of file +For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). diff --git a/src/Configuration/src/Placeholder/README.md b/src/Configuration/src/Placeholder/README.md index 6f4d15295a..72bc5c49f7 100644 --- a/src/Configuration/src/Placeholder/README.md +++ b/src/Configuration/src/Placeholder/README.md @@ -1,4 +1,4 @@ # Configuration Placeholder Resolver .NET Configuration Provider This project contains a Placeholder resolver configuration provider. -For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). \ No newline at end of file +For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). diff --git a/src/Configuration/src/RandomValue/README.md b/src/Configuration/src/RandomValue/README.md index 31110186c7..efcd44ce35 100644 --- a/src/Configuration/src/RandomValue/README.md +++ b/src/Configuration/src/RandomValue/README.md @@ -1,4 +1,4 @@ # Configuration Random Value Generator .NET Configuration Provider This project contains a Random Value configuration provider. -For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). \ No newline at end of file +For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). diff --git a/src/Configuration/src/SpringBoot/README.md b/src/Configuration/src/SpringBoot/README.md index 45c705048f..08fcb36dcd 100644 --- a/src/Configuration/src/SpringBoot/README.md +++ b/src/Configuration/src/SpringBoot/README.md @@ -1,6 +1,6 @@ # Configuration SpringBoot Env .NET Configuration Provider -This project contains configuration providers for environments friendly to Spring Boot applications like SCDF. The configuration may be provided as a json string inside a single environment variable that looks like +This project contains configuration providers for environments friendly to Spring Boot applications like SCDF. The configuration may be provided as a json string inside a single environment variable that looks like `{"spring.cloud.stream.input.binding":"barfoo"}` or as a command-line parameter that looks like `spring.cloud.stream.input.binding=barfoo`. For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). @@ -9,7 +9,7 @@ For more information on how to use this component see the online [Steeltoe docum using Steeltoe.Configuration.SpringBoot; -... +... internal static class Program { private static void Main(string[] args) @@ -32,7 +32,7 @@ internal static class Program } ``` -# Windows command +# Windows command ## Using SPRING_APPLICATION_JSON environment variable ``` diff --git a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs index 123aa323cc..f7270ba3ee 100644 --- a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs +++ b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs @@ -66,7 +66,7 @@ public void AddConfigServer_JsonAppSettingsConfiguresClient() ""timeout"": 10000, ""token"" : ""vaulttoken"", ""tokenRenewRate"": 50000, - ""disableTokenRenewal"": true, + ""disableTokenRenewal"": true, ""tokenTtl"": 50000, ""retry"": { ""enabled"":""false"", @@ -388,7 +388,7 @@ public void AddConfigServer_HandlesPlaceHolders() [Fact] public void AddConfigServer_WithCloudfoundryEnvironment_ConfiguresClientCorrectly() { - const string vcapApplication = @" + const string vcapApplication = @" { ""vcap"": { ""application"": { @@ -443,7 +443,7 @@ public void AddConfigServer_WithCloudfoundryEnvironment_ConfiguresClientCorrectl { ""spring"": { ""application"": { - ""name"": ""${vcap:application:name?foobar}"" + ""name"": ""${vcap:application:name?foobar}"" } } }"; @@ -489,7 +489,7 @@ public void AddConfigServer_WithCloudfoundryEnvironment_ConfiguresClientCorrectl [Fact] public void AddConfigServer_WithCloudfoundryEnvironmentSCS3_ConfiguresClientCorrectly() { - const string vcapApplication = @" + const string vcapApplication = @" { ""vcap"": { ""application"": { @@ -549,7 +549,7 @@ public void AddConfigServer_WithCloudfoundryEnvironmentSCS3_ConfiguresClientCorr { ""spring"": { ""application"": { - ""name"": ""${vcap:application:name?foobar}"" + ""name"": ""${vcap:application:name?foobar}"" } } }"; diff --git a/src/Connectors/src/Connectors/README.md b/src/Connectors/src/Connectors/README.md index a84e4f3879..17fea5ca6b 100644 --- a/src/Connectors/src/Connectors/README.md +++ b/src/Connectors/src/Connectors/README.md @@ -1,6 +1,6 @@ # .NET Service Connectors -This project contains base types used in creating Steeltoe Connectors. Steeltoe Connectors simplify connecting to services on platforms that support service binding. +This project contains base types used in creating Steeltoe Connectors. Steeltoe Connectors simplify connecting to services on platforms that support service binding. ## Connector Package Name and Feeds diff --git a/src/Discovery/src/Eureka/README.md b/src/Discovery/src/Eureka/README.md index 7164403a56..c3065110f0 100644 --- a/src/Discovery/src/Eureka/README.md +++ b/src/Discovery/src/Eureka/README.md @@ -2,4 +2,4 @@ This project contains the Steeltoe Eureka Client. This client provides access to the Netflix Eureka Server. -For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). \ No newline at end of file +For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). diff --git a/src/Security/src/DataProtection.Redis/Readme.md b/src/Security/src/DataProtection.Redis/Readme.md index 7f1cc0add3..ea3663daa6 100644 --- a/src/Security/src/DataProtection.Redis/Readme.md +++ b/src/Security/src/DataProtection.Redis/Readme.md @@ -4,4 +4,4 @@ This project contains a [ASP.NET Core DataProtection Key Storage Provider](https This provider simplifies using Redis on CloudFoundry as a custom key repository. -For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). \ No newline at end of file +For more information on how to use this component see the online [Steeltoe documentation](https://steeltoe.io/). diff --git a/src/Tools/src/ConfigurationSchemaGenerator/DiagnosticDescriptors.cs b/src/Tools/src/ConfigurationSchemaGenerator/DiagnosticDescriptors.cs index a264ecdf85..319fa21f86 100644 --- a/src/Tools/src/ConfigurationSchemaGenerator/DiagnosticDescriptors.cs +++ b/src/Tools/src/ConfigurationSchemaGenerator/DiagnosticDescriptors.cs @@ -12,7 +12,7 @@ namespace Microsoft.Extensions.Configuration.Binder.SourceGeneration; /// /// Mocks out the Configuration.Binder.SourceGeneration project's DiagnosticDescriptors class. -/// +/// /// The real diagnostic descriptors can't be used because they use localized strings, which /// would require getting dotnet/runtime's "SR" generator working in this repo. /// diff --git a/src/testenvironments.json b/src/testenvironments.json index ea1e3fa7ea..539ead6b04 100644 --- a/src/testenvironments.json +++ b/src/testenvironments.json @@ -1,5 +1,5 @@ { - "version": "1", + "version": "1", "environments": [ { "name": "Ubuntu", From 66b84fde89f7369a0efd56fcf028e25bc73028cd Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Wed, 31 Jul 2024 15:19:55 +0200 Subject: [PATCH 02/30] Reduce public API surface of Common, annotate for NRT --- .../CasingConventions/EnumExtensions.cs | 2 + ...SnakeCaseAllCapsEnumMemberJsonConverter.cs | 4 +- .../SnakeCaseEnumConverter.cs | 15 +-- .../ConfigurationKeyConverter.cs | 4 +- .../ConfigurationValuesHelper.cs | 99 +++++++++------ .../PropertyPlaceHolderHelper.cs | 112 +++++++++-------- .../Common/ConfigurationSchemaAttributes.cs | 3 +- .../Discovery/DiscoveryClientHostedService.cs | 2 +- .../{ => Extensions}/ExceptionExtensions.cs | 4 +- .../ServiceCollectionExtensions.cs | 4 +- .../ServiceProviderExtensions.cs | 4 +- .../Common/HealthChecks/HealthAggregator.cs | 9 +- .../Common/HealthChecks/HealthCheckResult.cs | 16 +-- src/Common/src/Common/IApplicationTask.cs | 2 + src/Common/src/Common/Net/InetUtils.cs | 1 + src/Common/src/Common/Platform.cs | 14 ++- .../src/Common/Properties/AssemblyInfo.cs | 2 + src/Common/src/Common/SecurityUtilities.cs | 22 ++-- .../ConfigurationValuesHelperTest.cs | 94 ++++++++------- .../PropertyPlaceholderHelperTest.cs | 114 +++++++++--------- .../ConfigServerDiscoveryService.cs | 1 + .../ConfigurationSettingsHelper.cs | 6 +- .../PlaceholderResolverProvider.cs | 4 +- .../CloudFoundryHostBuilderExtensionsTest.cs | 1 + .../CloudfoundryConfigurationProviderTest.cs | 37 +++--- .../PlaceholderResolverProviderTest.cs | 60 ++++----- .../CosmosDb/CosmosDbHealthContributor.cs | 1 + .../MongoDb/MongoDbHealthContributor.cs | 1 + .../RabbitMQ/RabbitMQHealthContributor.cs | 1 + .../Redis/RedisHealthContributor.cs | 1 + .../RelationalDatabaseHealthContributor.cs | 1 + .../ConsulServiceCollectionExtensions.cs | 1 + src/Discovery/src/Consul/PeriodicHeartbeat.cs | 1 + .../Consul/Registry/ConsulServiceRegistrar.cs | 1 + .../Consul/Registry/ConsulServiceRegistry.cs | 1 + .../src/Eureka/EurekaDiscoveryClient.cs | 1 + .../EurekaServiceCollectionExtensions.cs | 1 + .../HttpClients/DiscoveryHttpClientHandler.cs | 1 + .../DiscoveryHttpDelegatingHandler.cs | 1 + .../EurekaServerHealthContributorTest.cs | 2 +- .../PostConfigureEurekaInstanceOptionsTest.cs | 2 +- .../CloudFoundryEndpointHandler.cs | 10 +- .../CloudFoundrySecurityMiddleware.cs | 26 ++-- ...ndrySecurityServiceCollectionExtensions.cs | 4 +- .../EndpointApplicationBuilderExtensions.cs | 2 +- ...ecurityUtils.cs => PermissionsProvider.cs} | 7 +- .../ContentNegotiationExtensions.cs | 20 ++- .../src/Endpoint/Health/HealthConverter.cs | 2 +- .../src/Endpoint/Health/HealthConverterV3.cs | 2 +- .../Endpoint/Health/HealthEndpointHandler.cs | 17 ++- .../Health/HealthEndpointMiddleware.cs | 2 +- .../Endpoint/Health/HealthEndpointResponse.cs | 45 +++++-- .../src/Endpoint/Info/InfoEndpointHandler.cs | 1 + .../Loggers/LoggersEndpointMiddleware.cs | 2 +- .../src/Endpoint/PublicAPI.Unshipped.txt | 11 +- .../ServiceCollectionExtensions.cs | 1 + .../SpringBootAdminClientHostedService.cs | 1 + .../ThreadDump/EventPipeThreadDumper.cs | 1 + .../Web/Hypermedia/ActuatorEndpointHandler.cs | 6 +- .../Web/Hypermedia/HypermediaService.cs | 8 +- .../TracingBaseServiceCollectionExtensions.cs | 1 + .../CloudFoundrySecurityMiddlewareTest.cs | 8 +- ...tilsTest.cs => PermissionsProviderTest.cs} | 18 +-- .../Health/HealthEndpointTest.cs | 8 +- .../test/Endpoint.Test/Health/HealthTest.cs | 6 +- 65 files changed, 488 insertions(+), 374 deletions(-) rename src/Common/src/Common/{ => Extensions}/ExceptionExtensions.cs (93%) rename src/Common/src/Common/{ => Extensions}/ServiceCollectionExtensions.cs (90%) rename src/Common/src/Common/{ => Extensions}/ServiceProviderExtensions.cs (92%) rename src/Management/src/Endpoint/CloudFoundry/{SecurityUtils.cs => PermissionsProvider.cs} (94%) rename src/Management/test/Endpoint.Test/CloudFoundry/{SecurityUtilsTest.cs => PermissionsProviderTest.cs} (64%) diff --git a/src/Common/src/Common/CasingConventions/EnumExtensions.cs b/src/Common/src/Common/CasingConventions/EnumExtensions.cs index a1323d3ac8..69ef0f9207 100644 --- a/src/Common/src/Common/CasingConventions/EnumExtensions.cs +++ b/src/Common/src/Common/CasingConventions/EnumExtensions.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace Steeltoe.Common.CasingConventions; public static class EnumExtensions diff --git a/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs b/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs index 456f4c3448..c3a96ba682 100644 --- a/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs +++ b/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Text.Json; using System.Text.Json.Serialization; @@ -27,6 +29,6 @@ public override bool CanConvert(Type typeToConvert) public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { Type converterType = typeof(SnakeCaseEnumConverter<>).MakeGenericType(typeToConvert); - return (JsonConverter)Activator.CreateInstance(converterType, SnakeCaseStyle.AllCaps); + return (JsonConverter)Activator.CreateInstance(converterType, SnakeCaseStyle.AllCaps)!; } } diff --git a/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs b/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs index 154bceefa9..29fd360a9b 100644 --- a/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs +++ b/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -16,15 +18,10 @@ namespace Steeltoe.Common.CasingConventions; /// /// The enumeration type. /// -internal sealed class SnakeCaseEnumConverter : JsonConverter +internal sealed class SnakeCaseEnumConverter(SnakeCaseStyle style) : JsonConverter where TEnum : struct, Enum { - private readonly SnakeCaseStyle _style; - - public SnakeCaseEnumConverter(SnakeCaseStyle style) - { - _style = style; - } + private readonly SnakeCaseStyle _style = style; /// public override bool CanConvert(Type typeToConvert) @@ -39,7 +36,7 @@ public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSe if (token == JsonTokenType.String) { - string enumText = reader.GetString(); + string enumText = reader.GetString()!; string pascalCaseText = ToPascalCase(enumText); if (Enum.TryParse(pascalCaseText, out TEnum value) || Enum.TryParse(pascalCaseText, true, out value)) @@ -51,7 +48,7 @@ public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSe throw new JsonException(); } - public string ToPascalCase(string snakeCaseText) + private string ToPascalCase(string snakeCaseText) { var builder = new StringBuilder(); bool nextCharToUpper = true; diff --git a/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs b/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs index d74b9cb01c..eec5dcbc2f 100644 --- a/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs +++ b/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Text; using System.Text.RegularExpressions; using Microsoft.Extensions.Configuration; @@ -39,8 +41,6 @@ public static string AsDotNetConfigurationKey(string key) private static IEnumerable UniversalHierarchySplit(string source) { - ArgumentGuard.NotNull(source); - var result = new List(); int segmentStart = 0; diff --git a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs index 32c71d5c37..b7c24e2104 100644 --- a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs +++ b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs @@ -2,17 +2,20 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Globalization; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; namespace Steeltoe.Common.Configuration; -public static class ConfigurationValuesHelper +internal static class ConfigurationValuesHelper { - public static string GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration resolve, string def) + public static string? GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration? resolve, string? defaultValue) { // First check for key in primary - string setting = GetString(key, primary, resolve, null); + string? setting = GetString(key, primary, resolve, null); if (!string.IsNullOrEmpty(setting)) { @@ -27,37 +30,41 @@ public static string GetSetting(string key, IConfiguration primary, IConfigurati return setting; } - return def; + return defaultValue; } /// - /// Get setting from configuration searching the given sectionPrefix keys in order. Returns the first element with key. + /// Gets a setting from configuration by searching the given section prefix keys in order. Returns the first match. /// /// /// The key of the element to return. /// /// - /// IConfiguration to search through. + /// The to search through. /// /// - /// The default Value if no configuration is found. + /// The default value to return if no configuration is found. /// /// /// The prefixes to search for in given order. /// /// - /// Configuration value. + /// The value from configuration, or the default value if not found. /// - public static string GetSetting(string key, IConfiguration configuration, string defaultValue, params string[] sectionPrefixes) + public static string? GetSetting(string key, IConfiguration configuration, string? defaultValue, params string[] sectionPrefixes) { + ArgumentGuard.NotNull(key); + ArgumentGuard.NotNull(configuration); + ArgumentGuard.NotNull(sectionPrefixes); + foreach (string prefix in sectionPrefixes) { IConfigurationSection section = configuration.GetSection(prefix); - string result = section.GetValue(key); + string? value = section.GetValue(key); - if (!string.IsNullOrEmpty(result)) + if (!string.IsNullOrEmpty(value)) { - return result; + return value; } } @@ -65,84 +72,96 @@ public static string GetSetting(string key, IConfiguration configuration, string } /// - /// Get a setting from configuration by searching the given keys in order. Returns the first match. + /// Gets a setting from configuration by searching the given keys in order. Returns the first match. /// /// - /// IConfiguration to search through. + /// The to search through. /// /// - /// The default Value if no configuration is found. + /// The default value to return if no configuration is found. /// - /// + /// /// The fully-qualified keys to search for in given order. /// /// - /// Value from configuration or default (if not found). + /// The value from configuration, or the default value if not found. /// - public static string GetPreferredSetting(IConfiguration configuration, string defaultValue, params string[] configKeys) + public static string? GetPreferredSetting(IConfiguration configuration, string? defaultValue, params string?[] configurationKeys) { - foreach (string key in configKeys.Where(c => !string.IsNullOrEmpty(c))) + ArgumentGuard.NotNull(configuration); + ArgumentGuard.NotNull(configurationKeys); + + foreach (string key in configurationKeys.Where(key => !string.IsNullOrEmpty(key)).Cast()) { - string result = configuration.GetValue(key); + string? value = configuration.GetValue(key); - if (!string.IsNullOrEmpty(result)) + if (!string.IsNullOrEmpty(value)) { - return result; + return value; } } return defaultValue; } - public static int GetInt(string key, IConfiguration configuration, IConfiguration resolve, int def) + public static int GetInt32(string key, IConfiguration configuration, IConfiguration? resolve, int defaultValue) { - string val = GetString(key, configuration, resolve, null); + ArgumentGuard.NotNullOrEmpty(key); + ArgumentGuard.NotNull(configuration); - if (!string.IsNullOrEmpty(val) && int.TryParse(val, CultureInfo.InvariantCulture, out int result)) + string? value = GetString(key, configuration, resolve, null); + + if (!string.IsNullOrEmpty(value) && int.TryParse(value, CultureInfo.InvariantCulture, out int result)) { return result; } - return def; + return defaultValue; } - public static double GetDouble(string key, IConfiguration configuration, IConfiguration resolve, double def) + public static double GetDouble(string key, IConfiguration configuration, IConfiguration? resolve, double defaultValue) { - string val = GetString(key, configuration, resolve, null); + ArgumentGuard.NotNullOrEmpty(key); + ArgumentGuard.NotNull(configuration); + + string? value = GetString(key, configuration, resolve, null); - if (!string.IsNullOrEmpty(val) && - double.TryParse(val, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out double result)) + if (!string.IsNullOrEmpty(value) && + double.TryParse(value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out double result)) { return result; } - return def; + return defaultValue; } - public static bool GetBoolean(string key, IConfiguration configuration, IConfiguration resolve, bool def) + public static bool GetBoolean(string key, IConfiguration configuration, IConfiguration? resolve, bool defaultValue) { - string val = GetString(key, configuration, resolve, null); + ArgumentGuard.NotNullOrEmpty(key); + ArgumentGuard.NotNull(configuration); + + string? value = GetString(key, configuration, resolve, null); - if (!string.IsNullOrEmpty(val) && bool.TryParse(val, out bool result)) + if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out bool result)) { return result; } - return def; + return defaultValue; } - public static string GetString(string key, IConfiguration configuration, IConfiguration resolve, string def) + public static string? GetString(string key, IConfiguration configuration, IConfiguration? resolve, string? defaultValue) { ArgumentGuard.NotNullOrEmpty(key); ArgumentGuard.NotNull(configuration); - string val = configuration[key]; + string? value = configuration[key]; - if (!string.IsNullOrEmpty(val)) + if (!string.IsNullOrEmpty(value)) { - return PropertyPlaceholderHelper.ResolvePlaceholders(val, resolve); + return PropertyPlaceholderHelper.ResolvePlaceholders(value, resolve, NullLogger.Instance); } - return def; + return defaultValue; } } diff --git a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs index 6a4f52850c..7cfa6cdbd2 100644 --- a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs +++ b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs @@ -2,17 +2,30 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + +using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; namespace Steeltoe.Common.Configuration; /// /// Utility class for working with configuration values that have placeholders in them. A placeholder takes the form of: -/// ${some:config:reference?default_if_not_present}> Note: This was "inspired" by the Spring class: PropertyPlaceholderHelper. +/// +/// +/// Note: This was "inspired" by the Spring class +/// +/// PropertyPlaceholderHelper +/// +/// . +/// /// -public static class PropertyPlaceholderHelper +internal static class PropertyPlaceholderHelper { private const string Prefix = "${"; private const string Suffix = "}"; @@ -20,62 +33,68 @@ public static class PropertyPlaceholderHelper private const string Separator = "?"; /// - /// Replaces all placeholders of the form: ${some:config:reference?default_if_not_present} with the corresponding value from the supplied - /// . + /// Replaces all placeholders of the form: with the corresponding value from + /// the supplied . /// /// - /// the string containing one or more placeholders. + /// The string containing one or more placeholders. /// /// - /// the configuration used for finding replace values. + /// The configuration used for finding replacement values. /// /// - /// optional logger. + /// Used for internal logging. Pass to disable logging. /// /// - /// the supplied value with the placeholders replaced inline. + /// The supplied value, with the placeholders replaced inline. /// - public static string ResolvePlaceholders(string property, IConfiguration configuration, ILogger logger = null) + public static string? ResolvePlaceholders(string? property, IConfiguration? configuration, ILogger logger) { - return ParseStringValue(property, configuration, new HashSet(), logger); + ArgumentGuard.NotNull(logger); + + return ParseStringValue(property, configuration, false, new HashSet(), logger); } /// - /// Finds all placeholders of the form: ${some:config:reference?default_if_not_present}, resolves them from other values in the - /// configuration, returns a new list to add to your configuration. + /// Finds all placeholders of the form: , resolves them from other values in + /// the configuration, and returns a new dictionary to add to your configuration. /// /// /// The configuration to use as both source and target for placeholder resolution. /// /// - /// Optional logger. - /// - /// - /// Replace the placeholder with an empty string, so the application does not see it. + /// Used for internal logging. Pass to disable logging. /// /// - /// A list of keys with resolved values. Add to your with method 'AddInMemoryCollection'. + /// A list of keys with resolved values. Add them to your with method 'AddInMemoryCollection'. /// - public static IEnumerable> GetResolvedConfigurationPlaceholders(IConfiguration configuration, ILogger logger = null, - bool useEmptyStringIfNotFound = true) + public static IDictionary GetResolvedConfigurationPlaceholders(IConfiguration configuration, ILogger logger) { + ArgumentGuard.NotNull(configuration); + ArgumentGuard.NotNull(logger); + // setup a holding tank for resolved values - var resolvedValues = new Dictionary(); + var resolvedValues = new Dictionary(); var visitedPlaceholders = new HashSet(); // iterate all configuration entries where the value isn't null and contains both the prefix and suffix that identify placeholders - foreach (KeyValuePair entry in configuration.AsEnumerable().Where(e => - e.Value != null && e.Value.Contains(Prefix, StringComparison.Ordinal) && e.Value.Contains(Suffix, StringComparison.Ordinal))) + foreach ((string key, string? value) in configuration.AsEnumerable().Where(pair => + pair.Value != null && pair.Value.Contains(Prefix, StringComparison.Ordinal) && pair.Value.Contains(Suffix, StringComparison.Ordinal))) { - logger?.LogTrace("Found a property placeholder '{Placeholder}' to resolve for key '{Key}", entry.Value, entry.Key); - resolvedValues.Add(entry.Key, ParseStringValue(entry.Value, configuration, visitedPlaceholders, logger, useEmptyStringIfNotFound)); + logger.LogTrace("Found a property placeholder '{Placeholder}' to resolve for key '{Key}", value, key); + resolvedValues.Add(key, ParseStringValue(value, configuration, true, visitedPlaceholders, logger)); } return resolvedValues; } - private static string ParseStringValue(string property, IConfiguration configuration, ISet visitedPlaceHolders, ILogger logger = null, - bool useEmptyStringIfNotFound = false) + [return: NotNullIfNotNull(nameof(property))] + private static string? ParseStringValue(string? property, IConfiguration? configuration, bool useEmptyStringIfNotFound, ISet visitedPlaceHolders, + ILogger logger) { if (configuration == null) { @@ -112,15 +131,15 @@ private static string ParseStringValue(string property, IConfiguration configura } // Recursive invocation, parsing placeholders contained in the placeholder key. - placeholder = ParseStringValue(placeholder, configuration, visitedPlaceHolders); + placeholder = ParseStringValue(placeholder, configuration, useEmptyStringIfNotFound, visitedPlaceHolders, logger); // Handle array references foo:bar[1]:baz format -> foo:bar:1:baz string lookup = placeholder.Replace('[', ':').Replace("]", string.Empty, StringComparison.Ordinal); // Now obtain the value for the fully resolved key... - string propVal = configuration[lookup]; + string? propertyValue = configuration[lookup]; - if (propVal == null) + if (propertyValue == null) { int separatorIndex = placeholder.IndexOf(Separator, StringComparison.Ordinal); @@ -128,30 +147,29 @@ private static string ParseStringValue(string property, IConfiguration configura { string actualPlaceholder = placeholder.Substring(0, separatorIndex); string defaultValue = placeholder.Substring(separatorIndex + Separator.Length); - propVal = configuration[actualPlaceholder] ?? defaultValue; + propertyValue = configuration[actualPlaceholder] ?? defaultValue; } else if (useEmptyStringIfNotFound) { - propVal = string.Empty; + propertyValue = string.Empty; } } // Attempt to resolve as a spring-compatible placeholder - if (propVal == null) + if (propertyValue == null) { // Replace Spring delimiters ('.') with MS-friendly delimiters (':') so Spring placeholders can also be resolved lookup = placeholder.Replace('.', ':'); - propVal = configuration[lookup]; + propertyValue = configuration[lookup]; } - if (propVal != null) + if (propertyValue != null) { - // Recursive invocation, parsing placeholders contained in these - // previously resolved placeholder value. - propVal = ParseStringValue(propVal, configuration, visitedPlaceHolders); - result.Replace(startIndex, endIndex + Suffix.Length, propVal); - logger?.LogDebug("Resolved placeholder '{Placeholder}'", placeholder); - startIndex = result.IndexOf(Prefix, startIndex + propVal.Length); + // Recursive invocation, parsing placeholders contained in these previously resolved placeholder value. + propertyValue = ParseStringValue(propertyValue, configuration, useEmptyStringIfNotFound, visitedPlaceHolders, logger); + result.Replace(startIndex, endIndex + Suffix.Length, propertyValue); + logger.LogDebug("Resolved placeholder '{Placeholder}'", placeholder); + startIndex = result.IndexOf(Prefix, startIndex + propertyValue.Length); } else { @@ -170,14 +188,14 @@ private static string ParseStringValue(string property, IConfiguration configura return result.ToString(); } - private static int FindEndIndex(StringBuilder property, int startIndex) + private static int FindEndIndex(StringBuilder builder, int startIndex) { int index = startIndex + Prefix.Length; int withinNestedPlaceholder = 0; - while (index < property.Length) + while (index < builder.Length) { - if (SubstringMatch(property, index, Suffix)) + if (SubstringMatch(builder, index, Suffix)) { if (withinNestedPlaceholder > 0) { @@ -189,7 +207,7 @@ private static int FindEndIndex(StringBuilder property, int startIndex) return index; } } - else if (SubstringMatch(property, index, SimplePrefix)) + else if (SubstringMatch(builder, index, SimplePrefix)) { withinNestedPlaceholder++; index += Prefix.Length; @@ -203,16 +221,16 @@ private static int FindEndIndex(StringBuilder property, int startIndex) return -1; } - private static bool SubstringMatch(StringBuilder str, int index, string substring) + private static bool SubstringMatch(StringBuilder builder, int index, string substring) { - if (index + substring.Length > str.Length) + if (index + substring.Length > builder.Length) { return false; } for (int i = 0; i < substring.Length; i++) { - if (str[index + i] != substring[i]) + if (builder[index + i] != substring[i]) { return false; } diff --git a/src/Common/src/Common/ConfigurationSchemaAttributes.cs b/src/Common/src/Common/ConfigurationSchemaAttributes.cs index 0ad3b8de53..e64d6f9d6e 100644 --- a/src/Common/src/Common/ConfigurationSchemaAttributes.cs +++ b/src/Common/src/Common/ConfigurationSchemaAttributes.cs @@ -1,3 +1,5 @@ +#nullable enable + #pragma warning disable SA1636 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. @@ -7,7 +9,6 @@ #pragma warning disable #pragma warning disable SA1623 // Property summary documentation should match accessors -#pragma warning disable CS8632 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. namespace Aspire; diff --git a/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs b/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs index b911931860..a7a727cbae 100644 --- a/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs +++ b/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs @@ -9,7 +9,7 @@ namespace Steeltoe.Common.Discovery; /// /// Calls when the app is being stopped. /// -public sealed class DiscoveryClientHostedService : IHostedService +internal sealed class DiscoveryClientHostedService : IHostedService { private readonly ICollection _discoveryClients; diff --git a/src/Common/src/Common/ExceptionExtensions.cs b/src/Common/src/Common/Extensions/ExceptionExtensions.cs similarity index 93% rename from src/Common/src/Common/ExceptionExtensions.cs rename to src/Common/src/Common/Extensions/ExceptionExtensions.cs index 7a3c9b6fb4..23535c6ee2 100644 --- a/src/Common/src/Common/ExceptionExtensions.cs +++ b/src/Common/src/Common/Extensions/ExceptionExtensions.cs @@ -6,7 +6,7 @@ using System.Reflection; -namespace Steeltoe.Common; +namespace Steeltoe.Common.Extensions; public static class ExceptionExtensions { @@ -35,7 +35,7 @@ public static Exception UnwrapAll(this Exception exception) exception = exception.InnerException; hasChanges = true; } - else if (exception is AggregateException aggregateException && aggregateException.InnerExceptions.Count == 1) + else if (exception is AggregateException { InnerExceptions.Count: 1 } aggregateException) { exception = aggregateException.InnerExceptions[0]; hasChanges = true; diff --git a/src/Common/src/Common/ServiceCollectionExtensions.cs b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs similarity index 90% rename from src/Common/src/Common/ServiceCollectionExtensions.cs rename to src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs index 8488b3a455..8214c4213d 100644 --- a/src/Common/src/Common/ServiceCollectionExtensions.cs +++ b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs @@ -8,9 +8,9 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace Steeltoe.Common; +namespace Steeltoe.Common.Extensions; -public static class ServiceCollectionExtensions +internal static class ServiceCollectionExtensions { /// /// Try to register a default instance of . diff --git a/src/Common/src/Common/ServiceProviderExtensions.cs b/src/Common/src/Common/Extensions/ServiceProviderExtensions.cs similarity index 92% rename from src/Common/src/Common/ServiceProviderExtensions.cs rename to src/Common/src/Common/Extensions/ServiceProviderExtensions.cs index 96bec24591..c5aba0f5f7 100644 --- a/src/Common/src/Common/ServiceProviderExtensions.cs +++ b/src/Common/src/Common/Extensions/ServiceProviderExtensions.cs @@ -5,9 +5,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -namespace Steeltoe.Common; +namespace Steeltoe.Common.Extensions; -public static class ServiceProviderExtensions +internal static class ServiceProviderExtensions { /// /// If an instance of is found, it is returned. Otherwise, a default instance is returned. diff --git a/src/Common/src/Common/HealthChecks/HealthAggregator.cs b/src/Common/src/Common/HealthChecks/HealthAggregator.cs index ead046cf6f..e1f670fc12 100644 --- a/src/Common/src/Common/HealthChecks/HealthAggregator.cs +++ b/src/Common/src/Common/HealthChecks/HealthAggregator.cs @@ -7,6 +7,7 @@ using System.Collections.Concurrent; using Microsoft.Extensions.Diagnostics.HealthChecks; using Steeltoe.Common.CasingConventions; +using Steeltoe.Common.Extensions; using MicrosoftHealthCheckResult = Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult; using MicrosoftHealthStatus = Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus; using SteeltoeHealthCheckResult = Steeltoe.Common.HealthChecks.HealthCheckResult; @@ -119,10 +120,12 @@ private static async Task RunMicrosoftHealthCheckAsyn healthCheckResult.Status = status; // Only used for aggregate, doesn't get reported healthCheckResult.Description = result.Description; - healthCheckResult.Details = new Dictionary(result.Data) + foreach ((string key, object value) in result.Data) { - { "status", status.ToSnakeCaseString(SnakeCaseStyle.AllCaps) } - }; + healthCheckResult.Details[key] = value; + } + + healthCheckResult.Details["status"] = status.ToSnakeCaseString(SnakeCaseStyle.AllCaps); if (result.Description != null) { diff --git a/src/Common/src/Common/HealthChecks/HealthCheckResult.cs b/src/Common/src/Common/HealthChecks/HealthCheckResult.cs index b7f705824d..0083acdc89 100644 --- a/src/Common/src/Common/HealthChecks/HealthCheckResult.cs +++ b/src/Common/src/Common/HealthChecks/HealthCheckResult.cs @@ -2,18 +2,20 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace Steeltoe.Common.HealthChecks; /// /// The result of a health check. /// -public class HealthCheckResult +public sealed class HealthCheckResult { /// - /// Gets or sets the status of the check. + /// Gets or sets the status of the health check. /// /// - /// Used by HealthMiddleware to determine HTTP Status code. + /// Used by the health middleware to determine the HTTP Status code. /// public HealthStatus Status { get; set; } = HealthStatus.Unknown; @@ -23,13 +25,13 @@ public class HealthCheckResult /// /// Currently only used on check failures. /// - public string Description { get; set; } + public string? Description { get; set; } /// - /// Gets or sets details of the checked item. + /// Gets details of the health check. /// /// - /// For parity with Spring Boot, repeat status [with a call to .ToString()] here. + /// For parity with Spring Boot, repeat the status (in all-caps snake case) here. /// - public Dictionary Details { get; set; } = new(); + public IDictionary Details { get; } = new Dictionary(); } diff --git a/src/Common/src/Common/IApplicationTask.cs b/src/Common/src/Common/IApplicationTask.cs index 61766c8a0f..c2b922bd42 100644 --- a/src/Common/src/Common/IApplicationTask.cs +++ b/src/Common/src/Common/IApplicationTask.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace Steeltoe.Common; /// diff --git a/src/Common/src/Common/Net/InetUtils.cs b/src/Common/src/Common/Net/InetUtils.cs index 687e2cad2f..4b28de896f 100644 --- a/src/Common/src/Common/Net/InetUtils.cs +++ b/src/Common/src/Common/Net/InetUtils.cs @@ -13,6 +13,7 @@ namespace Steeltoe.Common.Net; +// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global // Non-sealed because this type is mocked by tests. internal class InetUtils { diff --git a/src/Common/src/Common/Platform.cs b/src/Common/src/Common/Platform.cs index d69fe3a060..ec436a0a4a 100644 --- a/src/Common/src/Common/Platform.cs +++ b/src/Common/src/Common/Platform.cs @@ -2,14 +2,16 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Runtime.InteropServices; namespace Steeltoe.Common; public static class Platform { - public const string VcapApplication = "VCAP_APPLICATION"; - public const string KubernetesHost = "KUBERNETES_SERVICE_HOST"; + private const string VcapApplication = "VCAP_APPLICATION"; + private const string KubernetesServiceHost = "KUBERNETES_SERVICE_HOST"; public static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); @@ -20,19 +22,19 @@ public static class Platform #pragma warning restore S100 // Methods and properties should be named in PascalCase /// - /// Gets a value indicating whether or not the application appears to be running in a container. + /// Gets a value indicating whether the application appears to be running in a container. /// public static bool IsContainerized => Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true"; /// - /// Gets a value indicating whether or not the platform is Cloud Foundry by checking if VCAP_APPLICATION has been set. + /// Gets a value indicating whether the platform is Cloud Foundry by checking if VCAP_APPLICATION has been set. /// public static bool IsCloudFoundry => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(VcapApplication)); /// - /// Gets a value indicating whether or not the platform is Kubernetes by checking if KUBERNETES_HOST has been set. + /// Gets a value indicating whether the platform is Kubernetes by checking if KUBERNETES_HOST has been set. /// - public static bool IsKubernetes => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(KubernetesHost)); + public static bool IsKubernetes => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(KubernetesServiceHost)); /// /// Gets a value indicating whether an app is running on a cloud provider. Currently supports Cloud Foundry and Kubernetes. diff --git a/src/Common/src/Common/Properties/AssemblyInfo.cs b/src/Common/src/Common/Properties/AssemblyInfo.cs index c30c10522f..f3197b7feb 100644 --- a/src/Common/src/Common/Properties/AssemblyInfo.cs +++ b/src/Common/src/Common/Properties/AssemblyInfo.cs @@ -12,9 +12,11 @@ [assembly: InternalsVisibleTo("Steeltoe.Common.Hosting.Test")] [assembly: InternalsVisibleTo("Steeltoe.Common.Http")] [assembly: InternalsVisibleTo("Steeltoe.Common.Test")] +[assembly: InternalsVisibleTo("Steeltoe.Configuration.CloudFoundry.Test")] [assembly: InternalsVisibleTo("Steeltoe.Configuration.ConfigServer")] [assembly: InternalsVisibleTo("Steeltoe.Configuration.Encryption")] [assembly: InternalsVisibleTo("Steeltoe.Configuration.Kubernetes.ServiceBinding")] +[assembly: InternalsVisibleTo("Steeltoe.Configuration.Placeholder")] [assembly: InternalsVisibleTo("Steeltoe.Connectors")] [assembly: InternalsVisibleTo("Steeltoe.Connectors.EntityFrameworkCore")] [assembly: InternalsVisibleTo("Steeltoe.Discovery.Configuration")] diff --git a/src/Common/src/Common/SecurityUtilities.cs b/src/Common/src/Common/SecurityUtilities.cs index c12c6d7a0f..bebfbd78bb 100644 --- a/src/Common/src/Common/SecurityUtilities.cs +++ b/src/Common/src/Common/SecurityUtilities.cs @@ -2,6 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + +using System.Diagnostics.CodeAnalysis; using System.Net; namespace Steeltoe.Common; @@ -9,24 +12,25 @@ namespace Steeltoe.Common; /// /// Helpers for compliance with security scans. /// -public static class SecurityUtilities +internal static class SecurityUtilities { /// - /// Remove line endings and HTML-encode strings. Useful for logging (potentially) user-entered data. + /// Removes line breaks from text and HTML-encodes it. Useful for logging (potentially) user-entered data. /// - /// - /// Some string to sanitize. + /// + /// The text to sanitize. /// /// - /// HTML-encoded version of original string with CR and LF removed. + /// The HTML-encoded version of the original string, with line breaks removed. /// - public static string SanitizeInput(string inputString) + [return: NotNullIfNotNull(nameof(text))] + public static string? SanitizeInput(string? text) { - if (string.IsNullOrEmpty(inputString)) + if (string.IsNullOrEmpty(text)) { - return inputString; + return text; } - return WebUtility.HtmlEncode(inputString.Replace("\r", string.Empty, StringComparison.Ordinal).Replace("\n", string.Empty, StringComparison.Ordinal)); + return WebUtility.HtmlEncode(text.Replace("\r", string.Empty, StringComparison.Ordinal).Replace("\n", string.Empty, StringComparison.Ordinal)); } } diff --git a/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs b/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs index 2dffeffff3..f1ecb85e52 100644 --- a/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs +++ b/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using Microsoft.Extensions.Configuration; using Steeltoe.Common.Configuration; @@ -12,40 +14,40 @@ public sealed class ConfigurationValuesHelperTest [Fact] public void GetString_NoResolveFromConfig() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - string result = ConfigurationValuesHelper.GetString("a:b", configuration, null, null); + string? result = ConfigurationValuesHelper.GetString("a:b", configuration, null, null); Assert.Equal("astring", result); } [Fact] - public void GetInt_ReturnsValue() + public void GetInt32_ReturnsValue() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "100" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - int result = ConfigurationValuesHelper.GetInt("a:b", configuration, null, 500); + int result = ConfigurationValuesHelper.GetInt32("a:b", configuration, null, 500); Assert.Equal(100, result); } [Fact] public void GetDouble_ReturnsValue() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "100.00" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); double result = ConfigurationValuesHelper.GetDouble("a:b", configuration, null, 500.00); Assert.Equal(100.00, result); @@ -54,12 +56,12 @@ public void GetDouble_ReturnsValue() [Fact] public void GetBoolean_ReturnsValue() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "True" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); bool result = ConfigurationValuesHelper.GetBoolean("a:b", configuration, null, false); Assert.True(result); @@ -68,26 +70,26 @@ public void GetBoolean_ReturnsValue() [Fact] public void GetInt_NotFoundReturnsDefault() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - int result = ConfigurationValuesHelper.GetInt("a:b:c", configuration, null, 100); + int result = ConfigurationValuesHelper.GetInt32("a:b:c", configuration, null, 100); Assert.Equal(100, result); } [Fact] public void GetDouble_NotFoundReturnsDefault() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); double result = ConfigurationValuesHelper.GetDouble("a:b:c", configuration, null, 100.00); Assert.Equal(100.00, result); @@ -96,12 +98,12 @@ public void GetDouble_NotFoundReturnsDefault() [Fact] public void GetBoolean_NotFoundReturnsDefault() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); bool result = ConfigurationValuesHelper.GetBoolean("a:b:c", configuration, null, true); Assert.True(result); @@ -110,114 +112,114 @@ public void GetBoolean_NotFoundReturnsDefault() [Fact] public void GetString_NotFoundReturnsDefault() { - var dict = new Dictionary + var settings = new Dictionary { { "a:b", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - string result = ConfigurationValuesHelper.GetString("a:b:c", configuration, null, "foobar"); + string? result = ConfigurationValuesHelper.GetString("a:b:c", configuration, null, "foobar"); Assert.Equal("foobar", result); } [Fact] public void GetString_ResolvesReference() { - var dict = new Dictionary + var settings1 = new Dictionary { { "a:b", "${a:b:c}" } }; - var dict2 = new Dictionary + var settings2 = new Dictionary { { "a:b:c", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); - IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(dict2).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); + IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, "foobar"); + string? result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, "foobar"); Assert.Equal("astring", result); } [Fact] public void GetString_ResolveNotFoundReturnsNotResolvedValue() { - var dict = new Dictionary + var settings1 = new Dictionary { { "a:b", "${a:b:c}" } }; - var dict2 = new Dictionary + var settings2 = new Dictionary { { "a:b:d", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); - IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(dict2).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); + IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, null); + string? result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, null); Assert.Equal("${a:b:c}", result); } [Fact] public void GetString_ResolveNotFoundReturnsPlaceholderDefault() { - var dict = new Dictionary + var settings1 = new Dictionary { { "a:b", "${a:b:c?placeholderdefault}" } }; - var dict2 = new Dictionary + var settings2 = new Dictionary { { "a:b:d", "astring" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); - IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(dict2).Build(); + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); + IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, "foobar"); + string? result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, "foobar"); Assert.Equal("placeholderdefault", result); } [Fact] public void GetSetting_GetsFromFirst() { - var dict = new Dictionary + var settings1 = new Dictionary { { "a:b", "setting1" } }; - var dict2 = new Dictionary + var settings2 = new Dictionary { { "a:b", "setting2" } }; - IConfiguration config1 = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); - IConfiguration config2 = new ConfigurationBuilder().AddInMemoryCollection(dict2).Build(); + IConfiguration config1 = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); + IConfiguration config2 = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); + string? result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); Assert.Equal("setting1", result); } [Fact] public void GetSetting_GetsFromSecond() { - var dict = new Dictionary + var settings1 = new Dictionary { { "a:b:c", "setting1" } }; - var dict2 = new Dictionary + var settings2 = new Dictionary { { "a:b", "setting2" } }; - IConfiguration config1 = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); - IConfiguration config2 = new ConfigurationBuilder().AddInMemoryCollection(dict2).Build(); + IConfiguration config1 = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); + IConfiguration config2 = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); + string? result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); Assert.Equal("setting2", result); } } diff --git a/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs b/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs index 9f224120e7..334f35cea6 100644 --- a/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs +++ b/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs @@ -2,7 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; using Steeltoe.Common.Configuration; using Steeltoe.Common.TestResources.IO; @@ -16,7 +19,7 @@ public void ResolvePlaceholders_ResolvesSinglePlaceholder() const string text = "foo=${foo}"; var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "foo", "bar" } }; @@ -24,7 +27,7 @@ public void ResolvePlaceholders_ResolvesSinglePlaceholder() builder.AddInMemoryCollection(dic1); IConfigurationRoot configurationRoot = builder.Build(); - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); Assert.Equal("foo=bar", result); } @@ -34,7 +37,7 @@ public void ResolvePlaceholders_ResolvesSingleSpringPlaceholder() const string text = "foo=${foo.bar}"; var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "foo:bar", "bar" } }; @@ -42,7 +45,7 @@ public void ResolvePlaceholders_ResolvesSingleSpringPlaceholder() builder.AddInMemoryCollection(dic1); IConfigurationRoot configurationRoot = builder.Build(); - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); Assert.Equal("foo=bar", result); } @@ -52,7 +55,7 @@ public void ResolvePlaceholders_ResolvesMultiplePlaceholders() const string text = "foo=${foo},bar=${bar}"; var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "foo", "bar" }, { "bar", "baz" } @@ -60,7 +63,7 @@ public void ResolvePlaceholders_ResolvesMultiplePlaceholders() builder.AddInMemoryCollection(dic1); - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build()); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build(), NullLogger.Instance); Assert.Equal("foo=bar,bar=baz", result); } @@ -70,7 +73,7 @@ public void ResolvePlaceholders_ResolvesMultipleSpringPlaceholders() const string text = "foo=${foo.boo},bar=${bar.far}"; var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "foo:boo", "bar" }, { "bar:far", "baz" } @@ -78,7 +81,7 @@ public void ResolvePlaceholders_ResolvesMultipleSpringPlaceholders() builder.AddInMemoryCollection(dic1); - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build()); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build(), NullLogger.Instance); Assert.Equal("foo=bar,bar=baz", result); } @@ -88,7 +91,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursivePlaceholders() const string text = "foo=${bar}"; var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "bar", "${baz}" }, { "baz", "bar" } @@ -97,7 +100,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursivePlaceholders() builder.AddInMemoryCollection(dic1); IConfigurationRoot configurationRoot = builder.Build(); - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); Assert.Equal("foo=bar", result); } @@ -107,7 +110,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveSpringPlaceholders() const string text = "foo=${bar.boo}"; var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "bar:boo", "${baz.faz}" }, { "baz:faz", "bar" } @@ -116,7 +119,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveSpringPlaceholders() builder.AddInMemoryCollection(dic1); IConfigurationRoot configurationRoot = builder.Build(); - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); Assert.Equal("foo=bar", result); } @@ -126,7 +129,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() const string text1 = "foo=${b${inner}}"; var builder1 = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "bar", "bar" }, { "inner", "ar" } @@ -138,7 +141,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() const string text2 = "${top}"; var builder2 = new ConfigurationBuilder(); - var dic2 = new Dictionary + var dic2 = new Dictionary { { "top", "${child}+${child}" }, { "child", "${${differentiator}.grandchild}" }, @@ -149,9 +152,9 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() builder2.AddInMemoryCollection(dic2); IConfigurationRoot config2 = builder2.Build(); - string result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1); + string? result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1, NullLogger.Instance); Assert.Equal("foo=bar", result1); - string result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2); + string? result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2, NullLogger.Instance); Assert.Equal("actualValue+actualValue", result2); } @@ -161,7 +164,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInSpringPlaceholders() const string text1 = "foo=${b${inner.placeholder}}"; var builder1 = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "bar", "bar" }, { "inner:placeholder", "ar" } @@ -173,7 +176,7 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInSpringPlaceholders() const string text2 = "${top}"; var builder2 = new ConfigurationBuilder(); - var dic2 = new Dictionary + var dic2 = new Dictionary { { "top", "${child}+${child}" }, { "child", "${${differentiator}.grandchild}" }, @@ -184,9 +187,9 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInSpringPlaceholders() builder2.AddInMemoryCollection(dic2); IConfigurationRoot config2 = builder2.Build(); - string result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1); + string? result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1, NullLogger.Instance); Assert.Equal("foo=bar", result1); - string result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2); + string? result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2, NullLogger.Instance); Assert.Equal("actualValue+actualValue", result2); } @@ -196,7 +199,7 @@ public void ResolvePlaceholders_UnresolvedPlaceholderIsIgnored() const string text = "foo=${foo},bar=${bar}"; var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var dic1 = new Dictionary { { "foo", "bar" } }; @@ -204,44 +207,45 @@ public void ResolvePlaceholders_UnresolvedPlaceholderIsIgnored() builder.AddInMemoryCollection(dic1); IConfigurationRoot configurationRoot = builder.Build(); - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); Assert.Equal("foo=bar,bar=${bar}", result); } [Fact] public void ResolvePlaceholders_ResolvesArrayRefPlaceholder() { - const string json1 = @" -{ - ""vcap"": { - ""application"": { - ""application_id"": ""fa05c1a9-0fc1-4fbd-bae1-139850dec7a3"", - ""application_name"": ""my-app"", - ""application_uris"": [ - ""my-app.10.244.0.34.xip.io"" - ], - ""application_version"": ""fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca"", - ""limits"": { - ""disk"": 1024, - ""fds"": 16384, - ""mem"": 256 - }, - ""name"": ""my-app"", - ""space_id"": ""06450c72-4669-4dc6-8096-45f9777db68a"", - ""space_name"": ""my-space"", - ""uris"": [ - ""my-app.10.244.0.34.xip.io"", - ""my-app2.10.244.0.34.xip.io"" - ], - ""users"": null, - ""version"": ""fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca"" - } - } -}"; + const string json1 = """ + { + "vcap": { + "application": { + "application_id": "fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", + "application_name": "my-app", + "application_uris": [ + "my-app.10.244.0.34.xip.io" + ], + "application_version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca", + "limits": { + "disk": 1024, + "fds": 16384, + "mem": 256 + }, + "name": "my-app", + "space_id": "06450c72-4669-4dc6-8096-45f9777db68a", + "space_name": "my-space", + "uris": [ + "my-app.10.244.0.34.xip.io", + "my-app2.10.244.0.34.xip.io" + ], + "users": null, + "version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca" + } + } + } + """; using var sandbox = new Sandbox(); string path = sandbox.CreateFile("json", json1); - string directory = Path.GetDirectoryName(path); + string directory = Path.GetDirectoryName(path)!; string fileName = Path.GetFileName(path); var builder = new ConfigurationBuilder(); builder.SetBasePath(directory); @@ -251,7 +255,7 @@ public void ResolvePlaceholders_ResolvesArrayRefPlaceholder() const string text = "foo=${vcap:application:uris[1]}"; - string result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot); + string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); Assert.Equal("foo=my-app2.10.244.0.34.xip.io", result); } @@ -260,13 +264,13 @@ public void GetResolvedConfigurationPlaceholders_ReturnsValues_WhenResolved() { var builder = new ConfigurationBuilder(); - builder.AddInMemoryCollection(new Dictionary + builder.AddInMemoryCollection(new Dictionary { { "foo", "${bar}" }, { "bar", "baz" } }); - IEnumerable> resolved = PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(builder.Build()); + IDictionary resolved = PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(builder.Build(), NullLogger.Instance); Assert.Contains(resolved, f => f.Key == "foo"); Assert.DoesNotContain(resolved, f => f.Key == "bar"); @@ -278,12 +282,12 @@ public void GetResolvedConfigurationPlaceholders_ReturnsEmpty_WhenUnResolved() { var builder = new ConfigurationBuilder(); - builder.AddInMemoryCollection(new Dictionary + builder.AddInMemoryCollection(new Dictionary { { "foo", "${bar}" } }); - IEnumerable> resolved = PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(builder.Build()); + IDictionary resolved = PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(builder.Build(), NullLogger.Instance); Assert.Contains(resolved, f => f.Key == "foo"); Assert.Equal(string.Empty, resolved.First(k => k.Key == "foo").Value); diff --git a/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs b/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs index 9f074e8da6..5f15c1e707 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Logging; using Steeltoe.Common; using Steeltoe.Common.Discovery; +using Steeltoe.Common.Extensions; using Steeltoe.Discovery.Configuration; using Steeltoe.Discovery.Consul; using Steeltoe.Discovery.Eureka; diff --git a/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs b/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs index 0cd06933aa..c66ee0c376 100644 --- a/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs +++ b/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs @@ -66,19 +66,19 @@ private static bool GetCertificateValidation(IConfigurationSection section, bool return section.GetValue("validateCertificates", defaultValue) && section.GetValue("validate_certificates", defaultValue); } - private static string GetClientSecret(string sectionPrefix, IConfiguration configuration) + private static string? GetClientSecret(string sectionPrefix, IConfiguration configuration) { return ConfigurationValuesHelper.GetSetting("credentials:client_secret", configuration, null, VcapServicesConfigserverPrefix, VcapServicesConfigserver30Prefix, VcapServicesConfigserverAltPrefix, sectionPrefix); } - private static string GetClientId(string sectionPrefix, IConfiguration configuration) + private static string? GetClientId(string sectionPrefix, IConfiguration configuration) { return ConfigurationValuesHelper.GetSetting("credentials:client_id", configuration, null, VcapServicesConfigserverPrefix, VcapServicesConfigserver30Prefix, VcapServicesConfigserverAltPrefix, sectionPrefix); } - private static string GetAccessTokenUri(string sectionPrefix, IConfiguration configuration) + private static string? GetAccessTokenUri(string sectionPrefix, IConfiguration configuration) { return ConfigurationValuesHelper.GetSetting("credentials:access_token_uri", configuration, null, VcapServicesConfigserverPrefix, VcapServicesConfigserver30Prefix, VcapServicesConfigserverAltPrefix, sectionPrefix); diff --git a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs index 3d49dacd38..23b114b2d9 100644 --- a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs +++ b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs @@ -77,13 +77,13 @@ public PlaceholderResolverProvider(IList providers, ILog /// /// true if a value for the specified key was found, otherwise false. /// - public bool TryGet(string key, out string value) + public bool TryGet(string key, out string? value) { ArgumentGuard.NotNull(key); EnsureInitialized(); string? originalValue = Configuration![key]; - value = PropertyPlaceholderHelper.ResolvePlaceholders(originalValue, Configuration); + value = PropertyPlaceholderHelper.ResolvePlaceholders(originalValue, Configuration, NullLogger.Instance); if (value != originalValue && !ResolvedKeys.Contains(key)) { diff --git a/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs b/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs index 59de88c937..0c90709f53 100644 --- a/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs +++ b/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Common.TestResources; namespace Steeltoe.Configuration.CloudFoundry.Test; diff --git a/src/Configuration/test/CloudFoundry.Test/CloudfoundryConfigurationProviderTest.cs b/src/Configuration/test/CloudFoundry.Test/CloudfoundryConfigurationProviderTest.cs index 761e97170b..4c11551c9a 100644 --- a/src/Configuration/test/CloudFoundry.Test/CloudfoundryConfigurationProviderTest.cs +++ b/src/Configuration/test/CloudFoundry.Test/CloudfoundryConfigurationProviderTest.cs @@ -39,11 +39,11 @@ public void Load_VCAP_APPLICATION_ChangesDataDictionary() var provider = new CloudFoundryConfigurationProvider(new CloudFoundryEnvironmentSettingsReader()); provider.Load(); - IDictionary dict = provider.Properties; - Assert.Equal("fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", dict["vcap:application:application_id"]); - Assert.Equal("1024", dict["vcap:application:limits:disk"]); - Assert.Equal("my-app.10.244.0.34.xip.io", dict["vcap:application:uris:0"]); - Assert.Equal("my-app2.10.244.0.34.xip.io", dict["vcap:application:uris:1"]); + IDictionary properties = provider.Properties; + Assert.Equal("fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", properties["vcap:application:application_id"]); + Assert.Equal("1024", properties["vcap:application:limits:disk"]); + Assert.Equal("my-app.10.244.0.34.xip.io", properties["vcap:application:uris:0"]); + Assert.Equal("my-app2.10.244.0.34.xip.io", properties["vcap:application:uris:1"]); } [Fact] @@ -80,9 +80,9 @@ public void Load_VCAP_SERVICES_ChangesDataDictionary() var provider = new CloudFoundryConfigurationProvider(new CloudFoundryEnvironmentSettingsReader()); provider.Load(); - IDictionary dict = provider.Properties; - Assert.Equal("elephantsql-c6c60", dict["vcap:services:elephantsql:0:name"]); - Assert.Equal("mysendgrid", dict["vcap:services:sendgrid:0:name"]); + IDictionary properties = provider.Properties; + Assert.Equal("elephantsql-c6c60", properties["vcap:services:elephantsql:0:name"]); + Assert.Equal("mysendgrid", properties["vcap:services:sendgrid:0:name"]); } [Fact] @@ -156,20 +156,23 @@ public void Load_VCAP_SERVICES_MultiServices_ChangesDataDictionary() var provider = new CloudFoundryConfigurationProvider(new CloudFoundryEnvironmentSettingsReader()); provider.Load(); - IDictionary dict = provider.Properties; - Assert.Equal("myConfigServer", dict["vcap:services:p-config-server:0:name"]); - Assert.Equal("https://config-eafc353b-77e2-4dcc-b52a-25777e996ed9.apps.testcloud.com", dict["vcap:services:p-config-server:0:credentials:uri"]); - Assert.Equal("myServiceRegistry", dict["vcap:services:p-service-registry:0:name"]); - Assert.Equal("https://eureka-f4b98d1c-3166-4741-b691-79abba5b2d51.apps.testcloud.com", dict["vcap:services:p-service-registry:0:credentials:uri"]); - Assert.Equal("mySql1", dict["vcap:services:p-mysql:0:name"]); + IDictionary properties = provider.Properties; + Assert.Equal("myConfigServer", properties["vcap:services:p-config-server:0:name"]); + Assert.Equal("https://config-eafc353b-77e2-4dcc-b52a-25777e996ed9.apps.testcloud.com", properties["vcap:services:p-config-server:0:credentials:uri"]); + Assert.Equal("myServiceRegistry", properties["vcap:services:p-service-registry:0:name"]); + + Assert.Equal("https://eureka-f4b98d1c-3166-4741-b691-79abba5b2d51.apps.testcloud.com", + properties["vcap:services:p-service-registry:0:credentials:uri"]); + + Assert.Equal("mySql1", properties["vcap:services:p-mysql:0:name"]); Assert.Equal("mysql://9vD0Mtk3wFFuaaaY:Cjn4HsAiKV8sImst@192.168.0.97:3306/cf_0f5dda44_e678_4727_993f_30e6d455cc31?reconnect=true", - dict["vcap:services:p-mysql:0:credentials:uri"]); + properties["vcap:services:p-mysql:0:credentials:uri"]); - Assert.Equal("mySql2", dict["vcap:services:p-mysql:1:name"]); + Assert.Equal("mySql2", properties["vcap:services:p-mysql:1:name"]); Assert.Equal("mysql://gxXQb2pMbzFsZQW8:lvMkGf6oJQvKSOwn@192.168.0.97:3306/cf_b2d83697_5fa1_4a51_991b_975c9d7e5515?reconnect=true", - dict["vcap:services:p-mysql:1:credentials:uri"]); + properties["vcap:services:p-mysql:1:credentials:uri"]); } [Fact] diff --git a/src/Configuration/test/Placeholder.Test/PlaceholderResolverProviderTest.cs b/src/Configuration/test/Placeholder.Test/PlaceholderResolverProviderTest.cs index 2124dca6be..4faca23e07 100644 --- a/src/Configuration/test/Placeholder.Test/PlaceholderResolverProviderTest.cs +++ b/src/Configuration/test/Placeholder.Test/PlaceholderResolverProviderTest.cs @@ -50,15 +50,15 @@ public void TryGet_ReturnsResolvedValues() var holder = new PlaceholderResolverProvider(providers, NullLoggerFactory.Instance); - Assert.False(holder.TryGet("nokey", out string val)); - Assert.True(holder.TryGet("key1", out val)); - Assert.Equal("value1", val); - Assert.True(holder.TryGet("key2", out val)); - Assert.Equal("value1", val); - Assert.True(holder.TryGet("key3", out val)); - Assert.Equal("notfound", val); - Assert.True(holder.TryGet("key4", out val)); - Assert.Equal("${nokey}", val); + Assert.False(holder.TryGet("nokey", out string? value)); + Assert.True(holder.TryGet("key1", out value)); + Assert.Equal("value1", value); + Assert.True(holder.TryGet("key2", out value)); + Assert.Equal("value1", value); + Assert.True(holder.TryGet("key3", out value)); + Assert.Equal("notfound", value); + Assert.True(holder.TryGet("key4", out value)); + Assert.Equal("${nokey}", value); } [Fact] @@ -78,21 +78,21 @@ public void Set_SetsValues_ReturnsResolvedValues() var holder = new PlaceholderResolverProvider(providers, NullLoggerFactory.Instance); - Assert.False(holder.TryGet("nokey", out string val)); - Assert.True(holder.TryGet("key1", out val)); - Assert.Equal("value1", val); - Assert.True(holder.TryGet("key2", out val)); - Assert.Equal("value1", val); - Assert.True(holder.TryGet("key3", out val)); - Assert.Equal("notfound", val); - Assert.True(holder.TryGet("key4", out val)); - Assert.Equal("${nokey}", val); + Assert.False(holder.TryGet("nokey", out string? value)); + Assert.True(holder.TryGet("key1", out value)); + Assert.Equal("value1", value); + Assert.True(holder.TryGet("key2", out value)); + Assert.Equal("value1", value); + Assert.True(holder.TryGet("key3", out value)); + Assert.Equal("notfound", value); + Assert.True(holder.TryGet("key4", out value)); + Assert.Equal("${nokey}", value); holder.Set("nokey", "nokeyvalue"); - Assert.True(holder.TryGet("key3", out val)); - Assert.Equal("nokeyvalue", val); - Assert.True(holder.TryGet("key4", out val)); - Assert.Equal("nokeyvalue", val); + Assert.True(holder.TryGet("key3", out value)); + Assert.Equal("nokeyvalue", value); + Assert.True(holder.TryGet("key4", out value)); + Assert.Equal("nokeyvalue", value); } [Fact] @@ -142,8 +142,8 @@ public async Task GetReloadToken_ReturnsExpected_NotifyChanges() Assert.NotNull(token); Assert.False(token.HasChanged); - Assert.True(holder.TryGet("spring:cloud:config:name", out string val)); - Assert.Equal("myName", val); + Assert.True(holder.TryGet("spring:cloud:config:name", out string? value)); + Assert.Equal("myName", value); await File.WriteAllTextAsync(path, appsettings2); @@ -152,8 +152,8 @@ public async Task GetReloadToken_ReturnsExpected_NotifyChanges() await Task.Delay(2000); Assert.True(token.HasChanged); - Assert.True(holder.TryGet("spring:cloud:config:name", out val)); - Assert.Equal("newMyName", val); + Assert.True(holder.TryGet("spring:cloud:config:name", out value)); + Assert.Equal("newMyName", value); } [Fact] @@ -221,16 +221,16 @@ public async Task Load_ReloadsConfiguration() IConfigurationRoot configurationRoot = configurationBuilder.Build(); var holder = new PlaceholderResolverProvider(configurationRoot, NullLoggerFactory.Instance); - Assert.True(holder.TryGet("spring:cloud:config:name", out string val)); - Assert.Equal("myName", val); + Assert.True(holder.TryGet("spring:cloud:config:name", out string? value)); + Assert.Equal("myName", value); await File.WriteAllTextAsync(path, appsettings2); await Task.Delay(1000); // There is a 250ms delay holder.Load(); - Assert.True(holder.TryGet("spring:cloud:config:name", out val)); - Assert.Equal("newMyName", val); + Assert.True(holder.TryGet("spring:cloud:config:name", out value)); + Assert.Equal("newMyName", value); } [Fact] diff --git a/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs b/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs index 09e0c8572c..3f80cff2c8 100644 --- a/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs +++ b/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Logging; using Steeltoe.Common; using Steeltoe.Common.CasingConventions; +using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.CosmosDb.DynamicTypeAccess; using Steeltoe.Connectors.DynamicTypeAccess; diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs index a6d3547a4c..cfb196bc67 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging; using Steeltoe.Common; using Steeltoe.Common.CasingConventions; +using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.MongoDb.DynamicTypeAccess; diff --git a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs index 89c6f51fb5..a1b843d785 100644 --- a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs +++ b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Logging; using Steeltoe.Common; using Steeltoe.Common.CasingConventions; +using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.RabbitMQ.DynamicTypeAccess; diff --git a/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs b/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs index 3fe30905a0..57be40fb14 100644 --- a/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs +++ b/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging; using Steeltoe.Common; using Steeltoe.Common.CasingConventions; +using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.Redis.DynamicTypeAccess; diff --git a/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs b/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs index 220bba16f2..7648ee7f3e 100644 --- a/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs +++ b/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Logging; using Steeltoe.Common; using Steeltoe.Common.CasingConventions; +using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Connectors; diff --git a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs index 7797b7ce9a..ba345efb0f 100644 --- a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs +++ b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs @@ -9,6 +9,7 @@ using Steeltoe.Common; using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; +using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; using Steeltoe.Common.Net; using Steeltoe.Discovery.Consul.Configuration; diff --git a/src/Discovery/src/Consul/PeriodicHeartbeat.cs b/src/Discovery/src/Consul/PeriodicHeartbeat.cs index 5fb6b774d5..3a2fd6ccf2 100644 --- a/src/Discovery/src/Consul/PeriodicHeartbeat.cs +++ b/src/Discovery/src/Consul/PeriodicHeartbeat.cs @@ -5,6 +5,7 @@ using Consul; using Microsoft.Extensions.Logging; using Steeltoe.Common; +using Steeltoe.Common.Extensions; namespace Steeltoe.Discovery.Consul; diff --git a/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs b/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs index 7a59b6e577..00f36217e1 100644 --- a/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs +++ b/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Discovery.Consul.Configuration; namespace Steeltoe.Discovery.Consul.Registry; diff --git a/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs b/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs index 5ea9213338..a9a73d9fdb 100644 --- a/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs +++ b/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Discovery.Consul.Configuration; namespace Steeltoe.Discovery.Consul.Registry; diff --git a/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs b/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs index 72991dff08..937ce22da9 100644 --- a/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs +++ b/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Options; using Steeltoe.Common; using Steeltoe.Common.Discovery; +using Steeltoe.Common.Extensions; using Steeltoe.Discovery.Eureka.AppInfo; using Steeltoe.Discovery.Eureka.Configuration; using Steeltoe.Discovery.Eureka.Transport; diff --git a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs index ea6431d758..d75a9d2ffd 100644 --- a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs +++ b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs @@ -10,6 +10,7 @@ using Steeltoe.Common.Certificates; using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; +using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; using Steeltoe.Common.Http.HttpClientPooling; using Steeltoe.Common.Net; diff --git a/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs b/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs index 60f85340f9..8ea9901397 100644 --- a/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs +++ b/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Discovery.HttpClients.LoadBalancers; namespace Steeltoe.Discovery.HttpClients; diff --git a/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs b/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs index 549b304827..c4b73f3c7a 100644 --- a/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs +++ b/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.DependencyInjection; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Discovery.HttpClients.LoadBalancers; namespace Steeltoe.Discovery.HttpClients; diff --git a/src/Discovery/test/Eureka.Test/EurekaServerHealthContributorTest.cs b/src/Discovery/test/Eureka.Test/EurekaServerHealthContributorTest.cs index 2b5d97f1e4..eba7c60cb6 100644 --- a/src/Discovery/test/Eureka.Test/EurekaServerHealthContributorTest.cs +++ b/src/Discovery/test/Eureka.Test/EurekaServerHealthContributorTest.cs @@ -77,7 +77,7 @@ public void AddApplications_AddsExpected() var result = new HealthCheckResult(); contributor.AddApplications(apps, result); - Dictionary? details = result.Details; + IDictionary details = result.Details; Assert.Contains("applications", details.Keys); var appsDict = (Dictionary)details["applications"]; Assert.Contains("app1", appsDict.Keys); diff --git a/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs b/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs index 2cd6eebd0b..c8c6811cae 100644 --- a/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs +++ b/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs @@ -11,8 +11,8 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; -using Steeltoe.Common; using Steeltoe.Common.Configuration; +using Steeltoe.Common.Extensions; using Steeltoe.Common.Net; using Steeltoe.Common.TestResources; using Steeltoe.Discovery.Eureka.AppInfo; diff --git a/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs b/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs index 11ac5a3148..d17f7d8960 100755 --- a/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs +++ b/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs @@ -19,30 +19,30 @@ internal sealed class CloudFoundryEndpointHandler : ICloudFoundryEndpointHandler private readonly IOptionsMonitor _managementOptionsMonitor; private readonly IOptionsMonitor _endpointOptionsMonitor; private readonly ICollection _endpointOptionsCollection; - private readonly ILogger _logger; + private readonly ILogger _hypermediaServiceLogger; public EndpointOptions Options => _endpointOptionsMonitor.CurrentValue; public CloudFoundryEndpointHandler(IOptionsMonitor managementOptionsMonitor, IOptionsMonitor endpointOptionsMonitor, IEnumerable endpointOptionsCollection, - ILogger logger) + ILoggerFactory loggerFactory) { ArgumentGuard.NotNull(managementOptionsMonitor); ArgumentGuard.NotNull(endpointOptionsMonitor); ArgumentGuard.NotNull(endpointOptionsCollection); - ArgumentGuard.NotNull(logger); + ArgumentGuard.NotNull(loggerFactory); _managementOptionsMonitor = managementOptionsMonitor; _endpointOptionsMonitor = endpointOptionsMonitor; _endpointOptionsCollection = endpointOptionsCollection.ToList(); - _logger = logger; + _hypermediaServiceLogger = loggerFactory.CreateLogger(); } public async Task InvokeAsync(string baseUrl, CancellationToken cancellationToken) { ArgumentGuard.NotNull(baseUrl); - var hypermediaService = new HypermediaService(_managementOptionsMonitor, _endpointOptionsMonitor, _endpointOptionsCollection, _logger); + var hypermediaService = new HypermediaService(_managementOptionsMonitor, _endpointOptionsMonitor, _endpointOptionsCollection, _hypermediaServiceLogger); Links result = hypermediaService.Invoke(baseUrl); return await Task.FromResult(result); } diff --git a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs index a0a633797c..2f3c286289 100644 --- a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs +++ b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs @@ -21,22 +21,22 @@ internal sealed class CloudFoundrySecurityMiddleware private readonly ICollection _endpointOptionsCollection; private readonly RequestDelegate? _next; private readonly ILogger _logger; - private readonly SecurityUtils _securityUtils; + private readonly PermissionsProvider _permissionsProvider; public CloudFoundrySecurityMiddleware(IOptionsMonitor managementOptionsMonitor, IOptionsMonitor endpointOptionsMonitor, IEnumerable endpointOptionsCollection, - SecurityUtils securityUtils, ILogger logger, RequestDelegate? next) + PermissionsProvider permissionsProvider, ILogger logger, RequestDelegate? next) { ArgumentGuard.NotNull(managementOptionsMonitor); ArgumentGuard.NotNull(endpointOptionsMonitor); ArgumentGuard.NotNull(endpointOptionsCollection); - ArgumentGuard.NotNull(securityUtils); + ArgumentGuard.NotNull(permissionsProvider); ArgumentGuard.NotNull(logger); _managementOptionsMonitor = managementOptionsMonitor; _endpointOptionsMonitor = endpointOptionsMonitor; _endpointOptionsCollection = endpointOptionsCollection.Where(options => options is not HypermediaEndpointOptions).ToList(); - _securityUtils = securityUtils; + _permissionsProvider = permissionsProvider; _logger = logger; _next = next; } @@ -49,21 +49,21 @@ public async Task InvokeAsync(HttpContext context) CloudFoundryEndpointOptions endpointOptions = _endpointOptionsMonitor.CurrentValue; if (Platform.IsCloudFoundry && endpointOptions.IsEnabled(_managementOptionsMonitor.CurrentValue) && - SecurityUtils.IsCloudFoundryRequest(context.Request.Path)) + PermissionsProvider.IsCloudFoundryRequest(context.Request.Path)) { if (string.IsNullOrEmpty(endpointOptions.ApplicationId)) { _logger.LogCritical( "The Application Id could not be found. Make sure the Cloud Foundry Configuration Provider has been added to the application configuration."); - await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, SecurityUtils.ApplicationIdMissingMessage)); + await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, PermissionsProvider.ApplicationIdMissingMessage)); return; } if (string.IsNullOrEmpty(endpointOptions.CloudFoundryApi)) { - await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, SecurityUtils.CloudfoundryApiMissingMessage)); + await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, PermissionsProvider.CloudfoundryApiMissingMessage)); return; } @@ -72,7 +72,7 @@ public async Task InvokeAsync(HttpContext context) if (targetEndpointOptions == null) { - await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, SecurityUtils.EndpointNotConfiguredMessage)); + await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.ServiceUnavailable, PermissionsProvider.EndpointNotConfiguredMessage)); return; } @@ -87,7 +87,7 @@ public async Task InvokeAsync(HttpContext context) if (targetEndpointOptions.RequiredPermissions > givenPermissions.Permissions) { - await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.Forbidden, SecurityUtils.AccessDeniedMessage)); + await ReturnErrorAsync(context, new SecurityResult(HttpStatusCode.Forbidden, PermissionsProvider.AccessDeniedMessage)); return; } } @@ -100,13 +100,13 @@ public async Task InvokeAsync(HttpContext context) internal string GetAccessToken(HttpRequest request) { - if (request.Headers.TryGetValue(SecurityUtils.AuthorizationHeader, out StringValues headerVal)) + if (request.Headers.TryGetValue(PermissionsProvider.AuthorizationHeader, out StringValues headerVal)) { string header = headerVal.ToString(); - if (header.StartsWith(SecurityUtils.Bearer, StringComparison.OrdinalIgnoreCase)) + if (header.StartsWith(PermissionsProvider.Bearer, StringComparison.OrdinalIgnoreCase)) { - return header.Substring(SecurityUtils.Bearer.Length + 1); + return header.Substring(PermissionsProvider.Bearer.Length + 1); } } @@ -116,7 +116,7 @@ internal string GetAccessToken(HttpRequest request) internal Task GetPermissionsAsync(HttpContext context) { string accessToken = GetAccessToken(context.Request); - return _securityUtils.GetPermissionsAsync(accessToken, context.RequestAborted); + return _permissionsProvider.GetPermissionsAsync(accessToken, context.RequestAborted); } private EndpointOptions? FindTargetEndpoint(PathString requestPath) diff --git a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs index b18d6e7786..8a1c085335 100644 --- a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs @@ -15,7 +15,7 @@ public static IServiceCollection AddCloudFoundrySecurity(this IServiceCollection { ArgumentGuard.NotNull(services); - services.AddSingleton(); + services.AddSingleton(); ConfigureHttpClient(services); return services; @@ -26,7 +26,7 @@ private static void ConfigureHttpClient(IServiceCollection services) services.TryAddSingleton(); services.TryAddSingleton>(); - IHttpClientBuilder httpClientBuilder = services.AddHttpClient(SecurityUtils.HttpClientName); + IHttpClientBuilder httpClientBuilder = services.AddHttpClient(PermissionsProvider.HttpClientName); httpClientBuilder.ConfigurePrimaryHttpMessageHandler(serviceProvider => { diff --git a/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs b/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs index 72f45e95e6..9efdda688d 100644 --- a/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs +++ b/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs @@ -20,7 +20,7 @@ public static void UseCloudFoundrySecurity(this IApplicationBuilder builder) { ArgumentGuard.NotNull(builder); - if (builder.ApplicationServices.GetService() == null) + if (builder.ApplicationServices.GetService() == null) { throw new InvalidOperationException( $"Please call IServiceCollection.{nameof(CloudFoundrySecurityServiceCollectionExtensions.AddCloudFoundrySecurity)} first."); diff --git a/src/Management/src/Endpoint/CloudFoundry/SecurityUtils.cs b/src/Management/src/Endpoint/CloudFoundry/PermissionsProvider.cs similarity index 94% rename from src/Management/src/Endpoint/CloudFoundry/SecurityUtils.cs rename to src/Management/src/Endpoint/CloudFoundry/PermissionsProvider.cs index 8aafb00289..5d05912816 100644 --- a/src/Management/src/Endpoint/CloudFoundry/SecurityUtils.cs +++ b/src/Management/src/Endpoint/CloudFoundry/PermissionsProvider.cs @@ -10,12 +10,13 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Common.Http; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint.CloudFoundry; -internal sealed class SecurityUtils +internal sealed class PermissionsProvider { private const string AuthorizationHeaderInvalid = "Authorization header is missing or invalid"; private const string CloudfoundryNotReachableMessage = "Cloud controller not reachable"; @@ -31,9 +32,9 @@ internal sealed class SecurityUtils private readonly IOptionsMonitor _optionsMonitor; private readonly IHttpClientFactory _httpClientFactory; - private readonly ILogger _logger; + private readonly ILogger _logger; - public SecurityUtils(IOptionsMonitor optionsMonitor, IHttpClientFactory httpClientFactory, ILogger logger) + public PermissionsProvider(IOptionsMonitor optionsMonitor, IHttpClientFactory httpClientFactory, ILogger logger) { ArgumentGuard.NotNull(optionsMonitor); ArgumentGuard.NotNull(httpClientFactory); diff --git a/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs b/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs index 2bb35271e0..d0e3578393 100644 --- a/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs +++ b/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs @@ -12,37 +12,35 @@ namespace Steeltoe.Management.Endpoint.ContentNegotiation; internal static class ContentNegotiationExtensions { - internal static void HandleContentNegotiation(this HttpContext context, ILogger logger) + public static void HandleContentNegotiation(this HttpContext context, ILogger logger) { ArgumentGuard.NotNull(context); ArgumentGuard.NotNull(logger); - SetContentType(context.Response.Headers, context.Request.Headers, logger); + SetContentType(context.Request.Headers, context.Response.Headers, logger); } - private static void SetContentType(IHeaderDictionary responseHeaders, IHeaderDictionary requestHeaders, ILogger logger, + private static void SetContentType(IHeaderDictionary requestHeaders, IHeaderDictionary responseHeaders, ILogger logger, MediaTypeVersion version = MediaTypeVersion.V2) { var headers = new RequestHeaders(requestHeaders); List acceptMediaTypes = headers.Accept.Select(header => header.MediaType.Value!).ToList(); string contentType = ActuatorMediaTypes.GetContentHeaders(acceptMediaTypes, version); - responseHeaders.Append("Content-Type", contentType); - LogContentType(logger, requestHeaders, contentType); + LogResponseContentTypeWithRequestHeaders(contentType, requestHeaders, logger); } - private static void LogContentType(ILogger logger, IHeaderDictionary requestHeaders, string contentType) + private static void LogResponseContentTypeWithRequestHeaders(string contentType, IHeaderDictionary requestHeaders, ILogger logger) { - logger.LogTrace("setting contentType to {Type}", contentType); - bool? logTrace = logger.IsEnabled(LogLevel.Trace); - - if (logTrace.GetValueOrDefault()) + if (logger.IsEnabled(LogLevel.Trace)) { + logger.LogTrace("Setting Content-Type to {ContentType}", contentType); + foreach (KeyValuePair header in requestHeaders) { - logger.LogTrace("Header: {Key} - {Value}", header.Key, header.Value); + logger.LogTrace("Request header: {Key} = {Value}", header.Key, header.Value); } } } diff --git a/src/Management/src/Endpoint/Health/HealthConverter.cs b/src/Management/src/Endpoint/Health/HealthConverter.cs index aa426c3262..1f9c23647c 100644 --- a/src/Management/src/Endpoint/Health/HealthConverter.cs +++ b/src/Management/src/Endpoint/Health/HealthConverter.cs @@ -29,7 +29,7 @@ public override void Write(Utf8JsonWriter writer, HealthEndpointResponse value, writer.WriteString("description", value.Description); } - if (value.Details != null && value.Details.Count > 0) + if (value.Details.Count > 0) { writer.WritePropertyName("details"); writer.WriteStartObject(); diff --git a/src/Management/src/Endpoint/Health/HealthConverterV3.cs b/src/Management/src/Endpoint/Health/HealthConverterV3.cs index e82ed9c443..aa04bf8e07 100644 --- a/src/Management/src/Endpoint/Health/HealthConverterV3.cs +++ b/src/Management/src/Endpoint/Health/HealthConverterV3.cs @@ -27,7 +27,7 @@ public override void Write(Utf8JsonWriter writer, HealthEndpointResponse value, writer.WriteString("description", value.Description); } - if (value.Details != null && value.Details.Count > 0) + if (value.Details.Count > 0) { writer.WritePropertyName("components"); writer.WriteStartObject(); diff --git a/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs b/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs index 5b223e2f27..1f1a1b16d5 100755 --- a/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs +++ b/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs @@ -42,11 +42,11 @@ public HealthEndpointHandler(IOptionsMonitor endpointOpti _logger = loggerFactory.CreateLogger(); } - public int GetStatusCode(HealthCheckResult health) + public int GetStatusCode(HealthEndpointResponse response) { - ArgumentGuard.NotNull(health); + ArgumentGuard.NotNull(response); - return health.Status is HealthStatus.Down or HealthStatus.OutOfService ? 503 : 200; + return response.Status is HealthStatus.Down or HealthStatus.OutOfService ? 503 : 200; } public async Task InvokeAsync(HealthEndpointRequest healthRequest, CancellationToken cancellationToken) @@ -74,13 +74,12 @@ public async Task InvokeAsync(HealthEndpointRequest heal ShowDetails showDetails = endpointOptions.ShowDetails; - if (showDetails == ShowDetails.Never || (showDetails == ShowDetails.WhenAuthorized && !healthRequest.HasClaim)) + if (showDetails != ShowDetails.Never && (showDetails != ShowDetails.WhenAuthorized || healthRequest.HasClaim)) { - response.Details = new Dictionary(); - } - else - { - response.Groups = endpointOptions.Groups.Select(group => group.Key).ToList(); + foreach (string group in endpointOptions.Groups.Select(group => group.Key).ToList()) + { + response.Groups.Add(group); + } } return response; diff --git a/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs b/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs index aed6ed4aa5..59c694c660 100644 --- a/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs @@ -35,7 +35,7 @@ protected override async Task InvokeEndpointHandlerAsync if (!IsValidGroup(groupName)) { - return new HealthEndpointResponse(null) + return new HealthEndpointResponse { Exists = false }; diff --git a/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs b/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs index 1c41e7579b..4d6329e8f7 100644 --- a/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs +++ b/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs @@ -2,27 +2,52 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +using Steeltoe.Common; using Steeltoe.Common.HealthChecks; -#pragma warning disable S4004 // Collection properties should be readonly - namespace Steeltoe.Management.Endpoint.Health; -public sealed class HealthEndpointResponse : HealthCheckResult +public sealed class HealthEndpointResponse { /// - /// Gets or sets the list of available health groups. + /// Gets the status of the health check. + /// + public HealthStatus Status { get; init; } + + /// + /// Gets a description of the health check result. + /// + public string? Description { get; init; } + + /// + /// Gets details of the health check. + /// + public IDictionary Details { get; } = new Dictionary(); + + /// + /// Gets the list of available health groups. /// - public IList Groups { get; set; } = new List(); + public IList Groups { get; } = new List(); - public bool Exists { get; set; } = true; + /// + /// Gets a value indicating whether a health response exists. + /// + public bool Exists { get; init; } = true; - public HealthEndpointResponse(HealthCheckResult? result) + public HealthEndpointResponse() { - result ??= new HealthCheckResult(); + } + + public HealthEndpointResponse(HealthCheckResult result) + { + ArgumentGuard.NotNull(result); - Description = result.Description; - Details = result.Details; Status = result.Status; + Description = result.Description; + + foreach ((string key, object value) in result.Details) + { + Details[key] = value; + } } } diff --git a/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs b/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs index 48f725b42b..1d950f2e37 100755 --- a/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs +++ b/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Management.Info; namespace Steeltoe.Management.Endpoint.Info; diff --git a/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs b/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs index c4add1a2ec..c1e45f8383 100644 --- a/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Loggers/LoggersEndpointMiddleware.cs @@ -7,7 +7,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Management.Endpoint.ContentNegotiation; using Steeltoe.Management.Endpoint.Middleware; using Steeltoe.Management.Endpoint.Options; diff --git a/src/Management/src/Endpoint/PublicAPI.Unshipped.txt b/src/Management/src/Endpoint/PublicAPI.Unshipped.txt index 2ad3cbed6f..41daaf1826 100755 --- a/src/Management/src/Endpoint/PublicAPI.Unshipped.txt +++ b/src/Management/src/Endpoint/PublicAPI.Unshipped.txt @@ -235,11 +235,16 @@ Steeltoe.Management.Endpoint.Health.HealthEndpointRequest.GroupName.get -> strin Steeltoe.Management.Endpoint.Health.HealthEndpointRequest.HasClaim.get -> bool Steeltoe.Management.Endpoint.Health.HealthEndpointRequest.HealthEndpointRequest(string! groupName, bool hasClaim) -> void Steeltoe.Management.Endpoint.Health.HealthEndpointResponse +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Description.get -> string? +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Description.init -> void +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Details.get -> System.Collections.Generic.IDictionary! Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Exists.get -> bool -Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Exists.set -> void +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Exists.init -> void Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Groups.get -> System.Collections.Generic.IList! -Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Groups.set -> void -Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.HealthEndpointResponse(Steeltoe.Common.HealthChecks.HealthCheckResult? result) -> void +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.HealthEndpointResponse() -> void +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.HealthEndpointResponse(Steeltoe.Common.HealthChecks.HealthCheckResult! result) -> void +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Status.get -> Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Management.Endpoint.Health.HealthEndpointResponse.Status.init -> void Steeltoe.Management.Endpoint.Health.HealthGroupOptions Steeltoe.Management.Endpoint.Health.HealthGroupOptions.HealthGroupOptions() -> void Steeltoe.Management.Endpoint.Health.HealthGroupOptions.Include.get -> string? diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs index eedc6b8c6f..ab0c82b024 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Common.Http.HttpClientPooling; using Steeltoe.Management.Endpoint.Health; using Steeltoe.Management.Endpoint.Options; diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs b/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs index 2a09321deb..1a2213704a 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Common.Http; using Steeltoe.Management.Endpoint.Health; using Steeltoe.Management.Endpoint.Options; diff --git a/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs b/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs index 93ba9d845e..59ae5484b1 100644 --- a/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs +++ b/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Steeltoe.Common; +using Steeltoe.Common.Extensions; namespace Steeltoe.Management.Endpoint.ThreadDump; diff --git a/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs b/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs index 11e96164a1..2b1efab870 100755 --- a/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs @@ -17,7 +17,7 @@ internal sealed class ActuatorEndpointHandler : IActuatorEndpointHandler private readonly IOptionsMonitor _managementOptionsMonitor; private readonly IOptionsMonitor _endpointOptionsMonitor; private readonly ICollection _endpointOptionsCollection; - private readonly ILogger _logger; + private readonly ILogger _hypermediaServiceLogger; public EndpointOptions Options => _endpointOptionsMonitor.CurrentValue; @@ -32,14 +32,14 @@ public ActuatorEndpointHandler(IOptionsMonitor managementOpti _managementOptionsMonitor = managementOptionsMonitor; _endpointOptionsMonitor = endpointOptionsMonitor; _endpointOptionsCollection = endpointOptionsCollection.ToList(); - _logger = loggerFactory.CreateLogger(); + _hypermediaServiceLogger = loggerFactory.CreateLogger(); } public Task InvokeAsync(string baseUrl, CancellationToken cancellationToken) { ArgumentGuard.NotNull(baseUrl); - var service = new HypermediaService(_managementOptionsMonitor, _endpointOptionsMonitor, _endpointOptionsCollection, _logger); + var service = new HypermediaService(_managementOptionsMonitor, _endpointOptionsMonitor, _endpointOptionsCollection, _hypermediaServiceLogger); Links result = service.Invoke(baseUrl); return Task.FromResult(result); } diff --git a/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs b/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs index d55039e648..43522b1082 100644 --- a/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs @@ -15,10 +15,11 @@ internal sealed class HypermediaService private readonly IOptionsMonitor _managementOptionsMonitor; private readonly EndpointOptions _endpointOptions; private readonly ICollection _endpointOptionsCollection; - private readonly ILogger _logger; + private readonly ILogger _logger; public HypermediaService(IOptionsMonitor managementOptionsMonitor, - IOptionsMonitor hypermediaEndpointOptionsMonitor, ICollection endpointOptionsCollection, ILogger logger) + IOptionsMonitor hypermediaEndpointOptionsMonitor, ICollection endpointOptionsCollection, + ILogger logger) { ArgumentGuard.NotNull(managementOptionsMonitor); ArgumentGuard.NotNull(hypermediaEndpointOptionsMonitor); @@ -32,7 +33,8 @@ public HypermediaService(IOptionsMonitor managementOptionsMon } public HypermediaService(IOptionsMonitor managementOptionsMonitor, - IOptionsMonitor cloudFoundryEndpointOptionsMonitor, ICollection endpointOptionsCollection, ILogger logger) + IOptionsMonitor cloudFoundryEndpointOptionsMonitor, ICollection endpointOptionsCollection, + ILogger logger) { ArgumentGuard.NotNull(managementOptionsMonitor); ArgumentGuard.NotNull(cloudFoundryEndpointOptionsMonitor); diff --git a/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs b/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs index 6b98237172..65d70b22ae 100644 --- a/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs +++ b/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs @@ -14,6 +14,7 @@ using OpenTelemetry.Resources; using OpenTelemetry.Trace; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Logging; using Steeltoe.Management.Endpoint; using Steeltoe.Management.Wavefront.Exporters; diff --git a/src/Management/test/Endpoint.Test/CloudFoundry/CloudFoundrySecurityMiddlewareTest.cs b/src/Management/test/Endpoint.Test/CloudFoundry/CloudFoundrySecurityMiddlewareTest.cs index b7e8ee0ce4..c9cae792d3 100644 --- a/src/Management/test/Endpoint.Test/CloudFoundry/CloudFoundrySecurityMiddlewareTest.cs +++ b/src/Management/test/Endpoint.Test/CloudFoundry/CloudFoundrySecurityMiddlewareTest.cs @@ -331,9 +331,9 @@ public void GetAccessToken_ReturnsExpected() var services = new ServiceCollection(); services.AddCloudFoundrySecurity(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var securityUtils = serviceProvider.GetRequiredService(); + var permissionsProvider = serviceProvider.GetRequiredService(); - var middleware = new CloudFoundrySecurityMiddleware(managementOptionsMonitor, endpointOptionsMonitor, [], securityUtils, + var middleware = new CloudFoundrySecurityMiddleware(managementOptionsMonitor, endpointOptionsMonitor, [], permissionsProvider, NullLogger.Instance, null); HttpContext context1 = CreateRequest("GET", "/"); @@ -355,9 +355,9 @@ public async Task GetPermissions_ReturnsExpected() var services = new ServiceCollection(); services.AddCloudFoundrySecurity(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var securityUtils = serviceProvider.GetRequiredService(); + var permissionsProvider = serviceProvider.GetRequiredService(); - var middleware = new CloudFoundrySecurityMiddleware(managementOptionsMonitor, endpointOptionsMonitor, [], securityUtils, + var middleware = new CloudFoundrySecurityMiddleware(managementOptionsMonitor, endpointOptionsMonitor, [], permissionsProvider, NullLogger.Instance, null); HttpContext context = CreateRequest("GET", "/"); diff --git a/src/Management/test/Endpoint.Test/CloudFoundry/SecurityUtilsTest.cs b/src/Management/test/Endpoint.Test/CloudFoundry/PermissionsProviderTest.cs similarity index 64% rename from src/Management/test/Endpoint.Test/CloudFoundry/SecurityUtilsTest.cs rename to src/Management/test/Endpoint.Test/CloudFoundry/PermissionsProviderTest.cs index 7fee21962a..e3ccc0a25c 100644 --- a/src/Management/test/Endpoint.Test/CloudFoundry/SecurityUtilsTest.cs +++ b/src/Management/test/Endpoint.Test/CloudFoundry/PermissionsProviderTest.cs @@ -11,27 +11,27 @@ namespace Steeltoe.Management.Endpoint.Test.CloudFoundry; -public sealed class SecurityUtilsTest : BaseTest +public sealed class PermissionsProviderTest : BaseTest { [Fact] public void IsCloudFoundryRequest_ReturnsExpected() { - Assert.True(SecurityUtils.IsCloudFoundryRequest("/cloudfoundryapplication")); - Assert.True(SecurityUtils.IsCloudFoundryRequest("/cloudfoundryapplication/badpath")); + Assert.True(PermissionsProvider.IsCloudFoundryRequest("/cloudfoundryapplication")); + Assert.True(PermissionsProvider.IsCloudFoundryRequest("/cloudfoundryapplication/badpath")); } [Fact] public async Task GetPermissionsAsyncTest() { - SecurityUtils securityUtils = GetSecurityUtils(); - SecurityResult result = await securityUtils.GetPermissionsAsync("testToken", CancellationToken.None); + PermissionsProvider permissionsProvider = GetPermissionsProvider(); + SecurityResult result = await permissionsProvider.GetPermissionsAsync("testToken", CancellationToken.None); Assert.NotNull(result); } [Fact] public async Task GetPermissionsTest() { - SecurityUtils securityUtils = GetSecurityUtils(); + PermissionsProvider permissionsProvider = GetPermissionsProvider(); var response = new HttpResponseMessage(HttpStatusCode.OK); var permissions = new Dictionary @@ -40,11 +40,11 @@ public async Task GetPermissionsTest() }; response.Content = JsonContent.Create(permissions); - Permissions result = await securityUtils.GetPermissionsAsync(response, CancellationToken.None); + Permissions result = await permissionsProvider.GetPermissionsAsync(response, CancellationToken.None); Assert.Equal(Permissions.Full, result); } - private static SecurityUtils GetSecurityUtils() + private static PermissionsProvider GetPermissionsProvider() { IOptionsMonitor optionsMonitor = GetOptionsMonitorFromSettings(); @@ -53,6 +53,6 @@ private static SecurityUtils GetSecurityUtils() ServiceProvider serviceProvider = services.BuildServiceProvider(true); var httpClientFactory = serviceProvider.GetRequiredService(); - return new SecurityUtils(optionsMonitor, httpClientFactory, NullLogger.Instance); + return new PermissionsProvider(optionsMonitor, httpClientFactory, NullLogger.Instance); } } diff --git a/src/Management/test/Endpoint.Test/Health/HealthEndpointTest.cs b/src/Management/test/Endpoint.Test/Health/HealthEndpointTest.cs index 1309312194..311186f2ca 100644 --- a/src/Management/test/Endpoint.Test/Health/HealthEndpointTest.cs +++ b/src/Management/test/Endpoint.Test/Health/HealthEndpointTest.cs @@ -163,22 +163,22 @@ public void GetStatusCode_ReturnsExpected() var handler = (HealthEndpointHandler)testContext.GetRequiredScopedService(); - Assert.Equal(503, handler.GetStatusCode(new HealthCheckResult + Assert.Equal(503, handler.GetStatusCode(new HealthEndpointResponse { Status = HealthStatus.Down })); - Assert.Equal(503, handler.GetStatusCode(new HealthCheckResult + Assert.Equal(503, handler.GetStatusCode(new HealthEndpointResponse { Status = HealthStatus.OutOfService })); - Assert.Equal(200, handler.GetStatusCode(new HealthCheckResult + Assert.Equal(200, handler.GetStatusCode(new HealthEndpointResponse { Status = HealthStatus.Up })); - Assert.Equal(200, handler.GetStatusCode(new HealthCheckResult + Assert.Equal(200, handler.GetStatusCode(new HealthEndpointResponse { Status = HealthStatus.Unknown })); diff --git a/src/Management/test/Endpoint.Test/Health/HealthTest.cs b/src/Management/test/Endpoint.Test/Health/HealthTest.cs index 1954886ba9..b64ba66b4f 100644 --- a/src/Management/test/Endpoint.Test/Health/HealthTest.cs +++ b/src/Management/test/Endpoint.Test/Health/HealthTest.cs @@ -24,7 +24,7 @@ public void Constructor_InitializesDefaults() [Fact] public void Serialize_Default_ReturnsExpected() { - var health = new HealthEndpointResponse(null); + var health = new HealthEndpointResponse(); string json = Serialize(health); Assert.Equal("{\"status\":\"UNKNOWN\"}", json); } @@ -32,11 +32,11 @@ public void Serialize_Default_ReturnsExpected() [Fact] public void Serialize_WithDetails_ReturnsExpected() { - var health = new HealthEndpointResponse(null) + var health = new HealthEndpointResponse { Status = HealthStatus.OutOfService, Description = "Test", - Details = new Dictionary + Details = { { "item1", new HealthData() }, { "item2", "String" }, From c3fba5592f279efef408b0764f624f92cdcdedcf Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Thu, 1 Aug 2024 12:03:24 +0200 Subject: [PATCH 03/30] Use ObjectDisposedException.ThrowIf --- .../src/Encryption/EncryptionResolverProvider.cs | 5 +---- .../src/Placeholder/PlaceholderResolverProvider.cs | 5 +---- src/Connectors/src/Connectors/Connector.cs | 9 +++------ .../src/Abstractions/Diagnostics/DiagnosticsManager.cs | 5 +---- 4 files changed, 6 insertions(+), 18 deletions(-) diff --git a/src/Configuration/src/Encryption/EncryptionResolverProvider.cs b/src/Configuration/src/Encryption/EncryptionResolverProvider.cs index 3a98c63dd3..9066c9f017 100644 --- a/src/Configuration/src/Encryption/EncryptionResolverProvider.cs +++ b/src/Configuration/src/Encryption/EncryptionResolverProvider.cs @@ -179,10 +179,7 @@ public IEnumerable GetChildKeys(IEnumerable earlierKeys, string? private void EnsureInitialized() { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(EncryptionResolverProvider)); - } + ObjectDisposedException.ThrowIf(_isDisposed, this); Configuration ??= new ConfigurationRoot(Providers); } diff --git a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs index 23b114b2d9..cf3ad94ba5 100644 --- a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs +++ b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs @@ -159,10 +159,7 @@ public IEnumerable GetChildKeys(IEnumerable earlierKeys, string? private void EnsureInitialized() { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(PlaceholderResolverProvider)); - } + ObjectDisposedException.ThrowIf(_isDisposed, this); Configuration ??= new ConfigurationRoot(Providers); } diff --git a/src/Connectors/src/Connectors/Connector.cs b/src/Connectors/src/Connectors/Connector.cs index 5ad6b298ac..d249cc234b 100644 --- a/src/Connectors/src/Connectors/Connector.cs +++ b/src/Connectors/src/Connectors/Connector.cs @@ -104,12 +104,9 @@ public TConnection GetConnection() lock (_singletonLock) { - if (_singletonIsDisposed) - { - // The connection itself is responsible for throwing when used after its disposal. - // However, there's no point in allocating the connection if we're already disposed. - throw new ObjectDisposedException(GetType().FullName); - } + // The connection itself is responsible for throwing when used after its disposal. + // However, there's no point in allocating the connection if we're already disposed. + ObjectDisposedException.ThrowIf(_singletonIsDisposed, this); if (_singletonSnapshot == null) { diff --git a/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs b/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs index 13559d6864..67c5e23a30 100755 --- a/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs +++ b/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs @@ -70,10 +70,7 @@ public void OnNext(DiagnosticListener value) public void Start() { - if (_isDisposed) - { - throw new ObjectDisposedException(GetType().Name); - } + ObjectDisposedException.ThrowIf(_isDisposed, this); if (Interlocked.CompareExchange(ref _started, 1, 0) == 0) { From fc11f63635d069cf339fb3a8ba08382ad48676b3 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Mon, 5 Aug 2024 09:28:11 +0200 Subject: [PATCH 04/30] Use ArgumentException.ThrowIf* instead of ArgumentGuard, and review usages: - File/directory name can consist of whitespace - Configuration key can consist of whitespace - Logger category name can consist of whitespace - Assembly/type/member name can NOT consist of whitespace - Hostname/url can NOT consist of whitespace - Eureka app-name/instance-ID/VIP-address can NOT consist of whitespace Use ToArray() instead of ToList(), which is slightly more efficient --- .../src/AutoConfiguration/BootstrapScanner.cs | 9 +-- .../HostApplicationBuilderExtensions.cs | 7 ++- .../HostBuilderExtensions.cs | 7 ++- .../WebHostBuilderExtensions.cs | 7 ++- .../CertificateConfigurationExtensions.cs | 9 +-- .../CertificateServiceCollectionExtensions.cs | 7 ++- .../ConfigureCertificateOptions.cs | 10 ++-- .../FilePathInOptionsChangeTokenSource.cs | 2 +- .../ServiceCollectionExtensions.cs | 6 +- src/Common/src/Common/ArgumentGuard.cs | 56 ++++--------------- src/Common/src/Common/AssemblyLoader.cs | 6 +- .../ConfigurationOptionsBinder.cs | 4 +- .../ConfigurationValuesHelper.cs | 27 ++++----- .../PropertyPlaceHolderHelper.cs | 6 +- .../Discovery/DiscoveryClientHostedService.cs | 7 ++- .../DynamicTypeAccess/InstanceAccessor.cs | 4 +- .../DynamicTypeAccess/PackageResolver.cs | 12 ++-- .../DynamicTypeAccess/ReflectionAccessor.cs | 25 ++++----- .../src/Common/DynamicTypeAccess/Shim.cs | 2 +- .../Common/DynamicTypeAccess/TypeAccessor.cs | 14 ++--- .../Common/Extensions/ExceptionExtensions.cs | 2 +- .../src/Common/Extensions/UriExtensions.cs | 4 +- .../Common/HealthChecks/HealthAggregator.cs | 17 ++---- src/Common/src/Common/Net/DnsTools.cs | 2 +- src/Common/src/Common/Net/HostInfo.cs | 4 +- src/Common/src/Common/Net/InetUtils.cs | 4 +- .../src/Common/Properties/AssemblyInfo.cs | 3 + .../src/Common/ValidatedNotNullAttribute.cs | 11 ---- .../src/Hosting/HostBuilderContextWrapper.cs | 6 +- src/Common/src/Hosting/HostBuilderWrapper.cs | 20 +++---- src/Common/src/Http/HttpClientExtensions.cs | 4 +- ...tCertificateHttpClientHandlerConfigurer.cs | 4 +- .../HttpClientHandlerFactory.cs | 2 +- ...CertificatesHttpClientHandlerConfigurer.cs | 2 +- .../src/Logging/BootstrapLoggerContext.cs | 2 +- .../Logging/BootstrapLoggerHostedService.cs | 9 ++- .../UpgradableBootstrapLoggerFactory.cs | 2 +- .../TestResources/CapturingLoggerProvider.cs | 2 +- .../test/TestResources/XunitLoggerProvider.cs | 2 +- .../src/Abstractions/BaseServiceOptions.cs | 7 +-- .../Abstractions/ConfigurationExtensions.cs | 3 +- .../PostProcessorConfigurationProvider.cs | 3 +- .../PostProcessorConfigurationSource.cs | 3 +- ...ndryServiceBindingConfigurationProvider.cs | 3 +- ...oundryServiceBindingConfigurationSource.cs | 5 +- .../ConfigurationBuilderExtensions.cs | 9 ++- .../JsonStreamConfigurationProvider.cs | 3 +- .../JsonStreamConfigurationSource.cs | 5 +- .../EurekaCloudFoundryPostProcessor.cs | 3 +- .../IdentityCloudFoundryPostProcessor.cs | 3 +- .../ServiceBindingMapper.cs | 7 +-- ...udFoundryConfigurationBuilderExtensions.cs | 5 +- .../CloudFoundryConfigurationProvider.cs | 3 +- .../CloudFoundryHostBuilderExtensions.cs | 7 +-- ...CloudFoundryServiceCollectionExtensions.cs | 18 +++--- .../CloudFoundryServicesOptions.cs | 3 +- .../HostBuilderWrapperExtensions.cs | 7 +-- .../JsonStreamConfigurationProvider.cs | 3 +- .../JsonStreamConfigurationSource.cs | 5 +- ...figServerConfigurationBuilderExtensions.cs | 9 ++- .../ConfigServerConfigurationProvider.cs | 13 ++--- .../ConfigServerConfigurationSource.cs | 13 ++--- .../ConfigServerDiscoveryService.cs | 8 +-- .../ConfigServerHealthContributor.cs | 5 +- .../ConfigServerHostBuilderExtensions.cs | 13 ++--- .../ConfigServer/ConfigServerHostedService.cs | 9 ++- ...ConfigServerServiceCollectionExtensions.cs | 7 +-- .../ConfigurationSettingsHelper.cs | 7 +-- .../HostBuilderWrapperExtensions.cs | 7 +-- .../src/ConfigServer/OptionsMonitorWrapper.cs | 3 +- .../src/Encryption/ConfigurationView.cs | 3 +- .../Encryption/Decryption/AesTextDecryptor.cs | 8 +-- .../ConfigServerEncryptionSettings.cs | 2 +- .../Decryption/ConfigurationSettingsHelper.cs | 5 +- .../src/Encryption/Decryption/KeyProvider.cs | 11 ++-- .../Decryption/RsaKeyStoreDecryptor.cs | 17 +++--- .../EncryptionConfigurationExtensions.cs | 19 +++---- .../EncryptionHostBuilderExtensions.cs | 13 ++--- .../Encryption/EncryptionResolverProvider.cs | 17 +++--- .../Encryption/EncryptionResolverSource.cs | 17 +++--- .../EncryptionServiceCollectionExtensions.cs | 18 +++--- .../HostBuilderWrapperExtensions.cs | 7 +-- .../ConfigurationBuilderExtensions.cs | 9 ++- ...rnetesServiceBindingConfigurationSource.cs | 5 +- .../ConfigurationBuilderExtensions.cs | 5 +- .../src/Placeholder/ConfigurationView.cs | 3 +- .../PlaceholderConfigurationExtensions.cs | 13 ++--- .../PlaceholderResolverProvider.cs | 13 ++--- .../Placeholder/PlaceholderResolverSource.cs | 13 ++--- .../PlaceholderServiceCollectionExtensions.cs | 7 +-- ...ndomValueConfigurationBuilderExtensions.cs | 5 +- .../src/RandomValue/RandomValueProvider.cs | 7 +-- .../src/RandomValue/RandomValueSource.cs | 3 +- .../SpringBootCommandLineProvider.cs | 3 +- .../SpringBoot/SpringBootCommandLineSource.cs | 3 +- ...pringBootConfigurationBuilderExtensions.cs | 11 ++-- .../SpringBootEnvironmentVariableProvider.cs | 3 +- .../HomeController.cs | 5 +- .../ForwardingHttpClientHandler.cs | 4 +- ...nStringPostProcessorConfigurationSource.cs | 3 +- src/Connectors/src/Connectors/Connector.cs | 11 ++-- .../Connectors/ConnectorAddOptionsBuilder.cs | 5 +- .../src/Connectors/ConnectorFactory.cs | 7 ++- .../CosmosDbConfigurationBuilderExtensions.cs | 3 +- .../CosmosDb/CosmosDbHealthContributor.cs | 15 +++-- ...osmosDbHostApplicationBuilderExtensions.cs | 3 +- .../CosmosDbServiceCollectionExtensions.cs | 7 +-- .../DynamicTypeAccess/CosmosClientShim.cs | 3 +- .../DbConnectionStringBuilderWrapper.cs | 3 +- .../DynamicTypeAccess/ConnectorFactoryShim.cs | 13 ++--- .../DynamicTypeAccess/ConnectorShim.cs | 5 +- .../DynamicTypeAccess/MongoClientShim.cs | 3 +- .../MongoDbConfigurationBuilderExtensions.cs | 3 +- .../MongoDb/MongoDbConnectionStringBuilder.cs | 5 +- .../MongoDb/MongoDbHealthContributor.cs | 15 +++-- ...MongoDbHostApplicationBuilderExtensions.cs | 3 +- .../MongoDbServiceCollectionExtensions.cs | 7 +-- .../DynamicTypeAccess/MySqlConnectionShim.cs | 3 +- .../MySqlConnectionStringBuilderShim.cs | 3 +- .../MySqlConfigurationBuilderExtensions.cs | 5 +- .../MySqlConnectionStringPostProcessor.cs | 3 +- .../MySqlHostApplicationBuilderExtensions.cs | 5 +- .../MySql/MySqlServiceCollectionExtensions.cs | 7 +-- .../DynamicTypeAccess/NpgsqlConnectionShim.cs | 3 +- .../NpgsqlConnectionStringBuilderShim.cs | 3 +- ...ostgreSqlConfigurationBuilderExtensions.cs | 5 +- ...PostgreSqlConnectionStringPostProcessor.cs | 3 +- ...tgreSqlHostApplicationBuilderExtensions.cs | 3 +- .../PostgreSqlServiceCollectionExtensions.cs | 7 +-- .../ConnectionFactoryShim.cs | 3 +- .../RabbitMQConfigurationBuilderExtensions.cs | 3 +- .../RabbitMQConnectionStringBuilder.cs | 5 +- .../RabbitMQ/RabbitMQHealthContributor.cs | 7 +-- ...abbitMQHostApplicationBuilderExtensions.cs | 3 +- .../RabbitMQServiceCollectionExtensions.cs | 7 +-- .../ConnectionMultiplexerShim.cs | 5 +- .../RedisCacheOptionsShim.cs | 5 +- .../Redis/DynamicTypeAccess/RedisCacheShim.cs | 5 +- .../RedisConfigurationBuilderExtensions.cs | 3 +- .../Redis/RedisConnectionStringBuilder.cs | 5 +- .../Redis/RedisHealthContributor.cs | 3 +- .../RedisHostApplicationBuilderExtensions.cs | 3 +- .../Redis/RedisServiceCollectionExtensions.cs | 9 ++- .../RelationalDatabaseHealthContributor.cs | 5 +- .../RuntimeTypeAccess/SqlConnectionShim.cs | 3 +- .../SqlConnectionStringBuilderShim.cs | 3 +- ...SqlServerConfigurationBuilderExtensions.cs | 5 +- .../SqlServerConnectionStringPostProcessor.cs | 3 +- ...lServerHostApplicationBuilderExtensions.cs | 5 +- .../SqlServerServiceCollectionExtensions.cs | 7 +-- .../MigrateDbContextTask.cs | 10 ++-- .../MySqlDbContextOptionsExtensionsShim.cs | 3 +- ...MySqlEntityFrameworkCorePackageResolver.cs | 2 +- .../DynamicTypeAccess/ServerVersionShim.cs | 3 +- .../MySqlDbContextOptionsBuilderExtensions.cs | 7 +-- ...qlDbContextOptionsBuilderExtensionsShim.cs | 3 +- ...greSqlDbContextOptionsBuilderExtensions.cs | 7 +-- ...SqlServerDbContextOptionsExtensionsShim.cs | 3 +- ...ServerDbContextOptionsBuilderExtensions.cs | 7 +-- .../Connectors.Test/MemoryFileProvider.cs | 25 ++++----- .../PostgreSql/PostgreSqlConnectorTests.cs | 2 +- .../ConfigurationDiscoveryClient.cs | 7 +-- ...onfigurationServiceCollectionExtensions.cs | 3 +- .../src/Consul/ConsulClientFactory.cs | 3 +- .../src/Consul/ConsulDiscoveryClient.cs | 15 +++-- .../src/Consul/ConsulHealthContributor.cs | 5 +- .../ConsulServiceCollectionExtensions.cs | 2 +- .../src/Consul/ConsulServiceInstance.cs | 3 +- src/Discovery/src/Consul/PeriodicHeartbeat.cs | 7 +-- .../PostConfigureConsulDiscoveryOptions.cs | 7 +-- .../src/Consul/Registry/ConsulRegistration.cs | 8 +-- .../Consul/Registry/ConsulServiceRegistrar.cs | 11 ++-- .../Consul/Registry/ConsulServiceRegistry.cs | 17 +++--- .../src/Consul/ThisServiceInstance.cs | 3 +- src/Discovery/src/Consul/TtlScheduler.cs | 11 ++-- .../src/Consul/Util/ConsulServerUtils.cs | 5 +- .../src/Consul/Util/DateTimeConversions.cs | 3 +- .../src/Consul/ValidateConsulOptions.cs | 4 +- .../src/Eureka/AppInfo/ApplicationInfo.cs | 10 ++-- .../AppInfo/ApplicationInfoCollection.cs | 16 +++--- .../src/Eureka/AppInfo/InstanceInfo.cs | 19 +++---- src/Discovery/src/Eureka/AppInfo/LeaseInfo.cs | 3 +- .../Eureka/ApplicationsFetchedEventArgs.cs | 3 +- .../DynamicPortAssignmentHostedService.cs | 15 +++-- .../Eureka/EurekaApplicationInfoManager.cs | 7 +-- .../EurekaApplicationsHealthContributor.cs | 9 ++- src/Discovery/src/Eureka/EurekaClient.cs | 20 +++---- .../src/Eureka/EurekaDiscoveryClient.cs | 19 +++---- .../src/Eureka/EurekaHealthCheckHandler.cs | 7 +-- .../EurekaHttpClientHandlerConfigurer.cs | 5 +- .../Eureka/EurekaServerHealthContributor.cs | 7 +-- .../EurekaServiceCollectionExtensions.cs | 3 +- .../src/Eureka/EurekaServiceInstance.cs | 3 +- .../Eureka/EurekaServiceUriStateManager.cs | 11 ++-- src/Discovery/src/Eureka/GatedAction.cs | 4 +- .../src/Eureka/HealthCheckHandlerProvider.cs | 3 +- .../src/Eureka/InstanceChangedEventArgs.cs | 5 +- .../PostConfigureEurekaInstanceOptions.cs | 10 ++-- .../src/Eureka/ValidateEurekaClientOptions.cs | 2 +- .../DiscoveryHttpClientBuilderExtensions.cs | 3 +- .../HttpClients/DiscoveryHttpClientHandler.cs | 5 +- .../DiscoveryHttpDelegatingHandler.cs | 5 +- .../LoadBalancers/RandomLoadBalancer.cs | 7 +-- .../LoadBalancers/RoundRobinLoadBalancer.cs | 7 +-- .../LoadBalancers/ServiceInstancesResolver.cs | 15 +++-- .../DiscoveryHttpClientHandlerTest.cs | 5 +- .../DiscoveryHttpDelegatingHandlerTest.cs | 5 +- .../LoadBalancers/FakeLoadBalancer.cs | 7 +-- .../DynamicLoggerConfiguration.cs | 3 +- .../src/Abstractions/DynamicLoggerProvider.cs | 21 ++++--- .../Abstractions/LoggerFilterConfiguration.cs | 5 +- .../Abstractions/MessageProcessingLogger.cs | 20 ++++--- .../src/Abstractions/PublicAPI.Unshipped.txt | 3 +- .../DynamicConsoleLoggerProvider.cs | 5 +- .../DynamicLogger/LoggingBuilderExtensions.cs | 2 +- .../DynamicSerilogLoggerProvider.cs | 7 +-- .../HostBuilderWrapperExtensions.cs | 3 +- .../SerilogConfigurationExtensions.cs | 5 +- ...SerilogHostApplicationBuilderExtensions.cs | 3 +- .../SerilogHostBuilderExtensions.cs | 3 +- .../SerilogLoggingBuilderExtensions.cs | 3 +- .../SerilogMessageProcessingLogger.cs | 8 +-- .../src/DynamicSerilog/SerilogOptions.cs | 5 +- .../SerilogWebHostBuilderExtensions.cs | 3 +- .../LoggerSinkConfigurationExtensions.cs | 3 +- .../Diagnostics/DiagnosticObserver.cs | 13 ++--- .../Diagnostics/DiagnosticsManager.cs | 25 ++++++--- .../Info/ConfigurationContributor.cs | 9 ++- .../src/Abstractions/Info/InfoBuilder.cs | 6 +- .../src/Endpoint/ActuatorConventionBuilder.cs | 5 +- .../src/Endpoint/ActuatorEndpointMapper.cs | 19 ++++--- .../src/Endpoint/ActuatorMediaTypes.cs | 5 +- .../ActuatorRouteBuilderExtensions.cs | 5 +- .../ActuatorServiceCollectionExtensions.cs | 10 ++-- .../src/Endpoint/AllActuatorsStartupFilter.cs | 2 +- .../CloudFoundryEndpointHandler.cs | 15 +++-- .../CloudFoundryEndpointMiddleware.cs | 3 +- .../CloudFoundrySecurityMiddleware.cs | 17 +++--- ...ndrySecurityServiceCollectionExtensions.cs | 3 +- .../ConfigureCloudFoundryEndpointOptions.cs | 3 +- .../EndpointApplicationBuilderExtensions.cs | 3 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../CloudFoundry/PermissionsProvider.cs | 13 ++--- .../Endpoint/CloudFoundry/SecurityResult.cs | 3 +- .../ServiceCollectionExtensions.cs | 3 +- .../ContentNegotiationExtensions.cs | 7 +-- .../DbMigrationsEndpointHandler.cs | 16 ++---- .../EndpointServiceCollectionExtensions.cs | 3 +- .../ServiceCollectionExtensions.cs | 3 +- .../Diagnostics/DiagnosticsService.cs | 5 +- .../src/Endpoint/EndpointOptionsExtensions.cs | 13 ++--- .../ConfigureEnvironmentEndpointOptions.cs | 3 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../Environment/EnvironmentEndpointHandler.cs | 13 ++--- .../Environment/EnvironmentResponse.cs | 5 +- .../Environment/PropertySourceDescriptor.cs | 5 +- .../src/Endpoint/Environment/Sanitizer.cs | 3 +- .../ServiceCollectionExtensions.cs | 3 +- .../Availability/ApplicationAvailability.cs | 3 +- .../Availability/AvailabilityEventArgs.cs | 4 +- .../AvailabilityHealthContributor.cs | 9 ++- .../Health/Availability/AvailabilityState.cs | 4 +- .../Availability/LivenessHealthContributor.cs | 3 +- .../ReadinessHealthContributor.cs | 3 +- .../Health/ConfigureHealthEndpointOptions.cs | 3 +- .../ConfigureDiskSpaceContributorOptions.cs | 5 +- .../Contributor/DiskSpaceContributor.cs | 3 +- .../EndpointServiceCollectionExtensions.cs | 9 ++- .../src/Endpoint/Health/HealthConverter.cs | 3 +- .../src/Endpoint/Health/HealthConverterV3.cs | 3 +- .../Endpoint/Health/HealthEndpointHandler.cs | 35 ++++++------ .../Health/HealthEndpointMiddleware.cs | 5 +- .../Endpoint/Health/HealthEndpointRequest.cs | 4 +- .../Endpoint/Health/HealthEndpointResponse.cs | 3 +- .../Health/ServiceCollectionExtensions.cs | 3 +- .../Health/ServiceProviderExtensions.cs | 3 +- .../ConfigureHeapDumpEndpointOptions.cs | 2 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../HeapDump/HeapDumpEndpointHandler.cs | 7 +-- .../src/Endpoint/HeapDump/HeapDumper.cs | 5 +- .../HeapDump/ServiceCollectionExtensions.cs | 3 +- .../Info/Contributor/BuildInfoContributor.cs | 3 +- .../Info/Contributor/GitInfoContributor.cs | 25 ++++----- .../EndpointServiceCollectionExtensions.cs | 7 ++- .../Info/EpochSecondsDateTimeConverter.cs | 3 +- .../src/Endpoint/Info/InfoEndpointHandler.cs | 11 ++-- .../Info/ServiceCollectionExtensions.cs | 3 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../Loggers/LoggersEndpointHandler.cs | 8 +-- .../src/Endpoint/Loggers/LoggersRequest.cs | 4 +- .../src/Endpoint/Loggers/LoggersResponse.cs | 4 +- .../Loggers/ServiceCollectionExtensions.cs | 3 +- ...agementHostApplicationBuilderExtensions.cs | 35 ++++++------ .../ManagementHostBuilderExtensions.cs | 35 ++++++------ .../Endpoint/ManagementOptionsExtensions.cs | 5 +- .../ManagementPortMiddleware.cs | 7 +-- .../ManagementPortStartupFilter.cs | 5 +- .../ManagementWebHostBuilderExtensions.cs | 35 ++++++------ .../ConfigureMetricsObserverOptions.cs | 5 +- .../EndpointServiceCollectionExtensions.cs | 5 +- .../Metrics/MetricCollectionHostedService.cs | 3 +- .../Endpoint/Metrics/MetricLabelExtensions.cs | 4 +- .../src/Endpoint/Metrics/MetricTag.cs | 5 +- .../Metrics/MetricsEndpointHandler.cs | 37 ++++++------ .../Metrics/MetricsEndpointMiddleware.cs | 5 +- .../src/Endpoint/Metrics/MetricsExporter.cs | 9 ++- .../src/Endpoint/Metrics/MetricsRequest.cs | 6 +- .../src/Endpoint/Metrics/MetricsResponse.cs | 11 ++-- .../Observer/AspNetCoreHostingObserver.cs | 8 +-- .../Metrics/Observer/ClrRuntimeObserver.cs | 3 +- .../Metrics/Observer/EventCounterListener.cs | 9 ++- .../Observer/HttpClientCoreObserver.cs | 2 +- .../Observer/HttpClientDesktopObserver.cs | 2 +- .../Metrics/ServiceCollectionExtensions.cs | 5 +- .../Endpoint/Middleware/EndpointMiddleware.cs | 13 ++--- .../Options/ConfigureEndpointOptions.cs | 9 ++- .../Options/ConfigureManagementOptions.cs | 13 ++--- .../src/Endpoint/PublicAPI.Unshipped.txt | 2 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../Refresh/RefreshEndpointHandler.cs | 7 +-- .../Refresh/ServiceCollectionExtensions.cs | 3 +- .../RouteMappings/AspNetCoreRouteDetails.cs | 17 ++++-- .../Endpoint/RouteMappings/ContextMappings.cs | 3 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../RouteMappings/MediaTypeDescriptor.cs | 3 +- .../RouteMappings/RequestMappingConditions.cs | 18 ++++-- .../RouteMappings/RouteBuilderExtensions.cs | 3 +- .../RouteMappings/RouteMappingDescription.cs | 11 ++-- .../RouteMappings/RouteMappingDetails.cs | 3 +- .../RouteMappingsEndpointHandler.cs | 26 +++++---- .../RouteMappings/RouteMappingsResponse.cs | 3 +- .../ServiceCollectionExtensions.cs | 3 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../Services/ServiceCollectionExtensions.cs | 3 +- .../Endpoint/Services/ServiceRegistration.cs | 3 +- .../Services/ServicesEndpointHandler.cs | 9 ++- .../SpringBootAdminClient/Application.cs | 11 ++-- .../ConfigureSpringBootAdminClientOptions.cs | 4 +- .../ServiceCollectionExtensions.cs | 3 +- .../SpringBootAdminClientHostedService.cs | 11 ++-- .../EndpointServiceCollectionExtensions.cs | 5 +- .../ThreadDump/EventPipeThreadDumper.cs | 5 +- .../ThreadDump/ServiceCollectionExtensions.cs | 3 +- .../ThreadDump/ThreadDumpEndpointHandler.cs | 7 +-- .../ThreadDump/ThreadDumpV2Converter.cs | 3 +- .../Trace/ConfigureTraceEndpointOptions.cs | 5 +- .../EndpointServiceCollectionExtensions.cs | 5 +- .../src/Endpoint/Trace/HttpTrace.cs | 6 +- .../Trace/HttpTraceDiagnosticObserver.cs | 5 +- .../Trace/HttpTraceEndpointHandler.cs | 7 +-- .../Trace/HttpTraceResultConverter.cs | 3 +- .../src/Endpoint/Trace/HttpTraceResultV1.cs | 3 +- .../src/Endpoint/Trace/HttpTraceResultV2.cs | 3 +- .../src/Endpoint/Trace/Principal.cs | 4 +- src/Management/src/Endpoint/Trace/Request.cs | 8 +-- src/Management/src/Endpoint/Trace/Response.cs | 4 +- .../Trace/ServiceCollectionExtensions.cs | 3 +- src/Management/src/Endpoint/Trace/Session.cs | 4 +- .../Endpoint/Trace/TraceDiagnosticObserver.cs | 23 ++++---- .../src/Endpoint/Trace/TraceResult.cs | 3 +- .../Web/Hypermedia/ActuatorEndpointHandler.cs | 15 +++-- .../ActuatorHypermediaEndpointMiddleware.cs | 3 +- .../EndpointServiceCollectionExtensions.cs | 3 +- .../Web/Hypermedia/HypermediaService.cs | 20 ++++--- .../src/Endpoint/Web/Hypermedia/Link.cs | 4 +- .../Hypermedia/ServiceCollectionExtensions.cs | 3 +- .../src/Prometheus/PrometheusExtensions.cs | 5 +- src/Management/src/Tasks/DelegatingTask.cs | 2 +- .../src/Tasks/TaskHostExtensions.cs | 4 +- .../Tasks/TaskServiceCollectionExtensions.cs | 22 ++++---- .../TracingBaseServiceCollectionExtensions.cs | 2 +- .../TracingCoreServiceCollectionExtensions.cs | 3 +- .../src/Tracing/TracingLogProcessor.cs | 5 +- src/Management/src/Tracing/TracingOptions.cs | 2 +- .../ConfigureWavefrontExporterOptions.cs | 5 +- .../Exporters/WavefrontMetricsExporter.cs | 5 +- .../Exporters/WavefrontTraceExporter.cs | 5 +- .../Exporters/WavefrontTraceExtensions.cs | 7 +-- .../src/Wavefront/WavefrontExtensions.cs | 5 +- .../Contributor/GitInfoContributorTest.cs | 16 +++--- .../Infrastructure/TestContext.cs | 3 +- .../Endpoint.Test/RouteMappings/Startup.cs | 3 +- ...wtBearerAuthenticationBuilderExtensions.cs | 3 +- .../PostConfigureJwtBearerOptions.cs | 5 +- .../TokenKeyResolver.cs | 5 +- ...dConnectAuthenticationBuilderExtensions.cs | 3 +- .../PostConfigureOpenIdConnectOptions.cs | 3 +- .../TokenKeyResolver.cs | 5 +- ...CertificateApplicationBuilderExtensions.cs | 5 +- ...rtificateAuthorizationBuilderExtensions.cs | 3 +- .../CertificateAuthorizationHandler.cs | 7 +-- ...ateAuthorizationPolicyBuilderExtensions.cs | 5 +- .../CertificateHttpClientBuilderExtensions.cs | 5 +- ...nfigureCertificateAuthenticationOptions.cs | 7 +-- .../CloudFoundryRedisXmlRepository.cs | 3 +- .../RedisDataProtectionBuilderExtensions.cs | 3 +- src/Steeltoe.All.sln.DotSettings | 30 +++------- 397 files changed, 1236 insertions(+), 1550 deletions(-) delete mode 100644 src/Common/src/Common/ValidatedNotNullAttribute.cs diff --git a/src/Bootstrap/src/AutoConfiguration/BootstrapScanner.cs b/src/Bootstrap/src/AutoConfiguration/BootstrapScanner.cs index d3d6192416..41ad2c47fc 100644 --- a/src/Bootstrap/src/AutoConfiguration/BootstrapScanner.cs +++ b/src/Bootstrap/src/AutoConfiguration/BootstrapScanner.cs @@ -47,9 +47,10 @@ internal sealed class BootstrapScanner public BootstrapScanner(HostBuilderWrapper wrapper, IReadOnlySet assemblyNamesToExclude, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(wrapper); - ArgumentGuard.NotNull(assemblyNamesToExclude); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(wrapper); + ArgumentNullException.ThrowIfNull(assemblyNamesToExclude); + ArgumentGuard.ElementsNotNullOrWhiteSpace(assemblyNamesToExclude); + ArgumentNullException.ThrowIfNull(loggerFactory); _wrapper = wrapper; _loader = new AssemblyLoader(assemblyNamesToExclude); @@ -61,7 +62,7 @@ public void ConfigureSteeltoe() { if (_loggerFactory is IBootstrapLoggerFactory) { - BootstrapLoggerHostedService.Register(_loggerFactory, _wrapper); + BootstrapLoggerHostedService.Register(_wrapper); } if (!WireIfLoaded(WireConfigServer, SteeltoeAssemblyNames.ConfigurationConfigServer)) diff --git a/src/Bootstrap/src/AutoConfiguration/HostApplicationBuilderExtensions.cs b/src/Bootstrap/src/AutoConfiguration/HostApplicationBuilderExtensions.cs index 589222f0c4..256eca8e9f 100644 --- a/src/Bootstrap/src/AutoConfiguration/HostApplicationBuilderExtensions.cs +++ b/src/Bootstrap/src/AutoConfiguration/HostApplicationBuilderExtensions.cs @@ -84,9 +84,10 @@ public static IHostApplicationBuilder AddSteeltoe(this IHostApplicationBuilder b public static IHostApplicationBuilder AddSteeltoe(this IHostApplicationBuilder builder, IReadOnlySet assemblyNamesToExclude, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(assemblyNamesToExclude); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(assemblyNamesToExclude); + ArgumentGuard.ElementsNotNullOrWhiteSpace(assemblyNamesToExclude); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); diff --git a/src/Bootstrap/src/AutoConfiguration/HostBuilderExtensions.cs b/src/Bootstrap/src/AutoConfiguration/HostBuilderExtensions.cs index 30b5b4081d..aafaf45484 100644 --- a/src/Bootstrap/src/AutoConfiguration/HostBuilderExtensions.cs +++ b/src/Bootstrap/src/AutoConfiguration/HostBuilderExtensions.cs @@ -83,9 +83,10 @@ public static IHostBuilder AddSteeltoe(this IHostBuilder builder, ILoggerFactory /// public static IHostBuilder AddSteeltoe(this IHostBuilder builder, IReadOnlySet assemblyNamesToExclude, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(assemblyNamesToExclude); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(assemblyNamesToExclude); + ArgumentGuard.ElementsNotNullOrWhiteSpace(assemblyNamesToExclude); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); diff --git a/src/Bootstrap/src/AutoConfiguration/WebHostBuilderExtensions.cs b/src/Bootstrap/src/AutoConfiguration/WebHostBuilderExtensions.cs index cce9d918c0..70deab722a 100644 --- a/src/Bootstrap/src/AutoConfiguration/WebHostBuilderExtensions.cs +++ b/src/Bootstrap/src/AutoConfiguration/WebHostBuilderExtensions.cs @@ -83,9 +83,10 @@ public static IWebHostBuilder AddSteeltoe(this IWebHostBuilder builder, ILoggerF /// public static IWebHostBuilder AddSteeltoe(this IWebHostBuilder builder, IReadOnlySet assemblyNamesToExclude, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(assemblyNamesToExclude); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(assemblyNamesToExclude); + ArgumentGuard.ElementsNotNullOrWhiteSpace(assemblyNamesToExclude); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); diff --git a/src/Common/src/Certificates/CertificateConfigurationExtensions.cs b/src/Common/src/Certificates/CertificateConfigurationExtensions.cs index 4d26b0c504..1b49c3bbf7 100644 --- a/src/Common/src/Certificates/CertificateConfigurationExtensions.cs +++ b/src/Common/src/Certificates/CertificateConfigurationExtensions.cs @@ -29,10 +29,11 @@ public static class CertificateConfigurationExtensions internal static IConfigurationBuilder AddCertificate(this IConfigurationBuilder builder, string certificateName, string certificateFilePath, string? privateKeyFilePath = null) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNullOrEmpty(certificateFilePath); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(certificateName); + ArgumentException.ThrowIfNullOrEmpty(certificateFilePath); - string keyPrefix = string.IsNullOrEmpty(certificateName) + string keyPrefix = certificateName == string.Empty ? $"{CertificateOptions.ConfigurationKeyPrefix}{ConfigurationPath.KeyDelimiter}" : $"{CertificateOptions.ConfigurationKeyPrefix}{ConfigurationPath.KeyDelimiter}{certificateName}{ConfigurationPath.KeyDelimiter}"; @@ -85,7 +86,7 @@ public static IConfigurationBuilder AddAppInstanceIdentityCertificate(this IConf /// public static IConfigurationBuilder AddAppInstanceIdentityCertificate(this IConfigurationBuilder builder, Guid? organizationId, Guid? spaceId) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (!Platform.IsCloudFoundry) { diff --git a/src/Common/src/Certificates/CertificateServiceCollectionExtensions.cs b/src/Common/src/Certificates/CertificateServiceCollectionExtensions.cs index b15daf9468..d1bf2565da 100644 --- a/src/Common/src/Certificates/CertificateServiceCollectionExtensions.cs +++ b/src/Common/src/Certificates/CertificateServiceCollectionExtensions.cs @@ -21,11 +21,12 @@ public static class CertificateServiceCollectionExtensions /// /// Name of the certificate used in configuration and IOptions, or for an unnamed certificate. /// - public static IServiceCollection ConfigureCertificateOptions(this IServiceCollection services, string? certificateName) + public static IServiceCollection ConfigureCertificateOptions(this IServiceCollection services, string certificateName) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(certificateName); - string configurationKey = string.IsNullOrEmpty(certificateName) + string configurationKey = certificateName == string.Empty ? CertificateOptions.ConfigurationKeyPrefix : ConfigurationPath.Combine(CertificateOptions.ConfigurationKeyPrefix, certificateName); diff --git a/src/Common/src/Certificates/ConfigureCertificateOptions.cs b/src/Common/src/Certificates/ConfigureCertificateOptions.cs index 310fca69a8..784d48bbdf 100644 --- a/src/Common/src/Certificates/ConfigureCertificateOptions.cs +++ b/src/Common/src/Certificates/ConfigureCertificateOptions.cs @@ -20,7 +20,7 @@ internal sealed class ConfigureCertificateOptions : IConfigureNamedOptions(GetConfigurationKey(name, "CertificateFilePath")); @@ -47,10 +47,10 @@ public void Configure(string? name, CertificateOptions options) ? X509Certificate2.CreateFromPemFile(certificateFilePath, privateKeyFilePath) : new X509Certificate2(certificateFilePath); - List certChain = CertificateRegex.Matches(File.ReadAllText(certificateFilePath)) - .Select(x => new X509Certificate2(Encoding.ASCII.GetBytes(x.Value))).ToList(); + X509Certificate2[] certificateChain = CertificateRegex.Matches(File.ReadAllText(certificateFilePath)) + .Select(x => new X509Certificate2(Encoding.ASCII.GetBytes(x.Value))).ToArray(); - foreach (X509Certificate2 issuer in certChain.Skip(1)) + foreach (X509Certificate2 issuer in certificateChain.Skip(1)) { options.IssuerChain.Add(issuer); } diff --git a/src/Common/src/Certificates/FilePathInOptionsChangeTokenSource.cs b/src/Common/src/Certificates/FilePathInOptionsChangeTokenSource.cs index 37ac0b1dd8..ddf7cc1aa7 100644 --- a/src/Common/src/Certificates/FilePathInOptionsChangeTokenSource.cs +++ b/src/Common/src/Certificates/FilePathInOptionsChangeTokenSource.cs @@ -20,7 +20,7 @@ internal sealed class FilePathInOptionsChangeTokenSource : IOptionsChangeToke public FilePathInOptionsChangeTokenSource(string? optionName, string filePath) { - ArgumentGuard.NotNull(filePath); + ArgumentNullException.ThrowIfNull(filePath); Name = optionName ?? Options.DefaultName; _filePath = filePath; diff --git a/src/Common/src/Certificates/ServiceCollectionExtensions.cs b/src/Common/src/Certificates/ServiceCollectionExtensions.cs index 9f248c0aee..b99ef14c29 100644 --- a/src/Common/src/Certificates/ServiceCollectionExtensions.cs +++ b/src/Common/src/Certificates/ServiceCollectionExtensions.cs @@ -34,9 +34,9 @@ internal static class ServiceCollectionExtensions /// public static IServiceCollection WatchFilePathInOptions(this IServiceCollection services, string key, string? optionName, string pathPropertyName) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(key); - ArgumentGuard.NotNull(pathPropertyName); + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrEmpty(key); + ArgumentException.ThrowIfNullOrEmpty(pathPropertyName); services.AddSingleton>(serviceProvider => { diff --git a/src/Common/src/Common/ArgumentGuard.cs b/src/Common/src/Common/ArgumentGuard.cs index 93a749792b..09b489adfa 100644 --- a/src/Common/src/Common/ArgumentGuard.cs +++ b/src/Common/src/Common/ArgumentGuard.cs @@ -5,74 +5,40 @@ #nullable enable using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Steeltoe.Common; -public static class ArgumentGuard +internal static class ArgumentGuard { - public static void NotNull([ValidatedNotNull] [NotNull] T? value, [CallerArgumentExpression("value")] string? parameterName = null) - { - AssertNoDotInParameterName(parameterName); - - ArgumentNullException.ThrowIfNull(value, parameterName); - } - - public static void NotNullOrEmpty([ValidatedNotNull] [NotNull] IEnumerable? value, [CallerArgumentExpression("value")] string? parameterName = null) - { - AssertNoDotInParameterName(parameterName); - - ArgumentNullException.ThrowIfNull(value, parameterName); - - if (!value.Any()) - { - throw new ArgumentException("Collection cannot be empty.", parameterName); - } - } - - public static void NotNullOrEmpty([ValidatedNotNull] [NotNull] string? value, [CallerArgumentExpression("value")] string? parameterName = null) - { - AssertNoDotInParameterName(parameterName); - - ArgumentNullException.ThrowIfNull(value, parameterName); - - if (value == string.Empty) - { - throw new ArgumentException("String cannot be empty.", parameterName); - } - } - - public static void NotNullOrWhiteSpace([ValidatedNotNull] [NotNull] string? value, [CallerArgumentExpression("value")] string? parameterName = null) + public static void ElementsNotNull(IEnumerable? elements, [CallerArgumentExpression("elements")] string? parameterName = null) + where T : class { AssertNoDotInParameterName(parameterName); - ArgumentNullException.ThrowIfNull(value, parameterName); - - if (string.IsNullOrWhiteSpace(value)) + if (elements != null && elements.Any(element => element == null)) { - throw new ArgumentException("String cannot be empty or contain only whitespace.", parameterName); + throw new ArgumentException("Collection element cannot be null.", parameterName); } } - public static void ElementsNotNull(IEnumerable? elements, [CallerArgumentExpression("elements")] string? parameterName = null) - where T : class + public static void ElementsNotNullOrEmpty(IEnumerable? elements, [CallerArgumentExpression("elements")] string? parameterName = null) { AssertNoDotInParameterName(parameterName); - if (elements != null && elements.Any(element => element == null)) + if (elements != null && elements.Any(string.IsNullOrEmpty)) { - throw new ArgumentException("Collection cannot contain nulls.", parameterName); + throw new ArgumentException("Collection element cannot be null or an empty string.", parameterName); } } - public static void ElementsNotNullOrEmpty(IEnumerable? elements, [CallerArgumentExpression("elements")] string? parameterName = null) + public static void ElementsNotNullOrWhiteSpace(IEnumerable? elements, [CallerArgumentExpression("elements")] string? parameterName = null) { AssertNoDotInParameterName(parameterName); - if (elements != null && elements.Any(string.IsNullOrEmpty)) + if (elements != null && elements.Any(string.IsNullOrWhiteSpace)) { - throw new ArgumentException("Collection cannot contain nulls or empty strings.", parameterName); + throw new ArgumentException("Collection element cannot be null, an empty string, or composed entirely of whitespace.", parameterName); } } diff --git a/src/Common/src/Common/AssemblyLoader.cs b/src/Common/src/Common/AssemblyLoader.cs index ebc9218f86..53eabb60ad 100644 --- a/src/Common/src/Common/AssemblyLoader.cs +++ b/src/Common/src/Common/AssemblyLoader.cs @@ -26,8 +26,8 @@ public AssemblyLoader() public AssemblyLoader(IReadOnlySet assemblyNamesToExclude) { - ArgumentGuard.NotNull(assemblyNamesToExclude); - ArgumentGuard.ElementsNotNullOrEmpty(assemblyNamesToExclude); + ArgumentNullException.ThrowIfNull(assemblyNamesToExclude); + ArgumentGuard.ElementsNotNullOrWhiteSpace(assemblyNamesToExclude); // Take a copy to ensure comparisons are case-insensitive. AssemblyNamesToExclude = assemblyNamesToExclude.ToHashSet(StringComparer.OrdinalIgnoreCase); @@ -35,7 +35,7 @@ public AssemblyLoader(IReadOnlySet assemblyNamesToExclude) public bool IsAssemblyLoaded(string assemblyName) { - ArgumentGuard.NotNullOrEmpty(assemblyName); + ArgumentException.ThrowIfNullOrWhiteSpace(assemblyName); if (AssemblyNamesToExclude.Contains(assemblyName)) { diff --git a/src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs b/src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs index c225f41482..7869ad4e6c 100644 --- a/src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs +++ b/src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs @@ -33,8 +33,8 @@ public static void ConfigureReloadableOptions(this IServiceCollection Action? configureAction = null) where TOptions : class { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configurationKey); + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrEmpty(configurationKey); OptionsBuilder builder = services.AddOptions(); diff --git a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs index b7c24e2104..7f2f75bdb4 100644 --- a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs +++ b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs @@ -53,9 +53,10 @@ internal static class ConfigurationValuesHelper /// public static string? GetSetting(string key, IConfiguration configuration, string? defaultValue, params string[] sectionPrefixes) { - ArgumentGuard.NotNull(key); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(sectionPrefixes); + ArgumentException.ThrowIfNullOrEmpty(key); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(sectionPrefixes); + ArgumentGuard.ElementsNotNullOrEmpty(sectionPrefixes); foreach (string prefix in sectionPrefixes) { @@ -88,8 +89,8 @@ internal static class ConfigurationValuesHelper /// public static string? GetPreferredSetting(IConfiguration configuration, string? defaultValue, params string?[] configurationKeys) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(configurationKeys); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(configurationKeys); foreach (string key in configurationKeys.Where(key => !string.IsNullOrEmpty(key)).Cast()) { @@ -106,8 +107,8 @@ internal static class ConfigurationValuesHelper public static int GetInt32(string key, IConfiguration configuration, IConfiguration? resolve, int defaultValue) { - ArgumentGuard.NotNullOrEmpty(key); - ArgumentGuard.NotNull(configuration); + ArgumentException.ThrowIfNullOrEmpty(key); + ArgumentNullException.ThrowIfNull(configuration); string? value = GetString(key, configuration, resolve, null); @@ -121,8 +122,8 @@ public static int GetInt32(string key, IConfiguration configuration, IConfigurat public static double GetDouble(string key, IConfiguration configuration, IConfiguration? resolve, double defaultValue) { - ArgumentGuard.NotNullOrEmpty(key); - ArgumentGuard.NotNull(configuration); + ArgumentException.ThrowIfNullOrEmpty(key); + ArgumentNullException.ThrowIfNull(configuration); string? value = GetString(key, configuration, resolve, null); @@ -137,8 +138,8 @@ public static double GetDouble(string key, IConfiguration configuration, IConfig public static bool GetBoolean(string key, IConfiguration configuration, IConfiguration? resolve, bool defaultValue) { - ArgumentGuard.NotNullOrEmpty(key); - ArgumentGuard.NotNull(configuration); + ArgumentException.ThrowIfNullOrEmpty(key); + ArgumentNullException.ThrowIfNull(configuration); string? value = GetString(key, configuration, resolve, null); @@ -152,8 +153,8 @@ public static bool GetBoolean(string key, IConfiguration configuration, IConfigu public static string? GetString(string key, IConfiguration configuration, IConfiguration? resolve, string? defaultValue) { - ArgumentGuard.NotNullOrEmpty(key); - ArgumentGuard.NotNull(configuration); + ArgumentException.ThrowIfNullOrEmpty(key); + ArgumentNullException.ThrowIfNull(configuration); string? value = configuration[key]; diff --git a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs index 7cfa6cdbd2..9880e791ad 100644 --- a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs +++ b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs @@ -52,7 +52,7 @@ internal static class PropertyPlaceholderHelper /// public static string? ResolvePlaceholders(string? property, IConfiguration? configuration, ILogger logger) { - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(logger); return ParseStringValue(property, configuration, false, new HashSet(), logger); } @@ -74,8 +74,8 @@ internal static class PropertyPlaceholderHelper /// public static IDictionary GetResolvedConfigurationPlaceholders(IConfiguration configuration, ILogger logger) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(logger); // setup a holding tank for resolved values var resolvedValues = new Dictionary(); diff --git a/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs b/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs index a7a727cbae..093dfde822 100644 --- a/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs +++ b/src/Common/src/Common/Discovery/DiscoveryClientHostedService.cs @@ -15,9 +15,12 @@ internal sealed class DiscoveryClientHostedService : IHostedService public DiscoveryClientHostedService(IEnumerable discoveryClients) { - ArgumentGuard.NotNull(discoveryClients); + ArgumentNullException.ThrowIfNull(discoveryClients); - _discoveryClients = discoveryClients.ToArray(); + IDiscoveryClient[] discoveryClientArray = discoveryClients.ToArray(); + ArgumentGuard.ElementsNotNull(discoveryClientArray); + + _discoveryClients = discoveryClientArray; } public Task StartAsync(CancellationToken cancellationToken) diff --git a/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs b/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs index 29bd89b18b..3f992f1ad4 100644 --- a/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs +++ b/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs @@ -17,7 +17,7 @@ internal sealed class InstanceAccessor : ReflectionAccessor public InstanceAccessor(TypeAccessor declaredTypeAccessor, object instance) : base(AssertNotNull(declaredTypeAccessor)) { - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(instance); if (!declaredTypeAccessor.Type.IsInstanceOfType(instance)) { @@ -30,7 +30,7 @@ public InstanceAccessor(TypeAccessor declaredTypeAccessor, object instance) private static Type AssertNotNull(TypeAccessor declaredTypeAccessor) { - ArgumentGuard.NotNull(declaredTypeAccessor); + ArgumentNullException.ThrowIfNull(declaredTypeAccessor); return declaredTypeAccessor.Type; } diff --git a/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs b/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs index 571f16d5bd..7b2f67c7f0 100644 --- a/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs +++ b/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs @@ -32,10 +32,10 @@ protected PackageResolver(string assemblyName, string packageName) protected PackageResolver(IReadOnlyList assemblyNames, IReadOnlyList packageNames) { - ArgumentGuard.NotNull(assemblyNames); - ArgumentGuard.ElementsNotNullOrEmpty(assemblyNames); - ArgumentGuard.NotNull(packageNames); - ArgumentGuard.ElementsNotNullOrEmpty(packageNames); + ArgumentNullException.ThrowIfNull(assemblyNames); + ArgumentGuard.ElementsNotNullOrWhiteSpace(assemblyNames); + ArgumentNullException.ThrowIfNull(packageNames); + ArgumentGuard.ElementsNotNullOrWhiteSpace(packageNames); _assemblyNames = assemblyNames; _packageNames = packageNames; @@ -74,8 +74,8 @@ protected virtual bool IsAssemblyAvailable(IReadOnlySet assemblyNamesToE protected TypeAccessor ResolveType(params string[] typeNames) { - ArgumentGuard.NotNull(typeNames); - ArgumentGuard.ElementsNotNullOrEmpty(typeNames); + ArgumentNullException.ThrowIfNull(typeNames); + ArgumentGuard.ElementsNotNullOrWhiteSpace(typeNames); List exceptions = new(); diff --git a/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs b/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs index 74b63cda5e..322e933855 100644 --- a/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs +++ b/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs @@ -17,14 +17,14 @@ internal abstract class ReflectionAccessor protected ReflectionAccessor(Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); _type = type; } protected T GetPrivateFieldValue(string name, object? instance) { - ArgumentGuard.NotNullOrEmpty(name); + ArgumentException.ThrowIfNullOrWhiteSpace(name); object? value = GetPrivateFieldValue(name, instance); return (T)value!; @@ -51,7 +51,7 @@ private FieldInfo GetField(string name, bool isPublic, bool isStatic) protected T GetPropertyValue(string name, object? instance) { - ArgumentGuard.NotNullOrEmpty(name); + ArgumentException.ThrowIfNullOrWhiteSpace(name); object? value = GetPropertyValue(name, instance); return (T)value!; @@ -60,7 +60,7 @@ protected T GetPropertyValue(string name, object? instance) private object? GetPropertyValue(string name, object? instance) { MethodInfo propertySetter = GetPropertyGetter(name); - return propertySetter.Invoke(instance, Array.Empty()); + return propertySetter.Invoke(instance, []); } private MethodInfo GetPropertyGetter(string name) @@ -77,14 +77,11 @@ private MethodInfo GetPropertyGetter(string name) protected void SetPropertyValue(string name, object? instance, object? value) { - ArgumentGuard.NotNullOrEmpty(name); + ArgumentException.ThrowIfNullOrWhiteSpace(name); MethodInfo propertySetter = GetPropertySetter(name); - propertySetter.Invoke(instance, new[] - { - value - }); + propertySetter.Invoke(instance, [value]); } private MethodInfo GetPropertySetter(string name) @@ -113,8 +110,8 @@ private PropertyInfo GetProperty(string name) protected object? InvokeMethod(string name, bool isPublic, object? instance, object?[] arguments) { - ArgumentGuard.NotNullOrEmpty(name); - ArgumentGuard.NotNull(arguments); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(arguments); MethodInfo methodInfo = GetMethod(name, isPublic, instance == null, null); return methodInfo.Invoke(instance, arguments); @@ -122,10 +119,10 @@ private PropertyInfo GetProperty(string name) protected object? InvokeMethodOverload(string name, bool isPublic, Type[] parameterTypes, object? instance, object?[] arguments) { - ArgumentGuard.NotNullOrEmpty(name); - ArgumentGuard.NotNull(parameterTypes); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(parameterTypes); ArgumentGuard.ElementsNotNull(parameterTypes); - ArgumentGuard.NotNull(arguments); + ArgumentNullException.ThrowIfNull(arguments); MethodInfo methodInfo = GetMethod(name, isPublic, instance == null, parameterTypes); return methodInfo.Invoke(instance, arguments); diff --git a/src/Common/src/Common/DynamicTypeAccess/Shim.cs b/src/Common/src/Common/DynamicTypeAccess/Shim.cs index e65ec19919..e91d55c941 100644 --- a/src/Common/src/Common/DynamicTypeAccess/Shim.cs +++ b/src/Common/src/Common/DynamicTypeAccess/Shim.cs @@ -18,7 +18,7 @@ internal abstract class Shim protected Shim(InstanceAccessor instanceAccessor) { - ArgumentGuard.NotNull(instanceAccessor); + ArgumentNullException.ThrowIfNull(instanceAccessor); InstanceAccessor = instanceAccessor; } diff --git a/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs b/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs index eb498fcef8..37792fb428 100644 --- a/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs +++ b/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs @@ -9,19 +9,15 @@ namespace Steeltoe.Common.DynamicTypeAccess; /// /// Provides reflection-based access to static members of a . /// -internal sealed class TypeAccessor : ReflectionAccessor +internal sealed class TypeAccessor(Type type) : ReflectionAccessor(type) { - public Type Type { get; } - - public TypeAccessor(Type type) - : base(type) - { - Type = type; - } + public Type Type { get; } = type; public static TypeAccessor MakeGenericAccessor(Type openType, params Type[] typeArguments) { - ArgumentGuard.NotNull(openType); + ArgumentNullException.ThrowIfNull(openType); + ArgumentNullException.ThrowIfNull(typeArguments); + ArgumentGuard.ElementsNotNull(typeArguments); Type constructedType = openType.MakeGenericType(typeArguments); return new TypeAccessor(constructedType); diff --git a/src/Common/src/Common/Extensions/ExceptionExtensions.cs b/src/Common/src/Common/Extensions/ExceptionExtensions.cs index 23535c6ee2..f4318f5e01 100644 --- a/src/Common/src/Common/Extensions/ExceptionExtensions.cs +++ b/src/Common/src/Common/Extensions/ExceptionExtensions.cs @@ -22,7 +22,7 @@ public static class ExceptionExtensions /// public static Exception UnwrapAll(this Exception exception) { - ArgumentGuard.NotNull(exception); + ArgumentNullException.ThrowIfNull(exception); bool hasChanges = true; diff --git a/src/Common/src/Common/Extensions/UriExtensions.cs b/src/Common/src/Common/Extensions/UriExtensions.cs index 8ce24e7ee6..c36a405ddb 100644 --- a/src/Common/src/Common/Extensions/UriExtensions.cs +++ b/src/Common/src/Common/Extensions/UriExtensions.cs @@ -13,7 +13,7 @@ internal static class UriExtensions { public static string ToMaskedString(this Uri source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); string uris = source.ToString(); @@ -44,7 +44,7 @@ private static Uri ToMaskedUri(Uri source) public static bool TryGetUsernamePassword(this Uri uri, [NotNullWhen(true)] out string? username, [NotNullWhen(true)] out string? password) { - ArgumentGuard.NotNull(uri); + ArgumentNullException.ThrowIfNull(uri); string userInfo = uri.GetComponents(UriComponents.UserInfo, UriFormat.UriEscaped); diff --git a/src/Common/src/Common/HealthChecks/HealthAggregator.cs b/src/Common/src/Common/HealthChecks/HealthAggregator.cs index e1f670fc12..c96d631b2c 100644 --- a/src/Common/src/Common/HealthChecks/HealthAggregator.cs +++ b/src/Common/src/Common/HealthChecks/HealthAggregator.cs @@ -20,9 +20,9 @@ internal sealed class HealthAggregator : IHealthAggregator public async Task AggregateAsync(ICollection contributors, ICollection healthCheckRegistrations, IServiceProvider serviceProvider, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(contributors); - ArgumentGuard.NotNull(healthCheckRegistrations); - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(contributors); + ArgumentNullException.ThrowIfNull(healthCheckRegistrations); + ArgumentNullException.ThrowIfNull(serviceProvider); SteeltoeHealthCheckResult contributorsResult = await AggregateHealthContributorsAsync(contributors, cancellationToken); @@ -35,8 +35,6 @@ public async Task AggregateAsync(ICollection AggregateHealthContributorsAsync(ICollection contributors, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(contributors); - if (contributors.Count == 0) { return new SteeltoeHealthCheckResult(); @@ -44,11 +42,11 @@ private async Task AggregateHealthContributorsAsync(I var aggregatorResult = new SteeltoeHealthCheckResult(); var healthChecks = new ConcurrentDictionary(); - var keyList = new ConcurrentBag(); + var keys = new ConcurrentBag(); await Parallel.ForEachAsync(contributors, cancellationToken, async (contributor, _) => { - string contributorId = GetKey(keyList, contributor.Id); + string contributorId = GetKey(keys, contributor.Id); SteeltoeHealthCheckResult? healthCheckResult; try @@ -159,8 +157,6 @@ private static SteeltoeHealthStatus ToHealthStatus(MicrosoftHealthStatus status) private static string GetKey(ConcurrentBag keys, string key) { - ArgumentGuard.NotNull(keys); - lock (keys) { // add the contributor with a -n appended to the id @@ -178,9 +174,6 @@ private static string GetKey(ConcurrentBag keys, string key) private static SteeltoeHealthCheckResult AddChecksSetStatus(SteeltoeHealthCheckResult result, IDictionary healthChecks) { - ArgumentGuard.NotNull(result); - ArgumentGuard.NotNull(healthChecks); - foreach (KeyValuePair healthCheck in healthChecks) { if (healthCheck.Value.Status > result.Status) diff --git a/src/Common/src/Common/Net/DnsTools.cs b/src/Common/src/Common/Net/DnsTools.cs index 69be5f5158..565b9d1df9 100644 --- a/src/Common/src/Common/Net/DnsTools.cs +++ b/src/Common/src/Common/Net/DnsTools.cs @@ -22,7 +22,7 @@ internal static class DnsTools /// public static string? ResolveHostAddress(string hostName) { - ArgumentGuard.NotNull(hostName); + ArgumentException.ThrowIfNullOrWhiteSpace(hostName); try { diff --git a/src/Common/src/Common/Net/HostInfo.cs b/src/Common/src/Common/Net/HostInfo.cs index b1eaf11521..40867f50c9 100644 --- a/src/Common/src/Common/Net/HostInfo.cs +++ b/src/Common/src/Common/Net/HostInfo.cs @@ -13,8 +13,8 @@ internal sealed class HostInfo public HostInfo(string hostname, string ipAddress) { - ArgumentGuard.NotNull(hostname); - ArgumentGuard.NotNull(ipAddress); + ArgumentException.ThrowIfNullOrWhiteSpace(hostname); + ArgumentException.ThrowIfNullOrWhiteSpace(ipAddress); Hostname = hostname; IPAddress = ipAddress; diff --git a/src/Common/src/Common/Net/InetUtils.cs b/src/Common/src/Common/Net/InetUtils.cs index 4b28de896f..f3f258fcb9 100644 --- a/src/Common/src/Common/Net/InetUtils.cs +++ b/src/Common/src/Common/Net/InetUtils.cs @@ -22,8 +22,8 @@ internal class InetUtils public InetUtils(IOptionsMonitor optionsMonitor, ILogger logger) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _optionsMonitor = optionsMonitor; _logger = logger; diff --git a/src/Common/src/Common/Properties/AssemblyInfo.cs b/src/Common/src/Common/Properties/AssemblyInfo.cs index f3197b7feb..4749c1afb8 100644 --- a/src/Common/src/Common/Properties/AssemblyInfo.cs +++ b/src/Common/src/Common/Properties/AssemblyInfo.cs @@ -25,8 +25,11 @@ [assembly: InternalsVisibleTo("Steeltoe.Discovery.Consul.Test")] [assembly: InternalsVisibleTo("Steeltoe.Discovery.Eureka")] [assembly: InternalsVisibleTo("Steeltoe.Discovery.Eureka.Test")] +[assembly: InternalsVisibleTo("Steeltoe.Discovery.HttpClients")] [assembly: InternalsVisibleTo("Steeltoe.Discovery.HttpClients.Test")] +[assembly: InternalsVisibleTo("Steeltoe.Logging.Abstractions")] [assembly: InternalsVisibleTo("Steeltoe.Logging.DynamicSerilog")] +[assembly: InternalsVisibleTo("Steeltoe.Management.Abstractions")] [assembly: InternalsVisibleTo("Steeltoe.Management.Endpoint")] [assembly: InternalsVisibleTo("Steeltoe.Management.Endpoint.Test")] [assembly: InternalsVisibleTo("Steeltoe.Management.Prometheus")] diff --git a/src/Common/src/Common/ValidatedNotNullAttribute.cs b/src/Common/src/Common/ValidatedNotNullAttribute.cs deleted file mode 100644 index cee2b99f5c..0000000000 --- a/src/Common/src/Common/ValidatedNotNullAttribute.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. - -namespace Steeltoe.Common; - -[AttributeUsage(AttributeTargets.Parameter)] -internal sealed class ValidatedNotNullAttribute : Attribute -{ - // This type is used by https://rules.sonarsource.com/csharp/RSPEC-3900 to validate null checks in public methods. -} diff --git a/src/Common/src/Hosting/HostBuilderContextWrapper.cs b/src/Common/src/Hosting/HostBuilderContextWrapper.cs index 7c8e77dec9..177d1e1725 100644 --- a/src/Common/src/Hosting/HostBuilderContextWrapper.cs +++ b/src/Common/src/Hosting/HostBuilderContextWrapper.cs @@ -29,21 +29,21 @@ private HostBuilderContextWrapper(IConfiguration configuration, IHostEnvironment public static HostBuilderContextWrapper Wrap(HostBuilderContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); return new HostBuilderContextWrapper(context.Configuration, context.HostingEnvironment, context); } public static HostBuilderContextWrapper Wrap(WebHostBuilderContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); return new HostBuilderContextWrapper(context.Configuration, context.HostingEnvironment, context); } public static HostBuilderContextWrapper Wrap(IHostApplicationBuilder context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); return new HostBuilderContextWrapper(context.Configuration, context.Environment, context); } diff --git a/src/Common/src/Hosting/HostBuilderWrapper.cs b/src/Common/src/Hosting/HostBuilderWrapper.cs index 031fc749e7..e8a382ee79 100644 --- a/src/Common/src/Hosting/HostBuilderWrapper.cs +++ b/src/Common/src/Hosting/HostBuilderWrapper.cs @@ -31,7 +31,7 @@ private HostBuilderWrapper(object innerBuilder) public static HostBuilderWrapper Wrap(IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); var wrapper = new HostBuilderWrapper(builder); @@ -58,7 +58,7 @@ public static HostBuilderWrapper Wrap(IHostBuilder builder) public static HostBuilderWrapper Wrap(IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); var wrapper = new HostBuilderWrapper(builder); @@ -85,7 +85,7 @@ public static HostBuilderWrapper Wrap(IWebHostBuilder builder) public static HostBuilderWrapper Wrap(IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); // IHostApplicationBuilder implementations immediately execute callbacks, so don't capture them for deferred execution. @@ -103,14 +103,14 @@ private static void InvokeDeferredActions(IEnumerable configureAction) { - ArgumentGuard.NotNull(configureAction); + ArgumentNullException.ThrowIfNull(configureAction); return ConfigureServices((_, services) => configureAction(services)); } public HostBuilderWrapper ConfigureServices(Action configureAction) { - ArgumentGuard.NotNull(configureAction); + ArgumentNullException.ThrowIfNull(configureAction); if (_innerBuilder is IHostApplicationBuilder applicationBuilder) { @@ -127,14 +127,14 @@ public HostBuilderWrapper ConfigureServices(Action configureAction) { - ArgumentGuard.NotNull(configureAction); + ArgumentNullException.ThrowIfNull(configureAction); return ConfigureAppConfiguration((_, configurationBuilder) => configureAction(configurationBuilder)); } public HostBuilderWrapper ConfigureAppConfiguration(Action configureAction) { - ArgumentGuard.NotNull(configureAction); + ArgumentNullException.ThrowIfNull(configureAction); if (_innerBuilder is IHostApplicationBuilder applicationBuilder) { @@ -151,14 +151,14 @@ public HostBuilderWrapper ConfigureAppConfiguration(Action configureAction) { - ArgumentGuard.NotNull(configureAction); + ArgumentNullException.ThrowIfNull(configureAction); return ConfigureLogging((_, configurationBuilder) => configureAction(configurationBuilder)); } public HostBuilderWrapper ConfigureLogging(Action configureAction) { - ArgumentGuard.NotNull(configureAction); + ArgumentNullException.ThrowIfNull(configureAction); if (_innerBuilder is IHostApplicationBuilder applicationBuilder) { @@ -175,7 +175,7 @@ public HostBuilderWrapper ConfigureLogging(Action configureAction) { - ArgumentGuard.NotNull(configureAction); + ArgumentNullException.ThrowIfNull(configureAction); if (_innerBuilder is IHostBuilder hostBuilder) { diff --git a/src/Common/src/Http/HttpClientExtensions.cs b/src/Common/src/Http/HttpClientExtensions.cs index 04cd30a9ff..cd96f09dd5 100644 --- a/src/Common/src/Http/HttpClientExtensions.cs +++ b/src/Common/src/Http/HttpClientExtensions.cs @@ -41,8 +41,8 @@ internal static class HttpClientExtensions public static async Task GetAccessTokenAsync(this HttpClient httpClient, Uri accessTokenUri, string? username, string? password, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(httpClient); - ArgumentGuard.NotNull(accessTokenUri); + ArgumentNullException.ThrowIfNull(httpClient); + ArgumentNullException.ThrowIfNull(accessTokenUri); var request = new HttpRequestMessage(HttpMethod.Post, accessTokenUri) { diff --git a/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs b/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs index 73651cb281..1b0cb19797 100644 --- a/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs +++ b/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs @@ -18,7 +18,7 @@ public sealed class ClientCertificateHttpClientHandlerConfigurer : IHttpClientHa public ClientCertificateHttpClientHandlerConfigurer(IOptionsMonitor optionsMonitor) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); _optionsMonitor = optionsMonitor; } @@ -30,7 +30,7 @@ public void SetCertificateName(string certificateName) public void Configure(HttpClientHandler handler) { - ArgumentGuard.NotNull(handler); + ArgumentNullException.ThrowIfNull(handler); X509Certificate2 certificate = _optionsMonitor.Get(_clientCertificateName).Certificate; diff --git a/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs b/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs index 99c871330a..ce377d5fd0 100644 --- a/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs +++ b/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs @@ -21,7 +21,7 @@ public sealed class HttpClientHandlerFactory /// public HttpClientHandlerFactory Using(HttpClientHandler handler) { - ArgumentGuard.NotNull(handler); + ArgumentNullException.ThrowIfNull(handler); _handler = handler; return this; diff --git a/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs b/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs index a0212f5c4f..af1a99d9e8 100644 --- a/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs +++ b/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs @@ -22,7 +22,7 @@ internal sealed class ValidateCertificatesHttpClientHandlerConfigurer public ValidateCertificatesHttpClientHandlerConfigurer(IOptionsMonitor optionsMonitor) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); _optionsMonitor = optionsMonitor; } diff --git a/src/Common/src/Logging/BootstrapLoggerContext.cs b/src/Common/src/Logging/BootstrapLoggerContext.cs index a7553e29b3..1de3f473c6 100644 --- a/src/Common/src/Logging/BootstrapLoggerContext.cs +++ b/src/Common/src/Logging/BootstrapLoggerContext.cs @@ -14,7 +14,7 @@ public sealed class BootstrapLoggerContext public BootstrapLoggerContext(object key) { - ArgumentGuard.NotNull(key); + ArgumentNullException.ThrowIfNull(key); _key = key; } diff --git a/src/Common/src/Logging/BootstrapLoggerHostedService.cs b/src/Common/src/Logging/BootstrapLoggerHostedService.cs index c962877244..b28ac55858 100644 --- a/src/Common/src/Logging/BootstrapLoggerHostedService.cs +++ b/src/Common/src/Logging/BootstrapLoggerHostedService.cs @@ -17,8 +17,8 @@ internal sealed class BootstrapLoggerHostedService : IHostedService public BootstrapLoggerHostedService(BootstrapLoggerContext context, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(context); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(loggerFactory); _context = context; _loggerFactory = loggerFactory; @@ -36,10 +36,9 @@ public Task StopAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public static void Register(ILoggerFactory loggerFactory, HostBuilderWrapper wrapper) + public static void Register(HostBuilderWrapper wrapper) { - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(wrapper); + ArgumentNullException.ThrowIfNull(wrapper); wrapper.ConfigureServices(services => { diff --git a/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs b/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs index da3b6c6a5e..8c2d36699f 100644 --- a/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs +++ b/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs @@ -51,7 +51,7 @@ public UpgradableBootstrapLoggerFactory(Action /// public void Update(IConfiguration value) { - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(value); if (_factory != null) { diff --git a/src/Common/test/TestResources/CapturingLoggerProvider.cs b/src/Common/test/TestResources/CapturingLoggerProvider.cs index b3d3d01f23..e45f4b8e00 100644 --- a/src/Common/test/TestResources/CapturingLoggerProvider.cs +++ b/src/Common/test/TestResources/CapturingLoggerProvider.cs @@ -50,7 +50,7 @@ public IList GetAll() { lock (_lockObject) { - return _messages.ToList(); + return _messages.ToArray(); } } diff --git a/src/Common/test/TestResources/XunitLoggerProvider.cs b/src/Common/test/TestResources/XunitLoggerProvider.cs index 869b21ea27..7c54a1267d 100644 --- a/src/Common/test/TestResources/XunitLoggerProvider.cs +++ b/src/Common/test/TestResources/XunitLoggerProvider.cs @@ -54,7 +54,7 @@ private sealed class XunitLogger : ILogger public XunitLogger(ITestOutputHelper output, string categoryName, Func filter) { ArgumentNullException.ThrowIfNull(output); - ArgumentNullException.ThrowIfNull(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); ArgumentNullException.ThrowIfNull(filter); _output = output; diff --git a/src/Configuration/src/Abstractions/BaseServiceOptions.cs b/src/Configuration/src/Abstractions/BaseServiceOptions.cs index fdee7432ca..6b1b4cd1cd 100644 --- a/src/Configuration/src/Abstractions/BaseServiceOptions.cs +++ b/src/Configuration/src/Abstractions/BaseServiceOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration; @@ -71,7 +70,7 @@ public IList GetAllServices() /// public IList GetServicesOfType(string serviceType) { - ArgumentGuard.NotNullOrEmpty(serviceType); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceType); return Services.TryGetValue(serviceType, out IList? services) ? services : Array.Empty(); } @@ -87,8 +86,8 @@ public IList GetServicesOfType(string serviceType) /// public void Bind(IConfiguration configuration, string serviceName) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNullOrEmpty(serviceName); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceName); IConfigurationSection services = configuration.GetSection(ConfigurationPrefix); IConfigurationSection? section = FindServiceSection(services, serviceName); diff --git a/src/Configuration/src/Abstractions/ConfigurationExtensions.cs b/src/Configuration/src/Abstractions/ConfigurationExtensions.cs index 992bba1d6d..10510c936a 100644 --- a/src/Configuration/src/Abstractions/ConfigurationExtensions.cs +++ b/src/Configuration/src/Abstractions/ConfigurationExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration; @@ -22,7 +21,7 @@ internal static class ConfigurationExtensions public static TProvider? FindConfigurationProvider(this IConfiguration configuration) where TProvider : class, IConfigurationProvider { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); if (configuration is IConfigurationRoot root) { diff --git a/src/Configuration/src/Abstractions/PostProcessorConfigurationProvider.cs b/src/Configuration/src/Abstractions/PostProcessorConfigurationProvider.cs index 355111e976..cfff66a355 100644 --- a/src/Configuration/src/Abstractions/PostProcessorConfigurationProvider.cs +++ b/src/Configuration/src/Abstractions/PostProcessorConfigurationProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration; @@ -13,7 +12,7 @@ internal abstract class PostProcessorConfigurationProvider : ConfigurationProvid protected PostProcessorConfigurationProvider(PostProcessorConfigurationSource source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); Source = source; } diff --git a/src/Configuration/src/Abstractions/PostProcessorConfigurationSource.cs b/src/Configuration/src/Abstractions/PostProcessorConfigurationSource.cs index d8e453fc4f..4d9cee9ff7 100644 --- a/src/Configuration/src/Abstractions/PostProcessorConfigurationSource.cs +++ b/src/Configuration/src/Abstractions/PostProcessorConfigurationSource.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration; @@ -17,7 +16,7 @@ internal abstract class PostProcessorConfigurationSource public void RegisterPostProcessor(IConfigurationPostProcessor processor) { - ArgumentGuard.NotNull(processor); + ArgumentNullException.ThrowIfNull(processor); _postProcessors.Add(processor); } diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationProvider.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationProvider.cs index 28cad8bc02..455d262063 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationProvider.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding; @@ -17,7 +16,7 @@ internal sealed class CloudFoundryServiceBindingConfigurationProvider : PostProc public CloudFoundryServiceBindingConfigurationProvider(PostProcessorConfigurationSource source, IServiceBindingsReader serviceBindingsReader) : base(source) { - ArgumentGuard.NotNull(serviceBindingsReader); + ArgumentNullException.ThrowIfNull(serviceBindingsReader); _serviceBindingsReader = serviceBindingsReader; } diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationSource.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationSource.cs index 5c709c30d7..1eac85182e 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationSource.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/CloudFoundryServiceBindingConfigurationSource.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding; @@ -13,14 +12,14 @@ internal sealed class CloudFoundryServiceBindingConfigurationSource : PostProces public CloudFoundryServiceBindingConfigurationSource(IServiceBindingsReader serviceBindingsReader) { - ArgumentGuard.NotNull(serviceBindingsReader); + ArgumentNullException.ThrowIfNull(serviceBindingsReader); _serviceBindingsReader = serviceBindingsReader; } public IConfigurationProvider Build(IConfigurationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); CaptureConfigurationBuilder(builder); return new CloudFoundryServiceBindingConfigurationProvider(this, _serviceBindingsReader); diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/ConfigurationBuilderExtensions.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/ConfigurationBuilderExtensions.cs index ab63131ec4..84cf2a83e9 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/ConfigurationBuilderExtensions.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/ConfigurationBuilderExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Configuration.CloudFoundry.ServiceBinding.PostProcessors; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding; @@ -71,10 +70,10 @@ public static IConfigurationBuilder AddCloudFoundryServiceBindings(this IConfigu public static IConfigurationBuilder AddCloudFoundryServiceBindings(this IConfigurationBuilder builder, Predicate ignoreKeyPredicate, IServiceBindingsReader serviceBindingsReader, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(ignoreKeyPredicate); - ArgumentGuard.NotNull(serviceBindingsReader); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(ignoreKeyPredicate); + ArgumentNullException.ThrowIfNull(serviceBindingsReader); + ArgumentNullException.ThrowIfNull(loggerFactory); if (!builder.Sources.OfType().Any()) { diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationProvider.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationProvider.cs index 26f2846b83..bb64cbc6cb 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationProvider.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration.Json; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding; @@ -14,7 +13,7 @@ internal sealed class JsonStreamConfigurationProvider : JsonConfigurationProvide public JsonStreamConfigurationProvider(JsonStreamConfigurationSource source) : base(source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); _source = source; } diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationSource.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationSource.cs index eca27358c0..2d91b39b74 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationSource.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/JsonStreamConfigurationSource.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding; @@ -14,14 +13,14 @@ internal sealed class JsonStreamConfigurationSource : JsonConfigurationSource public JsonStreamConfigurationSource(Stream stream) { - ArgumentGuard.NotNull(stream); + ArgumentNullException.ThrowIfNull(stream); Stream = stream; } public override IConfigurationProvider Build(IConfigurationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); return new JsonStreamConfigurationProvider(this); } diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/EurekaCloudFoundryPostProcessor.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/EurekaCloudFoundryPostProcessor.cs index 2987eae1d2..f5866b36b8 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/EurekaCloudFoundryPostProcessor.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/EurekaCloudFoundryPostProcessor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding.PostProcessors; @@ -15,7 +14,7 @@ internal sealed class EurekaCloudFoundryPostProcessor : CloudFoundryPostProcesso public EurekaCloudFoundryPostProcessor(ILogger logger) { - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; } diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/IdentityCloudFoundryPostProcessor.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/IdentityCloudFoundryPostProcessor.cs index 10c130e36a..ee1acf654a 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/IdentityCloudFoundryPostProcessor.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/PostProcessors/IdentityCloudFoundryPostProcessor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding.PostProcessors; @@ -22,7 +21,7 @@ internal sealed class IdentityCloudFoundryPostProcessor : CloudFoundryPostProces public IdentityCloudFoundryPostProcessor(ILogger logger) { - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; } diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/ServiceBindingMapper.cs b/src/Configuration/src/CloudFoundry.ServiceBinding/ServiceBindingMapper.cs index 8fda267b0a..6c9f5ff556 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/ServiceBindingMapper.cs +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/ServiceBindingMapper.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry.ServiceBinding; @@ -25,9 +24,9 @@ private ServiceBindingMapper(IDictionary configurationData, str public static ServiceBindingMapper Create(IDictionary configurationData, string bindingKey, string bindingType, string? overrideToPrefix = null) { - ArgumentGuard.NotNull(bindingType); - ArgumentGuard.NotNull(bindingKey); - ArgumentGuard.NotNull(configurationData); + ArgumentNullException.ThrowIfNull(configurationData); + ArgumentException.ThrowIfNullOrEmpty(bindingKey); + ArgumentException.ThrowIfNullOrEmpty(bindingType); string bindingName = configurationData[ConfigurationPath.Combine(bindingKey, "name")] ?? string.Empty; string bindingProvider = ConfigurationPath.GetSectionKey(ConfigurationPath.GetParentPath(bindingKey)) ?? string.Empty; diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationBuilderExtensions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationBuilderExtensions.cs index 24c8324a45..35df7746f6 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationBuilderExtensions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationBuilderExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry; @@ -24,8 +23,8 @@ public static IConfigurationBuilder AddCloudFoundry(this IConfigurationBuilder c public static IConfigurationBuilder AddCloudFoundry(this IConfigurationBuilder configurationBuilder, ICloudFoundrySettingsReader? settingsReader, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configurationBuilder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(configurationBuilder); + ArgumentNullException.ThrowIfNull(loggerFactory); var source = new CloudFoundryConfigurationSource(settingsReader); return configurationBuilder.Add(source); diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationProvider.cs b/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationProvider.cs index d9d00bfc01..86a87d5d5f 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationProvider.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryConfigurationProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry; @@ -15,7 +14,7 @@ internal sealed class CloudFoundryConfigurationProvider : ConfigurationProvider public CloudFoundryConfigurationProvider(ICloudFoundrySettingsReader settingsReader) { - ArgumentGuard.NotNull(settingsReader); + ArgumentNullException.ThrowIfNull(settingsReader); _settingsReader = settingsReader; } diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryHostBuilderExtensions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryHostBuilderExtensions.cs index f5d8c9d26a..c2fc29bcc2 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryHostBuilderExtensions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryHostBuilderExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Common.Hosting; using Steeltoe.Common.Logging; @@ -43,7 +42,7 @@ public static IWebHostBuilder AddCloudFoundryConfiguration(this IWebHostBuilder /// public static IWebHostBuilder AddCloudFoundryConfiguration(this IWebHostBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddCloudFoundryConfiguration(loggerFactory); @@ -80,7 +79,7 @@ public static IHostBuilder AddCloudFoundryConfiguration(this IHostBuilder builde /// public static IHostBuilder AddCloudFoundryConfiguration(this IHostBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddCloudFoundryConfiguration(loggerFactory); @@ -117,7 +116,7 @@ public static IHostApplicationBuilder AddCloudFoundryConfiguration(this IHostApp /// public static IHostApplicationBuilder AddCloudFoundryConfiguration(this IHostApplicationBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddCloudFoundryConfiguration(loggerFactory); diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs index a338f83f99..fe8d653bc6 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs @@ -28,8 +28,8 @@ public static class CloudFoundryServiceCollectionExtensions /// public static IServiceCollection ConfigureCloudFoundryOptions(this IServiceCollection services, IConfiguration configuration) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); services.AddOptions(); @@ -63,9 +63,9 @@ public static IServiceCollection ConfigureCloudFoundryOptions(this IServiceColle /// public static IServiceCollection ConfigureCloudFoundryService(this IServiceCollection services, IConfiguration configuration, string serviceName) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNullOrEmpty(serviceName); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceName); services.Configure(serviceName, option => option.Bind(configuration, serviceName)); @@ -91,9 +91,9 @@ public static IServiceCollection ConfigureCloudFoundryService(this IServiceColle /// public static IServiceCollection ConfigureCloudFoundryServices(this IServiceCollection services, IConfiguration configuration, string serviceLabel) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNullOrEmpty(serviceLabel); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceLabel); var servicesOptions = new CloudFoundryServicesOptions(configuration); @@ -119,7 +119,7 @@ public static IServiceCollection ConfigureCloudFoundryServices(this IServiceColl /// public static IServiceCollection RegisterCloudFoundryApplicationInstanceInfo(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); ServiceDescriptor? appInfoDescriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IApplicationInstanceInfo)); diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs index f57c6a7540..5a5c06a212 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry; @@ -20,7 +19,7 @@ public CloudFoundryServicesOptions() public CloudFoundryServicesOptions(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); configuration.GetSection(ServicesConfigurationRoot).Bind(this); } diff --git a/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs b/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs index ca3ab99d8a..f7a63d4ccf 100644 --- a/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs +++ b/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.Hosting; using Steeltoe.Common.Logging; @@ -13,15 +12,15 @@ internal static class HostBuilderWrapperExtensions { public static HostBuilderWrapper AddCloudFoundryConfiguration(this HostBuilderWrapper wrapper, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(wrapper); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(wrapper); + ArgumentNullException.ThrowIfNull(loggerFactory); wrapper.ConfigureAppConfiguration(builder => builder.AddCloudFoundry(null, loggerFactory)); wrapper.ConfigureServices(services => services.RegisterCloudFoundryApplicationInstanceInfo()); if (loggerFactory is IBootstrapLoggerFactory) { - BootstrapLoggerHostedService.Register(loggerFactory, wrapper); + BootstrapLoggerHostedService.Register(wrapper); } return wrapper; diff --git a/src/Configuration/src/CloudFoundry/JsonStreamConfigurationProvider.cs b/src/Configuration/src/CloudFoundry/JsonStreamConfigurationProvider.cs index 7f9f6ad9fc..499d3a2754 100644 --- a/src/Configuration/src/CloudFoundry/JsonStreamConfigurationProvider.cs +++ b/src/Configuration/src/CloudFoundry/JsonStreamConfigurationProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration.Json; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry; @@ -14,7 +13,7 @@ internal sealed class JsonStreamConfigurationProvider : JsonConfigurationProvide public JsonStreamConfigurationProvider(JsonStreamConfigurationSource source) : base(source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); _source = source; } diff --git a/src/Configuration/src/CloudFoundry/JsonStreamConfigurationSource.cs b/src/Configuration/src/CloudFoundry/JsonStreamConfigurationSource.cs index ce8d5829fc..8d75f7feb1 100644 --- a/src/Configuration/src/CloudFoundry/JsonStreamConfigurationSource.cs +++ b/src/Configuration/src/CloudFoundry/JsonStreamConfigurationSource.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; -using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry; @@ -14,14 +13,14 @@ internal sealed class JsonStreamConfigurationSource : JsonConfigurationSource public JsonStreamConfigurationSource(Stream stream) { - ArgumentGuard.NotNull(stream); + ArgumentNullException.ThrowIfNull(stream); Stream = stream; } public override IConfigurationProvider Build(IConfigurationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); return new JsonStreamConfigurationProvider(this); } diff --git a/src/Configuration/src/ConfigServer/ConfigServerConfigurationBuilderExtensions.cs b/src/Configuration/src/ConfigServer/ConfigServerConfigurationBuilderExtensions.cs index 376598355c..85937ce1e5 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerConfigurationBuilderExtensions.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerConfigurationBuilderExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Configuration.CloudFoundry; using Steeltoe.Configuration.Kubernetes.ServiceBinding; using Steeltoe.Configuration.Placeholder; @@ -70,7 +69,7 @@ public static IConfigurationBuilder AddConfigServer(this IConfigurationBuilder c public static IConfigurationBuilder AddConfigServer(this IConfigurationBuilder configurationBuilder, IHostEnvironment environment, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(environment); + ArgumentNullException.ThrowIfNull(environment); var options = new ConfigServerClientOptions { @@ -84,9 +83,9 @@ public static IConfigurationBuilder AddConfigServer(this IConfigurationBuilder c public static IConfigurationBuilder AddConfigServer(this IConfigurationBuilder configurationBuilder, ConfigServerClientOptions options, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configurationBuilder); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(configurationBuilder); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); if (configurationBuilder.Sources.All(source => source is not CloudFoundryConfigurationSource)) { diff --git a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs index ea0328f2b3..be6f35cf7b 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs @@ -13,7 +13,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; using Steeltoe.Common.Extensions; @@ -81,8 +80,8 @@ public ConfigServerConfigurationProvider(ConfigServerConfigurationSource source, internal ConfigServerConfigurationProvider(ConfigServerClientOptions options, IConfiguration? configuration, HttpClientHandler? httpClientHandler, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); _loggerFactory = loggerFactory; Logger = _loggerFactory.CreateLogger(); @@ -457,7 +456,7 @@ internal void AddConfigServerClientOptions() /// private void AddConfigServerClientOptions(IDictionary data) { - ArgumentGuard.NotNull(data); + ArgumentNullException.ThrowIfNull(data); data["spring:cloud:config:enabled"] = Options.Enabled.ToString(CultureInfo.InvariantCulture); data["spring:cloud:config:failFast"] = Options.FailFast.ToString(CultureInfo.InvariantCulture); @@ -565,7 +564,7 @@ private void AddConfigServerClientOptions(IDictionary data) /// internal Uri BuildConfigServerUri(string serverUri, string? label) { - ArgumentGuard.NotNullOrEmpty(serverUri); + ArgumentException.ThrowIfNullOrWhiteSpace(serverUri); var uriBuilder = new UriBuilder(new Uri(serverUri)); @@ -613,7 +612,7 @@ internal Uri BuildConfigServerUri(string serverUri, string? label) /// private void AddPropertySource(PropertySource? source, IDictionary data) { - ArgumentGuard.NotNull(data); + ArgumentNullException.ThrowIfNull(data); if (source?.Source == null) { @@ -735,7 +734,7 @@ internal bool IsDiscoveryFirstEnabled() /// internal HttpClient CreateHttpClient(ConfigServerClientOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); ObjectDisposedException.ThrowIf(_httpClientHandler == null, this); var clientCertificateConfigurer = new ClientCertificateHttpClientHandlerConfigurer(OptionsMonitorWrapper.Create(options.ClientCertificate)); diff --git a/src/Configuration/src/ConfigServer/ConfigServerConfigurationSource.cs b/src/Configuration/src/ConfigServer/ConfigServerConfigurationSource.cs index 88e0c18a6b..dae8754184 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerConfigurationSource.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerConfigurationSource.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Common.Certificates; using Steeltoe.Common.Configuration; @@ -46,9 +45,9 @@ internal sealed class ConfigServerConfigurationSource : IConfigurationSource /// public ConfigServerConfigurationSource(ConfigServerClientOptions defaultOptions, IConfiguration configuration, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(defaultOptions); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(defaultOptions); + ArgumentNullException.ThrowIfNull(loggerFactory); Configuration = configuration; DefaultOptions = defaultOptions; @@ -74,9 +73,9 @@ public ConfigServerConfigurationSource(ConfigServerClientOptions defaultOptions, public ConfigServerConfigurationSource(ConfigServerClientOptions defaultOptions, IList sources, IDictionary? properties, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(defaultOptions); - ArgumentGuard.NotNull(sources); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(defaultOptions); + ArgumentNullException.ThrowIfNull(sources); + ArgumentNullException.ThrowIfNull(loggerFactory); Sources = new List(sources); diff --git a/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs b/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs index 5f15c1e707..1dcb37d0d3 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerDiscoveryService.cs @@ -27,9 +27,9 @@ internal sealed class ConfigServerDiscoveryService public ConfigServerDiscoveryService(IConfiguration configuration, ConfigServerClientOptions options, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); _configuration = configuration; _options = options; @@ -155,7 +155,7 @@ internal async Task> GetConfigServerInstancesAsync internal async Task ProvideRuntimeReplacementsAsync(ICollection discoveryClientsFromServiceProvider, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(discoveryClientsFromServiceProvider); + ArgumentNullException.ThrowIfNull(discoveryClientsFromServiceProvider); _logger.LogInformation("Replacing the IDiscoveryClient(s) built at startup with the ones for runtime"); diff --git a/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs b/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs index 1ae0b25dc4..e52fb354f6 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Configuration.ConfigServer; @@ -20,8 +19,8 @@ internal sealed class ConfigServerHealthContributor : IHealthContributor public ConfigServerHealthContributor(IConfiguration configuration, ILogger logger) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; Provider = configuration.FindConfigurationProvider(); diff --git a/src/Configuration/src/ConfigServer/ConfigServerHostBuilderExtensions.cs b/src/Configuration/src/ConfigServer/ConfigServerHostBuilderExtensions.cs index 8dd37512eb..2c12250f36 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerHostBuilderExtensions.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerHostBuilderExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Common.Hosting; using Steeltoe.Common.Logging; @@ -43,8 +42,8 @@ public static IWebHostBuilder AddConfigServer(this IWebHostBuilder builder) /// public static IWebHostBuilder AddConfigServer(this IWebHostBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddConfigServer(loggerFactory); @@ -81,8 +80,8 @@ public static IHostBuilder AddConfigServer(this IHostBuilder builder) /// public static IHostBuilder AddConfigServer(this IHostBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddConfigServer(loggerFactory); @@ -121,8 +120,8 @@ public static IHostApplicationBuilder AddConfigServer(this IHostApplicationBuild /// public static IHostApplicationBuilder AddConfigServer(this IHostApplicationBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddConfigServer(loggerFactory); diff --git a/src/Configuration/src/ConfigServer/ConfigServerHostedService.cs b/src/Configuration/src/ConfigServer/ConfigServerHostedService.cs index 74e2a429bd..9227be3b50 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerHostedService.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerHostedService.cs @@ -24,13 +24,16 @@ public ConfigServerHostedService(IConfigurationRoot configuration) public ConfigServerHostedService(IConfigurationRoot configuration, IEnumerable discoveryClients) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(discoveryClients); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(discoveryClients); + + IDiscoveryClient[] discoveryClientArray = discoveryClients.ToArray(); + ArgumentGuard.ElementsNotNull(discoveryClientArray); _configurationProvider = configuration.FindConfigurationProvider() ?? throw new ArgumentException("ConfigServerConfigurationProvider was not found in configuration.", nameof(configuration)); - _discoveryClients = discoveryClients.ToArray(); + _discoveryClients = discoveryClientArray; } public async Task StartAsync(CancellationToken cancellationToken) diff --git a/src/Configuration/src/ConfigServer/ConfigServerServiceCollectionExtensions.cs b/src/Configuration/src/ConfigServer/ConfigServerServiceCollectionExtensions.cs index a3a53fd745..577016ae16 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerServiceCollectionExtensions.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Configuration.ConfigServer; @@ -17,7 +16,7 @@ public static class ConfigServerServiceCollectionExtensions { public static IServiceCollection ConfigureConfigServerClientOptions(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddOptions().Configure((options, configuration) => configuration.GetSection(ConfigServerClientOptions.ConfigurationPrefix).Bind(options)); @@ -36,7 +35,7 @@ public static IServiceCollection ConfigureConfigServerClientOptions(this IServic /// public static IServiceCollection AddConfigServerHealthContributor(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IHealthContributor), typeof(ConfigServerHealthContributor))); @@ -52,7 +51,7 @@ public static IServiceCollection AddConfigServerHealthContributor(this IServiceC /// public static void AddConfigServerServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureConfigServerClientOptions(); services.TryAddSingleton(serviceProvider => (IConfigurationRoot)serviceProvider.GetRequiredService()); diff --git a/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs b/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs index c66ee0c376..2fd54eb3c2 100644 --- a/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs +++ b/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Common.Configuration; namespace Steeltoe.Configuration.ConfigServer; @@ -18,9 +17,9 @@ internal static class ConfigurationSettingsHelper public static void Initialize(string sectionPrefix, ConfigServerClientOptions options, IConfiguration configuration) { - ArgumentGuard.NotNull(sectionPrefix); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(configuration); + ArgumentException.ThrowIfNullOrEmpty(sectionPrefix); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(configuration); IConfigurationSection configurationSection = configuration.GetSection(sectionPrefix); diff --git a/src/Configuration/src/ConfigServer/HostBuilderWrapperExtensions.cs b/src/Configuration/src/ConfigServer/HostBuilderWrapperExtensions.cs index eecc9dbab5..44ee79d33e 100644 --- a/src/Configuration/src/ConfigServer/HostBuilderWrapperExtensions.cs +++ b/src/Configuration/src/ConfigServer/HostBuilderWrapperExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.Hosting; using Steeltoe.Common.Logging; @@ -13,15 +12,15 @@ internal static class HostBuilderWrapperExtensions { public static HostBuilderWrapper AddConfigServer(this HostBuilderWrapper wrapper, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(wrapper); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(wrapper); + ArgumentNullException.ThrowIfNull(loggerFactory); wrapper.ConfigureAppConfiguration((context, builder) => builder.AddConfigServer(context.HostEnvironment, loggerFactory)); wrapper.ConfigureServices(services => services.AddConfigServerServices()); if (loggerFactory is IBootstrapLoggerFactory) { - BootstrapLoggerHostedService.Register(loggerFactory, wrapper); + BootstrapLoggerHostedService.Register(wrapper); } return wrapper; diff --git a/src/Configuration/src/ConfigServer/OptionsMonitorWrapper.cs b/src/Configuration/src/ConfigServer/OptionsMonitorWrapper.cs index f59d501e1b..dc07c45912 100644 --- a/src/Configuration/src/ConfigServer/OptionsMonitorWrapper.cs +++ b/src/Configuration/src/ConfigServer/OptionsMonitorWrapper.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Configuration.ConfigServer; @@ -23,7 +22,7 @@ internal sealed class OptionsMonitorWrapper : IOptionsMonitor public OptionsMonitorWrapper(T options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); CurrentValue = options; } diff --git a/src/Configuration/src/Encryption/ConfigurationView.cs b/src/Configuration/src/Encryption/ConfigurationView.cs index 0d81eb90e8..0ef6fa2ecd 100644 --- a/src/Configuration/src/Encryption/ConfigurationView.cs +++ b/src/Configuration/src/Encryption/ConfigurationView.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption; @@ -44,7 +43,7 @@ public string? this[string key] /// public ConfigurationView(IList providers) { - ArgumentGuard.NotNull(providers); + ArgumentNullException.ThrowIfNull(providers); _providers = providers; } diff --git a/src/Configuration/src/Encryption/Decryption/AesTextDecryptor.cs b/src/Configuration/src/Encryption/Decryption/AesTextDecryptor.cs index 709cbafa80..2079f84e53 100644 --- a/src/Configuration/src/Encryption/Decryption/AesTextDecryptor.cs +++ b/src/Configuration/src/Encryption/Decryption/AesTextDecryptor.cs @@ -7,7 +7,6 @@ using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption.Decryption; @@ -30,9 +29,8 @@ public AesTextDecryptor(string key, string salt) public AesTextDecryptor(string key, string salt, bool strong) { - ArgumentGuard.NotNull(key); - ArgumentGuard.NotNull(salt); - ArgumentGuard.NotNull(strong); + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(salt); _cipher = strong ? CipherUtilities.GetCipher("AES/GCM/NoPadding") : CipherUtilities.GetCipher("AES/CBC/PKCS5Padding"); @@ -66,7 +64,7 @@ public string Decrypt(string fullCipher, string alias) public string Decrypt(byte[] fullCipher) { - ArgumentGuard.NotNull(fullCipher); + ArgumentNullException.ThrowIfNull(fullCipher); byte[] iv = new byte[IvSize / 8]; byte[] cipherBytes = new byte[fullCipher.Length - iv.Length]; diff --git a/src/Configuration/src/Encryption/Decryption/ConfigServerEncryptionSettings.cs b/src/Configuration/src/Encryption/Decryption/ConfigServerEncryptionSettings.cs index 8c58f95f9b..f97451fb8b 100644 --- a/src/Configuration/src/Encryption/Decryption/ConfigServerEncryptionSettings.cs +++ b/src/Configuration/src/Encryption/Decryption/ConfigServerEncryptionSettings.cs @@ -32,7 +32,7 @@ internal sealed class ConfigServerEncryptionSettings /// public string? EncryptionKey { get; set; } - internal static ITextDecryptor CreateTextDecryptor(IConfiguration configuration) + public static ITextDecryptor CreateTextDecryptor(IConfiguration configuration) { var settings = new ConfigServerEncryptionSettings(); ConfigurationSettingsHelper.Initialize(settings, configuration); diff --git a/src/Configuration/src/Encryption/Decryption/ConfigurationSettingsHelper.cs b/src/Configuration/src/Encryption/Decryption/ConfigurationSettingsHelper.cs index c7dafcc8eb..a14207912b 100644 --- a/src/Configuration/src/Encryption/Decryption/ConfigurationSettingsHelper.cs +++ b/src/Configuration/src/Encryption/Decryption/ConfigurationSettingsHelper.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption.Decryption; @@ -13,8 +12,8 @@ internal static class ConfigurationSettingsHelper public static void Initialize(ConfigServerEncryptionSettings settings, IConfiguration configuration) { - ArgumentGuard.NotNull(settings); - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(configuration); IConfigurationSection configurationSection = configuration.GetSection(ConfigurationPrefix); diff --git a/src/Configuration/src/Encryption/Decryption/KeyProvider.cs b/src/Configuration/src/Encryption/Decryption/KeyProvider.cs index e04e9508db..8af1d3cf25 100644 --- a/src/Configuration/src/Encryption/Decryption/KeyProvider.cs +++ b/src/Configuration/src/Encryption/Decryption/KeyProvider.cs @@ -4,7 +4,6 @@ using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Pkcs; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption.Decryption; @@ -14,8 +13,8 @@ internal sealed class KeyProvider : IKeyProvider public KeyProvider(string fileName, string pfxPassword) { - ArgumentGuard.NotNull(fileName); - ArgumentGuard.NotNull(pfxPassword); + ArgumentException.ThrowIfNullOrEmpty(fileName); + ArgumentNullException.ThrowIfNull(pfxPassword); using var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); _store = CreateStore(fileStream, pfxPassword); @@ -23,8 +22,8 @@ public KeyProvider(string fileName, string pfxPassword) public KeyProvider(Stream fileStream, string pfxPassword) { - ArgumentGuard.NotNull(fileStream); - ArgumentGuard.NotNull(pfxPassword); + ArgumentNullException.ThrowIfNull(fileStream); + ArgumentNullException.ThrowIfNull(pfxPassword); _store = CreateStore(fileStream, pfxPassword); } @@ -40,6 +39,8 @@ private static Pkcs12Store CreateStore(Stream fileStream, string pfxPassword) public ICipherParameters? GetKey(string keyAlias) { + ArgumentNullException.ThrowIfNull(keyAlias); + return _store.GetKey(keyAlias)?.Key; } } diff --git a/src/Configuration/src/Encryption/Decryption/RsaKeyStoreDecryptor.cs b/src/Configuration/src/Encryption/Decryption/RsaKeyStoreDecryptor.cs index 74caf11370..36329f39b7 100644 --- a/src/Configuration/src/Encryption/Decryption/RsaKeyStoreDecryptor.cs +++ b/src/Configuration/src/Encryption/Decryption/RsaKeyStoreDecryptor.cs @@ -5,7 +5,6 @@ using System.Buffers.Binary; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Security; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption.Decryption; @@ -24,11 +23,10 @@ public RsaKeyStoreDecryptor(IKeyProvider keyProvider, string alias) public RsaKeyStoreDecryptor(IKeyProvider keyProvider, string alias, string salt, bool strong, string algorithm) { - ArgumentGuard.NotNull(keyProvider); - ArgumentGuard.NotNull(alias); - ArgumentGuard.NotNull(salt); - ArgumentGuard.NotNull(strong); - ArgumentGuard.NotNull(algorithm); + ArgumentNullException.ThrowIfNull(keyProvider); + ArgumentNullException.ThrowIfNull(alias); + ArgumentNullException.ThrowIfNull(salt); + ArgumentNullException.ThrowIfNull(algorithm); _salt = salt; _defaultKeyAlias = alias; @@ -49,20 +47,23 @@ private IBufferedCipher CreateCipher(string algorithm) public string Decrypt(string fullCipher) { + ArgumentNullException.ThrowIfNull(fullCipher); + byte[] bytes = Convert.FromBase64String(fullCipher); return Decrypt(bytes, _defaultKeyAlias); } public string Decrypt(string fullCipher, string alias) { + ArgumentNullException.ThrowIfNull(fullCipher); + ArgumentNullException.ThrowIfNull(alias); + byte[] bytes = Convert.FromBase64String(fullCipher); return Decrypt(bytes, alias); } private string Decrypt(byte[] fullCipher, string alias) { - ArgumentGuard.NotNull(fullCipher); - ICipherParameters? key = _keyProvider.GetKey(alias); if (key == null) diff --git a/src/Configuration/src/Encryption/EncryptionConfigurationExtensions.cs b/src/Configuration/src/Encryption/EncryptionConfigurationExtensions.cs index b253a15fa7..0276179a7c 100644 --- a/src/Configuration/src/Encryption/EncryptionConfigurationExtensions.cs +++ b/src/Configuration/src/Encryption/EncryptionConfigurationExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption; @@ -51,9 +50,9 @@ public static IConfigurationBuilder AddEncryptionResolver(this IConfigurationBui /// public static IConfigurationBuilder AddEncryptionResolver(this IConfigurationBuilder builder, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); if (!builder.Sources.Any(source => source is EncryptionResolverSource)) { @@ -110,9 +109,9 @@ public static IConfiguration AddEncryptionResolver(this IConfiguration configura /// public static IConfiguration AddEncryptionResolver(this IConfiguration configuration, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); if (configuration is not IConfigurationRoot root) { @@ -171,9 +170,9 @@ public static ConfigurationManager AddEncryptionResolver(this ConfigurationManag public static ConfigurationManager AddEncryptionResolver(this ConfigurationManager configurationManager, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configurationManager); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(configurationManager); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); ((IConfigurationBuilder)configurationManager).AddEncryptionResolver(textDecryptor, loggerFactory); diff --git a/src/Configuration/src/Encryption/EncryptionHostBuilderExtensions.cs b/src/Configuration/src/Encryption/EncryptionHostBuilderExtensions.cs index c67afd9058..58fecfccdb 100644 --- a/src/Configuration/src/Encryption/EncryptionHostBuilderExtensions.cs +++ b/src/Configuration/src/Encryption/EncryptionHostBuilderExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Common.Hosting; using Steeltoe.Common.Logging; @@ -50,8 +49,8 @@ public static IWebHostBuilder AddEncryptionResolver(this IWebHostBuilder builder /// public static IWebHostBuilder AddEncryptionResolver(this IWebHostBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddEncryptionResolver(loggerFactory); @@ -94,8 +93,8 @@ public static IHostBuilder AddEncryptionResolver(this IHostBuilder builder) /// public static IHostBuilder AddEncryptionResolver(this IHostBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddEncryptionResolver(loggerFactory); @@ -138,8 +137,8 @@ public static IHostApplicationBuilder AddEncryptionResolver(this IHostApplicatio /// public static IHostApplicationBuilder AddEncryptionResolver(this IHostApplicationBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddEncryptionResolver(loggerFactory); diff --git a/src/Configuration/src/Encryption/EncryptionResolverProvider.cs b/src/Configuration/src/Encryption/EncryptionResolverProvider.cs index 9066c9f017..462d7ef9ff 100644 --- a/src/Configuration/src/Encryption/EncryptionResolverProvider.cs +++ b/src/Configuration/src/Encryption/EncryptionResolverProvider.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption; @@ -46,9 +45,9 @@ internal sealed class EncryptionResolverProvider : IConfigurationProvider, IDisp /// public EncryptionResolverProvider(IConfigurationRoot root, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(root); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); Configuration = root; Decryptor = textDecryptor; @@ -69,9 +68,9 @@ public EncryptionResolverProvider(IConfigurationRoot root, ITextDecryptor textDe /// public EncryptionResolverProvider(IList providers, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(providers); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(providers); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); Providers = providers; Decryptor = textDecryptor; @@ -91,7 +90,7 @@ public EncryptionResolverProvider(IList providers, IText /// public bool TryGet(string key, out string? value) { - ArgumentGuard.NotNull(key); + ArgumentException.ThrowIfNullOrEmpty(key); EnsureInitialized(); string? originalValue = Configuration![key]; @@ -124,7 +123,7 @@ public bool TryGet(string key, out string? value) /// public void Set(string key, string? value) { - ArgumentGuard.NotNull(key); + ArgumentException.ThrowIfNullOrEmpty(key); EnsureInitialized(); Configuration![key] = value; diff --git a/src/Configuration/src/Encryption/EncryptionResolverSource.cs b/src/Configuration/src/Encryption/EncryptionResolverSource.cs index f1a4099ee8..f4682c7518 100644 --- a/src/Configuration/src/Encryption/EncryptionResolverSource.cs +++ b/src/Configuration/src/Encryption/EncryptionResolverSource.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.Encryption; @@ -37,9 +36,9 @@ internal sealed class EncryptionResolverSource : IConfigurationSource /// public EncryptionResolverSource(IList sources, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(sources); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(sources); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); _textDecryptor = textDecryptor; Sources = sources.ToList(); @@ -60,9 +59,9 @@ public EncryptionResolverSource(IList sources, ITextDecryp /// public EncryptionResolverSource(IConfigurationRoot root, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(root); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); _configuration = root; _textDecryptor = textDecryptor; @@ -80,11 +79,11 @@ public EncryptionResolverSource(IConfigurationRoot root, ITextDecryptor textDecr /// public IConfigurationProvider Build(IConfigurationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (_configuration != null) { - var configurationView = new ConfigurationView(_configuration.Providers.ToList()); + var configurationView = new ConfigurationView(_configuration.Providers.ToArray()); return new EncryptionResolverProvider(configurationView, _textDecryptor, LoggerFactory); } diff --git a/src/Configuration/src/Encryption/EncryptionServiceCollectionExtensions.cs b/src/Configuration/src/Encryption/EncryptionServiceCollectionExtensions.cs index 3bcccb9486..928eb3ecb2 100644 --- a/src/Configuration/src/Encryption/EncryptionServiceCollectionExtensions.cs +++ b/src/Configuration/src/Encryption/EncryptionServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Configuration.Encryption.Decryption; namespace Steeltoe.Configuration.Encryption; @@ -30,6 +29,9 @@ public static class EncryptionServiceCollectionExtensions /// public static IConfiguration ConfigureEncryptionResolver(this IServiceCollection services, IConfiguration configuration) { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ITextDecryptor textDecryptor = ConfigServerEncryptionSettings.CreateTextDecryptor(configuration); return ConfigureEncryptionResolver(services, configuration, textDecryptor, NullLoggerFactory.Instance); } @@ -79,10 +81,10 @@ public static IConfiguration ConfigureEncryptionResolver(this IServiceCollection public static IConfiguration ConfigureEncryptionResolver(this IServiceCollection services, IConfiguration configuration, ITextDecryptor textDecryptor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(textDecryptor); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(textDecryptor); + ArgumentNullException.ThrowIfNull(loggerFactory); IConfiguration newConfiguration = configuration.AddEncryptionResolver(textDecryptor, loggerFactory); services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), newConfiguration)); @@ -130,9 +132,9 @@ public static IConfiguration ConfigureConfigServerEncryptionResolver(this IServi public static IConfiguration ConfigureConfigServerEncryptionResolver(this IServiceCollection services, IConfiguration configuration, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(loggerFactory); ITextDecryptor textDecryptor = ConfigServerEncryptionSettings.CreateTextDecryptor(configuration); diff --git a/src/Configuration/src/Encryption/HostBuilderWrapperExtensions.cs b/src/Configuration/src/Encryption/HostBuilderWrapperExtensions.cs index c84cf0d7c2..29d317a917 100644 --- a/src/Configuration/src/Encryption/HostBuilderWrapperExtensions.cs +++ b/src/Configuration/src/Encryption/HostBuilderWrapperExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.Hosting; using Steeltoe.Common.Logging; using Steeltoe.Configuration.Encryption.Decryption; @@ -14,8 +13,8 @@ internal static class HostBuilderWrapperExtensions { public static HostBuilderWrapper AddEncryptionResolver(this HostBuilderWrapper wrapper, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(wrapper); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(wrapper); + ArgumentNullException.ThrowIfNull(loggerFactory); wrapper.ConfigureAppConfiguration((context, configurationBuilder) => { @@ -25,7 +24,7 @@ public static HostBuilderWrapper AddEncryptionResolver(this HostBuilderWrapper w if (loggerFactory is IBootstrapLoggerFactory) { - BootstrapLoggerHostedService.Register(loggerFactory, wrapper); + BootstrapLoggerHostedService.Register(wrapper); } return wrapper; diff --git a/src/Configuration/src/Kubernetes.ServiceBinding/ConfigurationBuilderExtensions.cs b/src/Configuration/src/Kubernetes.ServiceBinding/ConfigurationBuilderExtensions.cs index 58f748e5a1..aa0307da5c 100644 --- a/src/Configuration/src/Kubernetes.ServiceBinding/ConfigurationBuilderExtensions.cs +++ b/src/Configuration/src/Kubernetes.ServiceBinding/ConfigurationBuilderExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Configuration.Kubernetes.ServiceBinding.PostProcessors; namespace Steeltoe.Configuration.Kubernetes.ServiceBinding; @@ -83,10 +82,10 @@ public static IConfigurationBuilder AddKubernetesServiceBindings(this IConfigura public static IConfigurationBuilder AddKubernetesServiceBindings(this IConfigurationBuilder builder, bool optional, bool reloadOnChange, Predicate ignoreKeyPredicate, IServiceBindingsReader serviceBindingsReader, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(ignoreKeyPredicate); - ArgumentGuard.NotNull(serviceBindingsReader); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(ignoreKeyPredicate); + ArgumentNullException.ThrowIfNull(serviceBindingsReader); + ArgumentNullException.ThrowIfNull(loggerFactory); if (!builder.Sources.OfType().Any()) { diff --git a/src/Configuration/src/Kubernetes.ServiceBinding/KubernetesServiceBindingConfigurationSource.cs b/src/Configuration/src/Kubernetes.ServiceBinding/KubernetesServiceBindingConfigurationSource.cs index bddb747525..5ff9d61f14 100644 --- a/src/Configuration/src/Kubernetes.ServiceBinding/KubernetesServiceBindingConfigurationSource.cs +++ b/src/Configuration/src/Kubernetes.ServiceBinding/KubernetesServiceBindingConfigurationSource.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; -using Steeltoe.Common; namespace Steeltoe.Configuration.Kubernetes.ServiceBinding; @@ -20,14 +19,14 @@ internal sealed class KubernetesServiceBindingConfigurationSource : PostProcesso public KubernetesServiceBindingConfigurationSource(IServiceBindingsReader reader) { - ArgumentGuard.NotNull(reader); + ArgumentNullException.ThrowIfNull(reader); FileProvider = reader.GetRootDirectory(); } public IConfigurationProvider Build(IConfigurationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); CaptureConfigurationBuilder(builder); return new KubernetesServiceBindingConfigurationProvider(this); diff --git a/src/Configuration/src/Placeholder/ConfigurationBuilderExtensions.cs b/src/Configuration/src/Placeholder/ConfigurationBuilderExtensions.cs index dde68767da..a3abe281b2 100644 --- a/src/Configuration/src/Placeholder/ConfigurationBuilderExtensions.cs +++ b/src/Configuration/src/Placeholder/ConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.Placeholder; @@ -21,7 +20,7 @@ internal static class ConfigurationBuilderExtensions public static TSource? FindConfigurationSource(this IConfigurationBuilder builder) where TSource : class, IConfigurationSource { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); return FindConfigurationSource(builder.Sources); } @@ -62,7 +61,7 @@ internal static class ConfigurationBuilderExtensions public static IEnumerable GetConfigurationSources(this IConfigurationBuilder builder) where TSource : class, IConfigurationSource { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); var sources = new List(); AddConfigurationSources(builder.Sources, sources); diff --git a/src/Configuration/src/Placeholder/ConfigurationView.cs b/src/Configuration/src/Placeholder/ConfigurationView.cs index c5f0360c2d..a9f8dfec6a 100644 --- a/src/Configuration/src/Placeholder/ConfigurationView.cs +++ b/src/Configuration/src/Placeholder/ConfigurationView.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; namespace Steeltoe.Configuration.Placeholder; @@ -44,7 +43,7 @@ public string? this[string key] /// public ConfigurationView(IList providers) { - ArgumentGuard.NotNull(providers); + ArgumentNullException.ThrowIfNull(providers); _providers = providers; } diff --git a/src/Configuration/src/Placeholder/PlaceholderConfigurationExtensions.cs b/src/Configuration/src/Placeholder/PlaceholderConfigurationExtensions.cs index 5116761176..1e454dde37 100644 --- a/src/Configuration/src/Placeholder/PlaceholderConfigurationExtensions.cs +++ b/src/Configuration/src/Placeholder/PlaceholderConfigurationExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.Placeholder; @@ -45,8 +44,8 @@ public static IConfigurationBuilder AddPlaceholderResolver(this IConfigurationBu /// public static IConfigurationBuilder AddPlaceholderResolver(this IConfigurationBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); if (!builder.Sources.Any(source => source is PlaceholderResolverSource)) { @@ -97,8 +96,8 @@ public static IConfiguration AddPlaceholderResolver(this IConfiguration configur /// public static IConfiguration AddPlaceholderResolver(this IConfiguration configuration, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(loggerFactory); if (configuration is not IConfigurationRoot root) { @@ -150,8 +149,8 @@ public static ConfigurationManager AddPlaceholderResolver(this ConfigurationMana /// public static ConfigurationManager AddPlaceholderResolver(this ConfigurationManager configurationManager, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(configurationManager); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(configurationManager); + ArgumentNullException.ThrowIfNull(loggerFactory); ((IConfigurationBuilder)configurationManager).AddPlaceholderResolver(loggerFactory); diff --git a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs index cf3ad94ba5..da71bf5b15 100644 --- a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs +++ b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; using Steeltoe.Common.Configuration; namespace Steeltoe.Configuration.Placeholder; @@ -41,8 +40,8 @@ internal sealed class PlaceholderResolverProvider : IPlaceholderResolverProvider /// public PlaceholderResolverProvider(IConfigurationRoot root, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(root); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(loggerFactory); Configuration = root; } @@ -59,8 +58,8 @@ public PlaceholderResolverProvider(IConfigurationRoot root, ILoggerFactory logge /// public PlaceholderResolverProvider(IList providers, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(providers); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(providers); + ArgumentNullException.ThrowIfNull(loggerFactory); Providers = providers; } @@ -79,7 +78,7 @@ public PlaceholderResolverProvider(IList providers, ILog /// public bool TryGet(string key, out string? value) { - ArgumentGuard.NotNull(key); + ArgumentException.ThrowIfNullOrEmpty(key); EnsureInitialized(); string? originalValue = Configuration![key]; @@ -104,7 +103,7 @@ public bool TryGet(string key, out string? value) /// public void Set(string key, string? value) { - ArgumentGuard.NotNull(key); + ArgumentException.ThrowIfNullOrEmpty(key); EnsureInitialized(); Configuration![key] = value; diff --git a/src/Configuration/src/Placeholder/PlaceholderResolverSource.cs b/src/Configuration/src/Placeholder/PlaceholderResolverSource.cs index 180b1fd3ca..b081067e4c 100644 --- a/src/Configuration/src/Placeholder/PlaceholderResolverSource.cs +++ b/src/Configuration/src/Placeholder/PlaceholderResolverSource.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.Placeholder; @@ -33,8 +32,8 @@ internal sealed class PlaceholderResolverSource : IConfigurationSource /// public PlaceholderResolverSource(IList sources, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(sources); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(sources); + ArgumentNullException.ThrowIfNull(loggerFactory); Sources = sources.ToList(); LoggerFactory = loggerFactory; @@ -51,8 +50,8 @@ public PlaceholderResolverSource(IList sources, ILoggerFac /// public PlaceholderResolverSource(IConfigurationRoot root, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(root); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(root); + ArgumentNullException.ThrowIfNull(loggerFactory); _configuration = root; LoggerFactory = loggerFactory; @@ -69,11 +68,11 @@ public PlaceholderResolverSource(IConfigurationRoot root, ILoggerFactory loggerF /// public IConfigurationProvider Build(IConfigurationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (_configuration != null) { - var configurationView = new ConfigurationView(_configuration.Providers.ToList()); + var configurationView = new ConfigurationView(_configuration.Providers.ToArray()); return new PlaceholderResolverProvider(configurationView, LoggerFactory); } diff --git a/src/Configuration/src/Placeholder/PlaceholderServiceCollectionExtensions.cs b/src/Configuration/src/Placeholder/PlaceholderServiceCollectionExtensions.cs index 0e60e93464..2b77a0c1d7 100644 --- a/src/Configuration/src/Placeholder/PlaceholderServiceCollectionExtensions.cs +++ b/src/Configuration/src/Placeholder/PlaceholderServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.Placeholder; @@ -51,9 +50,9 @@ public static IConfiguration ConfigurePlaceholderResolver(this IServiceCollectio /// public static IConfiguration ConfigurePlaceholderResolver(this IServiceCollection services, IConfiguration configuration, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(loggerFactory); IConfiguration newConfiguration = configuration.AddPlaceholderResolver(loggerFactory); services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), newConfiguration)); diff --git a/src/Configuration/src/RandomValue/RandomValueConfigurationBuilderExtensions.cs b/src/Configuration/src/RandomValue/RandomValueConfigurationBuilderExtensions.cs index c0a6d97fe8..72446533f1 100644 --- a/src/Configuration/src/RandomValue/RandomValueConfigurationBuilderExtensions.cs +++ b/src/Configuration/src/RandomValue/RandomValueConfigurationBuilderExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.RandomValue; @@ -76,8 +75,8 @@ public static IConfigurationBuilder AddRandomValueSource(this IConfigurationBuil /// public static IConfigurationBuilder AddRandomValueSource(this IConfigurationBuilder builder, string? prefix, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); if (prefix != null && !prefix.EndsWith(':')) { diff --git a/src/Configuration/src/RandomValue/RandomValueProvider.cs b/src/Configuration/src/RandomValue/RandomValueProvider.cs index c4f5340b07..d82638e409 100644 --- a/src/Configuration/src/RandomValue/RandomValueProvider.cs +++ b/src/Configuration/src/RandomValue/RandomValueProvider.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.RandomValue; @@ -29,8 +28,8 @@ internal sealed class RandomValueProvider : ConfigurationProvider /// public RandomValueProvider(string prefix, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(prefix); - ArgumentGuard.NotNull(loggerFactory); + ArgumentException.ThrowIfNullOrEmpty(prefix); + ArgumentNullException.ThrowIfNull(loggerFactory); _prefix = prefix; _logger = loggerFactory.CreateLogger(); @@ -51,7 +50,7 @@ public RandomValueProvider(string prefix, ILoggerFactory loggerFactory) /// public override bool TryGet(string key, out string? value) { - ArgumentGuard.NotNull(key); + ArgumentException.ThrowIfNullOrEmpty(key); value = null; diff --git a/src/Configuration/src/RandomValue/RandomValueSource.cs b/src/Configuration/src/RandomValue/RandomValueSource.cs index e20da25301..be23d9f9b7 100644 --- a/src/Configuration/src/RandomValue/RandomValueSource.cs +++ b/src/Configuration/src/RandomValue/RandomValueSource.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.RandomValue; @@ -41,7 +40,7 @@ public RandomValueSource(ILoggerFactory loggerFactory) /// public RandomValueSource(string? prefix, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(loggerFactory); Prefix = prefix ?? DefaultPrefix; LoggerFactory = loggerFactory; diff --git a/src/Configuration/src/SpringBoot/SpringBootCommandLineProvider.cs b/src/Configuration/src/SpringBoot/SpringBootCommandLineProvider.cs index 2b9c65c1f0..307455b6b4 100644 --- a/src/Configuration/src/SpringBoot/SpringBootCommandLineProvider.cs +++ b/src/Configuration/src/SpringBoot/SpringBootCommandLineProvider.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.CommandLine; -using Steeltoe.Common; namespace Steeltoe.Configuration.SpringBoot; @@ -26,7 +25,7 @@ internal sealed class SpringBootCommandLineProvider : ConfigurationProvider /// public SpringBootCommandLineProvider(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); _configuration = configuration; } diff --git a/src/Configuration/src/SpringBoot/SpringBootCommandLineSource.cs b/src/Configuration/src/SpringBoot/SpringBootCommandLineSource.cs index 695761f9d2..f2711d8a00 100644 --- a/src/Configuration/src/SpringBoot/SpringBootCommandLineSource.cs +++ b/src/Configuration/src/SpringBoot/SpringBootCommandLineSource.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Configuration.SpringBoot; @@ -22,7 +21,7 @@ internal sealed class SpringBootCommandLineSource : IConfigurationSource /// public SpringBootCommandLineSource(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); Configuration = configuration; } diff --git a/src/Configuration/src/SpringBoot/SpringBootConfigurationBuilderExtensions.cs b/src/Configuration/src/SpringBoot/SpringBootConfigurationBuilderExtensions.cs index fcba59da7d..cf4d69dd87 100644 --- a/src/Configuration/src/SpringBoot/SpringBootConfigurationBuilderExtensions.cs +++ b/src/Configuration/src/SpringBoot/SpringBootConfigurationBuilderExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; namespace Steeltoe.Configuration.SpringBoot; @@ -41,8 +40,8 @@ public static IConfigurationBuilder AddSpringBootFromEnvironmentVariable(this IC /// public static IConfigurationBuilder AddSpringBootFromEnvironmentVariable(this IConfigurationBuilder builder, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(loggerFactory); builder.Add(new SpringBootEnvironmentVariableSource()); @@ -86,9 +85,9 @@ public static IConfigurationBuilder AddSpringBootFromCommandLine(this IConfigura public static IConfigurationBuilder AddSpringBootFromCommandLine(this IConfigurationBuilder builder, IConfiguration configuration, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(loggerFactory); builder.Add(new SpringBootCommandLineSource(configuration)); diff --git a/src/Configuration/src/SpringBoot/SpringBootEnvironmentVariableProvider.cs b/src/Configuration/src/SpringBoot/SpringBootEnvironmentVariableProvider.cs index daa7ea561f..56fa996b9e 100644 --- a/src/Configuration/src/SpringBoot/SpringBootEnvironmentVariableProvider.cs +++ b/src/Configuration/src/SpringBoot/SpringBootEnvironmentVariableProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration.Json; -using Steeltoe.Common; namespace Steeltoe.Configuration.SpringBoot; @@ -35,7 +34,7 @@ public SpringBootEnvironmentVariableProvider() public SpringBootEnvironmentVariableProvider(string springApplicationJson) : base(new JsonStreamConfigurationSource()) { - ArgumentGuard.NotNull(springApplicationJson); + ArgumentException.ThrowIfNullOrWhiteSpace(springApplicationJson); _springApplicationJson = springApplicationJson; } diff --git a/src/Configuration/test/ConfigServer.Integration.Test/HomeController.cs b/src/Configuration/test/ConfigServer.Integration.Test/HomeController.cs index ae40fbeb13..0312ec8c3b 100644 --- a/src/Configuration/test/ConfigServer.Integration.Test/HomeController.cs +++ b/src/Configuration/test/ConfigServer.Integration.Test/HomeController.cs @@ -5,7 +5,6 @@ using System.Text; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.HealthChecks; @@ -18,8 +17,8 @@ public sealed class HomeController : Controller public HomeController(IOptions options, IHealthContributor healthContributor) { - ArgumentGuard.NotNull(healthContributor); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(healthContributor); + ArgumentNullException.ThrowIfNull(options); _options = options.Value; _healthContributor = healthContributor; diff --git a/src/Configuration/test/ConfigServer.Test/ForwardingHttpClientHandler.cs b/src/Configuration/test/ConfigServer.Test/ForwardingHttpClientHandler.cs index 8c89c30ac7..27100c24a7 100644 --- a/src/Configuration/test/ConfigServer.Test/ForwardingHttpClientHandler.cs +++ b/src/Configuration/test/ConfigServer.Test/ForwardingHttpClientHandler.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Configuration.ConfigServer.Test; internal sealed class ForwardingHttpClientHandler : HttpClientHandler @@ -12,7 +10,7 @@ internal sealed class ForwardingHttpClientHandler : HttpClientHandler public ForwardingHttpClientHandler(HttpMessageHandler innerHandler) { - ArgumentGuard.NotNull(innerHandler); + ArgumentNullException.ThrowIfNull(innerHandler); _invoker = new HttpMessageInvoker(innerHandler, false); } diff --git a/src/Connectors/src/Connectors/ConnectionStringPostProcessorConfigurationSource.cs b/src/Connectors/src/Connectors/ConnectionStringPostProcessorConfigurationSource.cs index 6456068b42..3199b4065f 100644 --- a/src/Connectors/src/Connectors/ConnectionStringPostProcessorConfigurationSource.cs +++ b/src/Connectors/src/Connectors/ConnectionStringPostProcessorConfigurationSource.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Configuration; namespace Steeltoe.Connectors; @@ -19,7 +18,7 @@ public ConnectionStringPostProcessorConfigurationSource(bool detectConfiguration public IConfigurationProvider Build(IConfigurationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); CaptureConfigurationBuilder(builder); return new ConnectionStringPostProcessorConfigurationProvider(this, _detectConfigurationChanges); diff --git a/src/Connectors/src/Connectors/Connector.cs b/src/Connectors/src/Connectors/Connector.cs index d249cc234b..8baafdc498 100644 --- a/src/Connectors/src/Connectors/Connector.cs +++ b/src/Connectors/src/Connectors/Connector.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Connectors; @@ -61,9 +60,9 @@ public TOptions Options public Connector(IServiceProvider serviceProvider, string serviceBindingName, ConnectorCreateConnection createConnection, bool useSingletonConnection) { - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(serviceBindingName); - ArgumentGuard.NotNull(createConnection); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceBindingName); + ArgumentNullException.ThrowIfNull(createConnection); _serviceBindingName = serviceBindingName; _createConnection = () => createConnection(serviceProvider, serviceBindingName); @@ -167,8 +166,8 @@ private sealed class ConnectionWithOptionsSnapshot public ConnectionWithOptionsSnapshot(TConnection connection, TOptions options) { - ArgumentGuard.NotNull(connection); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(options); Connection = connection; Options = options; diff --git a/src/Connectors/src/Connectors/ConnectorAddOptionsBuilder.cs b/src/Connectors/src/Connectors/ConnectorAddOptionsBuilder.cs index 4e7c7c4e20..967598860b 100644 --- a/src/Connectors/src/Connectors/ConnectorAddOptionsBuilder.cs +++ b/src/Connectors/src/Connectors/ConnectorAddOptionsBuilder.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Connectors; @@ -35,8 +34,8 @@ public sealed class ConnectorAddOptionsBuilder internal ConnectorAddOptionsBuilder(ConnectorCreateConnection createConnection, ConnectorCreateHealthContributor createHealthContributor) { - ArgumentGuard.NotNull(createConnection); - ArgumentGuard.NotNull(createHealthContributor); + ArgumentNullException.ThrowIfNull(createConnection); + ArgumentNullException.ThrowIfNull(createHealthContributor); CreateConnection = createConnection; CreateHealthContributor = createHealthContributor; diff --git a/src/Connectors/src/Connectors/ConnectorFactory.cs b/src/Connectors/src/Connectors/ConnectorFactory.cs index 4889a1effc..3f9e7d2108 100644 --- a/src/Connectors/src/Connectors/ConnectorFactory.cs +++ b/src/Connectors/src/Connectors/ConnectorFactory.cs @@ -36,9 +36,10 @@ public sealed class ConnectorFactory : IDisposable public ConnectorFactory(IServiceProvider serviceProvider, IReadOnlySet serviceBindingNames, ConnectorCreateConnection createConnection, bool useSingletonConnection) { - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(serviceBindingNames); - ArgumentGuard.NotNull(createConnection); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceBindingNames); + ArgumentGuard.ElementsNotNull(serviceBindingNames); + ArgumentNullException.ThrowIfNull(createConnection); _serviceProvider = serviceProvider; ServiceBindingNames = serviceBindingNames; diff --git a/src/Connectors/src/Connectors/CosmosDb/CosmosDbConfigurationBuilderExtensions.cs b/src/Connectors/src/Connectors/CosmosDb/CosmosDbConfigurationBuilderExtensions.cs index ced54d432c..a7e43eb0c5 100644 --- a/src/Connectors/src/Connectors/CosmosDb/CosmosDbConfigurationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/CosmosDb/CosmosDbConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Connectors.CosmosDb; @@ -37,7 +36,7 @@ public static IConfigurationBuilder ConfigureCosmosDb(this IConfigurationBuilder /// public static IConfigurationBuilder ConfigureCosmosDb(this IConfigurationBuilder builder, Action? configureAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); ConnectorConfigurer.Configure(builder, configureAction, new CosmosDbConnectionStringPostProcessor()); return builder; diff --git a/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs b/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs index 3f80cff2c8..42c9d2a07b 100644 --- a/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs +++ b/src/Connectors/src/Connectors/CosmosDb/CosmosDbHealthContributor.cs @@ -5,7 +5,6 @@ using System.Data.Common; using System.Runtime.ExceptionServices; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -30,10 +29,10 @@ internal sealed class CosmosDbHealthContributor : IHealthContributor, IDisposabl public CosmosDbHealthContributor(string serviceName, IServiceProvider serviceProvider, CosmosDbPackageResolver packageResolver, ILogger logger) { - ArgumentGuard.NotNull(serviceName); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(packageResolver); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(serviceName); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(packageResolver); + ArgumentNullException.ThrowIfNull(logger); ServiceName = serviceName; _clientFactory = new CosmosClientShimFactory(serviceName, serviceProvider, packageResolver); @@ -104,9 +103,9 @@ private sealed class CosmosClientShimFactory public CosmosClientShimFactory(string serviceName, IServiceProvider serviceProvider, CosmosDbPackageResolver packageResolver) { - ArgumentGuard.NotNull(serviceName); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(serviceName); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(packageResolver); ConnectorFactoryShim connectorFactoryShim = ConnectorFactoryShim.FromServiceProvider(serviceProvider, packageResolver.CosmosClientClass.Type); diff --git a/src/Connectors/src/Connectors/CosmosDb/CosmosDbHostApplicationBuilderExtensions.cs b/src/Connectors/src/Connectors/CosmosDb/CosmosDbHostApplicationBuilderExtensions.cs index afa38d377b..9f079a0e62 100644 --- a/src/Connectors/src/Connectors/CosmosDb/CosmosDbHostApplicationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/CosmosDb/CosmosDbHostApplicationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Hosting; -using Steeltoe.Common; namespace Steeltoe.Connectors.CosmosDb; @@ -43,7 +42,7 @@ public static IHostApplicationBuilder AddCosmosDb(this IHostApplicationBuilder b public static IHostApplicationBuilder AddCosmosDb(this IHostApplicationBuilder builder, Action? configureAction, Action? addAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Configuration.ConfigureCosmosDb(configureAction); builder.Services.AddCosmosDb(builder.Configuration, addAction); diff --git a/src/Connectors/src/Connectors/CosmosDb/CosmosDbServiceCollectionExtensions.cs b/src/Connectors/src/Connectors/CosmosDb/CosmosDbServiceCollectionExtensions.cs index c101d37457..ee9a04bdb6 100644 --- a/src/Connectors/src/Connectors/CosmosDb/CosmosDbServiceCollectionExtensions.cs +++ b/src/Connectors/src/Connectors/CosmosDb/CosmosDbServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.CosmosDb.DynamicTypeAccess; using Steeltoe.Connectors.DynamicTypeAccess; @@ -58,9 +57,9 @@ public static IServiceCollection AddCosmosDb(this IServiceCollection services, I private static IServiceCollection AddCosmosDb(this IServiceCollection services, IConfiguration configuration, CosmosDbPackageResolver packageResolver, Action? addAction = null) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(packageResolver); if (!ConnectorFactoryShim.IsRegistered(packageResolver.CosmosClientClass.Type, services)) { diff --git a/src/Connectors/src/Connectors/CosmosDb/DynamicTypeAccess/CosmosClientShim.cs b/src/Connectors/src/Connectors/CosmosDb/DynamicTypeAccess/CosmosClientShim.cs index 476bc965f2..bf42c3cdfe 100644 --- a/src/Connectors/src/Connectors/CosmosDb/DynamicTypeAccess/CosmosClientShim.cs +++ b/src/Connectors/src/Connectors/CosmosDb/DynamicTypeAccess/CosmosClientShim.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.CosmosDb.DynamicTypeAccess; @@ -23,7 +22,7 @@ private CosmosClientShim(InstanceAccessor instanceAccessor) public static CosmosClientShim CreateInstance(CosmosDbPackageResolver packageResolver, string? connectionString) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.CosmosClientClass.CreateInstance(connectionString, null); return new CosmosClientShim(instanceAccessor); diff --git a/src/Connectors/src/Connectors/DbConnectionStringBuilderWrapper.cs b/src/Connectors/src/Connectors/DbConnectionStringBuilderWrapper.cs index e0e62d0252..f7c2e3c7d0 100644 --- a/src/Connectors/src/Connectors/DbConnectionStringBuilderWrapper.cs +++ b/src/Connectors/src/Connectors/DbConnectionStringBuilderWrapper.cs @@ -4,7 +4,6 @@ using System.Data.Common; using System.Diagnostics.CodeAnalysis; -using Steeltoe.Common; namespace Steeltoe.Connectors; @@ -32,7 +31,7 @@ public object? this[string keyword] public DbConnectionStringBuilderWrapper(DbConnectionStringBuilder innerBuilder) { - ArgumentGuard.NotNull(innerBuilder); + ArgumentNullException.ThrowIfNull(innerBuilder); _innerBuilder = innerBuilder; } diff --git a/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorFactoryShim.cs b/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorFactoryShim.cs index 3f340b6099..98a889d57f 100644 --- a/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorFactoryShim.cs +++ b/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorFactoryShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.DynamicTypeAccess; @@ -23,8 +22,8 @@ private ConnectorFactoryShim(Type connectionType, InstanceAccessor instanceAcces public static bool IsRegistered(Type connectionType, IServiceCollection services) { - ArgumentGuard.NotNull(connectionType); - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(connectionType); + ArgumentNullException.ThrowIfNull(services); TypeAccessor typeAccessor = MakeGenericTypeAccessor(connectionType); return services.Any(descriptor => descriptor.ServiceType == typeAccessor.Type); @@ -33,8 +32,8 @@ public static bool IsRegistered(Type connectionType, IServiceCollection services public static void Register(Type connectionType, IServiceCollection services, IReadOnlySet serviceBindingNames, ConnectorCreateConnection createConnection, bool useSingletonConnection) { - ArgumentGuard.NotNull(connectionType); - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(connectionType); + ArgumentNullException.ThrowIfNull(services); TypeAccessor typeAccessor = MakeGenericTypeAccessor(connectionType); @@ -44,8 +43,8 @@ public static void Register(Type connectionType, IServiceCollection services, IR public static ConnectorFactoryShim FromServiceProvider(IServiceProvider serviceProvider, Type connectionType) { - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(connectionType); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(connectionType); TypeAccessor typeAccessor = MakeGenericTypeAccessor(connectionType); object instance = serviceProvider.GetRequiredService(typeAccessor.Type); diff --git a/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorShim.cs b/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorShim.cs index 61dda748f7..d8814f9959 100644 --- a/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorShim.cs +++ b/src/Connectors/src/Connectors/DynamicTypeAccess/ConnectorShim.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.DynamicTypeAccess; @@ -21,8 +20,8 @@ public ConnectorShim(Type connectionType, object instance) private static InstanceAccessor CreateAccessor(Type connectionType, object instance) { - ArgumentGuard.NotNull(connectionType); - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(connectionType); + ArgumentNullException.ThrowIfNull(instance); var typeAccessor = TypeAccessor.MakeGenericAccessor(typeof(Connector<,>), typeof(TOptions), connectionType); return new InstanceAccessor(typeAccessor, instance); diff --git a/src/Connectors/src/Connectors/MongoDb/DynamicTypeAccess/MongoClientShim.cs b/src/Connectors/src/Connectors/MongoDb/DynamicTypeAccess/MongoClientShim.cs index b726964e6e..619b52e336 100644 --- a/src/Connectors/src/Connectors/MongoDb/DynamicTypeAccess/MongoClientShim.cs +++ b/src/Connectors/src/Connectors/MongoDb/DynamicTypeAccess/MongoClientShim.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.MongoDb.DynamicTypeAccess; @@ -16,7 +15,7 @@ private MongoClientShim(InstanceAccessor instanceAccessor) public static MongoClientShim CreateInstance(MongoDbPackageResolver packageResolver, string? connectionString) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); // Ensure the argument is never null, so the proper ctor overload is selected (prevents AmbiguousMatchException). string constructorArgument = connectionString ?? string.Empty; diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbConfigurationBuilderExtensions.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbConfigurationBuilderExtensions.cs index d8d4725a26..a95b0b0100 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbConfigurationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Connectors.MongoDb; @@ -37,7 +36,7 @@ public static IConfigurationBuilder ConfigureMongoDb(this IConfigurationBuilder /// public static IConfigurationBuilder ConfigureMongoDb(this IConfigurationBuilder builder, Action? configureAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); ConnectorConfigurer.Configure(builder, configureAction, new MongoDbConnectionStringPostProcessor()); return builder; diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs index df6149cac3..6f774fd16a 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbConnectionStringBuilder.cs @@ -7,7 +7,6 @@ using System.Globalization; using System.Web; using Microsoft.AspNetCore.Http; -using Steeltoe.Common; namespace Steeltoe.Connectors.MongoDb; @@ -31,7 +30,7 @@ public object? this[string keyword] { get { - ArgumentGuard.NotNull(keyword); + ArgumentException.ThrowIfNullOrWhiteSpace(keyword); if (string.Equals(keyword, KnownKeywords.Url, StringComparison.OrdinalIgnoreCase)) { @@ -49,7 +48,7 @@ public object? this[string keyword] } set { - ArgumentGuard.NotNull(keyword); + ArgumentException.ThrowIfNullOrWhiteSpace(keyword); if (string.Equals(keyword, KnownKeywords.Url, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs index cfb196bc67..79a8bb51a4 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs @@ -4,7 +4,6 @@ using System.Runtime.ExceptionServices; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -26,10 +25,10 @@ internal sealed class MongoDbHealthContributor : IHealthContributor public MongoDbHealthContributor(string serviceName, IServiceProvider serviceProvider, MongoDbPackageResolver packageResolver, ILogger logger) { - ArgumentGuard.NotNull(serviceName); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(packageResolver); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(serviceName); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(packageResolver); + ArgumentNullException.ThrowIfNull(logger); ServiceName = serviceName; _clientFactory = new MongoClientInterfaceShimFactory(serviceName, serviceProvider, packageResolver); @@ -92,9 +91,9 @@ private sealed class MongoClientInterfaceShimFactory public MongoClientInterfaceShimFactory(string serviceName, IServiceProvider serviceProvider, MongoDbPackageResolver packageResolver) { - ArgumentGuard.NotNull(serviceName); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(serviceName); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(packageResolver); ConnectorFactoryShim connectorFactoryShim = ConnectorFactoryShim.FromServiceProvider(serviceProvider, packageResolver.MongoClientInterface.Type); diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbHostApplicationBuilderExtensions.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbHostApplicationBuilderExtensions.cs index 02c14a175a..43a254b4fd 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbHostApplicationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbHostApplicationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Hosting; -using Steeltoe.Common; namespace Steeltoe.Connectors.MongoDb; @@ -43,7 +42,7 @@ public static IHostApplicationBuilder AddMongoDb(this IHostApplicationBuilder bu public static IHostApplicationBuilder AddMongoDb(this IHostApplicationBuilder builder, Action? configureAction, Action? addAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Configuration.ConfigureMongoDb(configureAction); builder.Services.AddMongoDb(builder.Configuration, addAction); diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbServiceCollectionExtensions.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbServiceCollectionExtensions.cs index 40341c069c..b95ccd8b06 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbServiceCollectionExtensions.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.MongoDb.DynamicTypeAccess; @@ -58,9 +57,9 @@ public static IServiceCollection AddMongoDb(this IServiceCollection services, IC private static IServiceCollection AddMongoDb(this IServiceCollection services, IConfiguration configuration, MongoDbPackageResolver packageResolver, Action? addAction = null) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(packageResolver); if (!ConnectorFactoryShim.IsRegistered(packageResolver.MongoClientInterface.Type, services)) { diff --git a/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionShim.cs b/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionShim.cs index fa4602fdb3..d6d14950ef 100644 --- a/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionShim.cs +++ b/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Data.Common; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.MySql.DynamicTypeAccess; @@ -19,7 +18,7 @@ private MySqlConnectionShim(InstanceAccessor instanceAccessor) public static MySqlConnectionShim CreateInstance(MySqlPackageResolver packageResolver, string? connectionString) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.MySqlConnectionClass.CreateInstance(connectionString); return new MySqlConnectionShim(instanceAccessor); diff --git a/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionStringBuilderShim.cs b/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionStringBuilderShim.cs index 84178e12f7..cb4d299ed0 100644 --- a/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionStringBuilderShim.cs +++ b/src/Connectors/src/Connectors/MySql/DynamicTypeAccess/MySqlConnectionStringBuilderShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Data.Common; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.MySql.DynamicTypeAccess; @@ -19,7 +18,7 @@ private MySqlConnectionStringBuilderShim(InstanceAccessor instanceAccessor) public static MySqlConnectionStringBuilderShim CreateInstance(MySqlPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.MySqlConnectionStringBuilderClass.CreateInstance(null); return new MySqlConnectionStringBuilderShim(instanceAccessor); diff --git a/src/Connectors/src/Connectors/MySql/MySqlConfigurationBuilderExtensions.cs b/src/Connectors/src/Connectors/MySql/MySqlConfigurationBuilderExtensions.cs index 0083eca4f2..9ac7ccc117 100644 --- a/src/Connectors/src/Connectors/MySql/MySqlConfigurationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/MySql/MySqlConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Connectors.MySql.DynamicTypeAccess; namespace Steeltoe.Connectors.MySql; @@ -44,8 +43,8 @@ public static IConfigurationBuilder ConfigureMySql(this IConfigurationBuilder bu internal static IConfigurationBuilder ConfigureMySql(this IConfigurationBuilder builder, MySqlPackageResolver packageResolver, Action? configureAction = null) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(packageResolver); ConnectorConfigurer.Configure(builder, configureAction, new MySqlConnectionStringPostProcessor(packageResolver)); return builder; diff --git a/src/Connectors/src/Connectors/MySql/MySqlConnectionStringPostProcessor.cs b/src/Connectors/src/Connectors/MySql/MySqlConnectionStringPostProcessor.cs index a61c7e7b91..1dd9485a17 100644 --- a/src/Connectors/src/Connectors/MySql/MySqlConnectionStringPostProcessor.cs +++ b/src/Connectors/src/Connectors/MySql/MySqlConnectionStringPostProcessor.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Connectors.MySql.DynamicTypeAccess; namespace Steeltoe.Connectors.MySql; @@ -15,7 +14,7 @@ internal sealed class MySqlConnectionStringPostProcessor : ConnectionStringPostP public MySqlConnectionStringPostProcessor(MySqlPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); _packageResolver = packageResolver; } diff --git a/src/Connectors/src/Connectors/MySql/MySqlHostApplicationBuilderExtensions.cs b/src/Connectors/src/Connectors/MySql/MySqlHostApplicationBuilderExtensions.cs index fa67271cea..c911d6d671 100644 --- a/src/Connectors/src/Connectors/MySql/MySqlHostApplicationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/MySql/MySqlHostApplicationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Hosting; -using Steeltoe.Common; using Steeltoe.Connectors.MySql.DynamicTypeAccess; namespace Steeltoe.Connectors.MySql; @@ -50,8 +49,8 @@ public static IHostApplicationBuilder AddMySql(this IHostApplicationBuilder buil internal static IHostApplicationBuilder AddMySql(this IHostApplicationBuilder builder, MySqlPackageResolver packageResolver, Action? configureAction = null, Action? addAction = null) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(packageResolver); builder.Configuration.ConfigureMySql(packageResolver, configureAction); builder.Services.AddMySql(builder.Configuration, packageResolver, addAction); diff --git a/src/Connectors/src/Connectors/MySql/MySqlServiceCollectionExtensions.cs b/src/Connectors/src/Connectors/MySql/MySqlServiceCollectionExtensions.cs index 933d4e6b26..68a2bd865b 100644 --- a/src/Connectors/src/Connectors/MySql/MySqlServiceCollectionExtensions.cs +++ b/src/Connectors/src/Connectors/MySql/MySqlServiceCollectionExtensions.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.MySql.DynamicTypeAccess; @@ -59,9 +58,9 @@ public static IServiceCollection AddMySql(this IServiceCollection services, ICon internal static IServiceCollection AddMySql(this IServiceCollection services, IConfiguration configuration, MySqlPackageResolver packageResolver, Action? addAction = null) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(packageResolver); if (!ConnectorFactoryShim.IsRegistered(packageResolver.MySqlConnectionClass.Type, services)) { diff --git a/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionShim.cs b/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionShim.cs index 894e8edff4..92b05aeb38 100644 --- a/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionShim.cs +++ b/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Data.Common; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.PostgreSql.DynamicTypeAccess; @@ -19,7 +18,7 @@ private NpgsqlConnectionShim(InstanceAccessor instanceAccessor) public static NpgsqlConnectionShim CreateInstance(PostgreSqlPackageResolver packageResolver, string? connectionString) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.NpgsqlConnectionClass.CreateInstance(connectionString); return new NpgsqlConnectionShim(instanceAccessor); diff --git a/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionStringBuilderShim.cs b/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionStringBuilderShim.cs index 9a49877cf1..8589b12264 100644 --- a/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionStringBuilderShim.cs +++ b/src/Connectors/src/Connectors/PostgreSql/DynamicTypeAccess/NpgsqlConnectionStringBuilderShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Data.Common; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.PostgreSql.DynamicTypeAccess; @@ -19,7 +18,7 @@ private NpgsqlConnectionStringBuilderShim(InstanceAccessor instanceAccessor) public static NpgsqlConnectionStringBuilderShim CreateInstance(PostgreSqlPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.NpgsqlConnectionStringBuilderClass.CreateInstance(null); return new NpgsqlConnectionStringBuilderShim(instanceAccessor); diff --git a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConfigurationBuilderExtensions.cs b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConfigurationBuilderExtensions.cs index 2365281500..9912b35711 100644 --- a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConfigurationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Connectors.PostgreSql.DynamicTypeAccess; namespace Steeltoe.Connectors.PostgreSql; @@ -44,8 +43,8 @@ public static IConfigurationBuilder ConfigurePostgreSql(this IConfigurationBuild private static IConfigurationBuilder ConfigurePostgreSql(this IConfigurationBuilder builder, PostgreSqlPackageResolver packageResolver, Action? configureAction = null) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(packageResolver); ConnectorConfigurer.Configure(builder, configureAction, new PostgreSqlConnectionStringPostProcessor(packageResolver)); return builder; diff --git a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConnectionStringPostProcessor.cs b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConnectionStringPostProcessor.cs index dd8976f58d..065e8b8113 100644 --- a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConnectionStringPostProcessor.cs +++ b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlConnectionStringPostProcessor.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Connectors.PostgreSql.DynamicTypeAccess; namespace Steeltoe.Connectors.PostgreSql; @@ -15,7 +14,7 @@ internal sealed class PostgreSqlConnectionStringPostProcessor : ConnectionString public PostgreSqlConnectionStringPostProcessor(PostgreSqlPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); _packageResolver = packageResolver; } diff --git a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlHostApplicationBuilderExtensions.cs b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlHostApplicationBuilderExtensions.cs index 29c5a8ed3c..e03e1f6c2a 100644 --- a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlHostApplicationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlHostApplicationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Hosting; -using Steeltoe.Common; namespace Steeltoe.Connectors.PostgreSql; @@ -43,7 +42,7 @@ public static IHostApplicationBuilder AddPostgreSql(this IHostApplicationBuilder public static IHostApplicationBuilder AddPostgreSql(this IHostApplicationBuilder builder, Action? configureAction, Action? addAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Configuration.ConfigurePostgreSql(configureAction); builder.Services.AddPostgreSql(builder.Configuration, addAction); diff --git a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlServiceCollectionExtensions.cs b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlServiceCollectionExtensions.cs index 6d50574796..4a70ac2813 100644 --- a/src/Connectors/src/Connectors/PostgreSql/PostgreSqlServiceCollectionExtensions.cs +++ b/src/Connectors/src/Connectors/PostgreSql/PostgreSqlServiceCollectionExtensions.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.PostgreSql.DynamicTypeAccess; @@ -60,9 +59,9 @@ public static IServiceCollection AddPostgreSql(this IServiceCollection services, private static IServiceCollection AddPostgreSql(this IServiceCollection services, IConfiguration configuration, PostgreSqlPackageResolver packageResolver, Action? addAction = null) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(packageResolver); if (!ConnectorFactoryShim.IsRegistered(packageResolver.NpgsqlConnectionClass.Type, services)) { diff --git a/src/Connectors/src/Connectors/RabbitMQ/DynamicTypeAccess/ConnectionFactoryShim.cs b/src/Connectors/src/Connectors/RabbitMQ/DynamicTypeAccess/ConnectionFactoryShim.cs index 078a4b8427..1d78f7e085 100644 --- a/src/Connectors/src/Connectors/RabbitMQ/DynamicTypeAccess/ConnectionFactoryShim.cs +++ b/src/Connectors/src/Connectors/RabbitMQ/DynamicTypeAccess/ConnectionFactoryShim.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.RabbitMQ.DynamicTypeAccess; @@ -25,7 +24,7 @@ private ConnectionFactoryShim(RabbitMQPackageResolver packageResolver, InstanceA public static ConnectionFactoryShim CreateInstance(RabbitMQPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.ConnectionFactoryClass.CreateInstance(); return new ConnectionFactoryShim(packageResolver, instanceAccessor); diff --git a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConfigurationBuilderExtensions.cs b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConfigurationBuilderExtensions.cs index da4f9147e0..8e52204c51 100644 --- a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConfigurationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Connectors.RabbitMQ; @@ -37,7 +36,7 @@ public static IConfigurationBuilder ConfigureRabbitMQ(this IConfigurationBuilder /// public static IConfigurationBuilder ConfigureRabbitMQ(this IConfigurationBuilder builder, Action? configureAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); ConnectorConfigurer.Configure(builder, configureAction, new RabbitMQConnectionStringPostProcessor()); return builder; diff --git a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConnectionStringBuilder.cs b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConnectionStringBuilder.cs index de9a14ee85..7695f83d36 100644 --- a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConnectionStringBuilder.cs +++ b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQConnectionStringBuilder.cs @@ -4,7 +4,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; -using Steeltoe.Common; namespace Steeltoe.Connectors.RabbitMQ; @@ -28,7 +27,7 @@ public object? this[string keyword] { get { - ArgumentGuard.NotNull(keyword); + ArgumentException.ThrowIfNullOrWhiteSpace(keyword); AssertIsKnownKeyword(keyword); if (string.Equals(keyword, KnownKeywords.Url, StringComparison.OrdinalIgnoreCase)) @@ -45,7 +44,7 @@ public object? this[string keyword] } set { - ArgumentGuard.NotNull(keyword); + ArgumentException.ThrowIfNullOrWhiteSpace(keyword); AssertIsKnownKeyword(keyword); if (string.Equals(keyword, KnownKeywords.Url, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs index a1b843d785..fa0d359cc3 100644 --- a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs +++ b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHealthContributor.cs @@ -5,7 +5,6 @@ using System.Runtime.ExceptionServices; using System.Text; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -25,9 +24,9 @@ internal sealed class RabbitMQHealthContributor : IHealthContributor, IDisposabl public RabbitMQHealthContributor(object connectionFactory, string host, ILogger logger) { - ArgumentGuard.NotNull(connectionFactory); - ArgumentGuard.NotNullOrEmpty(host); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(connectionFactory); + ArgumentException.ThrowIfNullOrWhiteSpace(host); + ArgumentNullException.ThrowIfNull(logger); _connectionFactoryInterfaceShim = new ConnectionFactoryInterfaceShim(RabbitMQPackageResolver.Default, connectionFactory); Host = host; diff --git a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHostApplicationBuilderExtensions.cs b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHostApplicationBuilderExtensions.cs index 80e6e29800..e2cda0ff2e 100644 --- a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHostApplicationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQHostApplicationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Hosting; -using Steeltoe.Common; namespace Steeltoe.Connectors.RabbitMQ; @@ -43,7 +42,7 @@ public static IHostApplicationBuilder AddRabbitMQ(this IHostApplicationBuilder b public static IHostApplicationBuilder AddRabbitMQ(this IHostApplicationBuilder builder, Action? configureAction, Action? addAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Configuration.ConfigureRabbitMQ(configureAction); builder.Services.AddRabbitMQ(builder.Configuration, addAction); diff --git a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQServiceCollectionExtensions.cs b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQServiceCollectionExtensions.cs index 15141c2812..b5d82465dc 100644 --- a/src/Connectors/src/Connectors/RabbitMQ/RabbitMQServiceCollectionExtensions.cs +++ b/src/Connectors/src/Connectors/RabbitMQ/RabbitMQServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.RabbitMQ.DynamicTypeAccess; @@ -58,9 +57,9 @@ public static IServiceCollection AddRabbitMQ(this IServiceCollection services, I private static IServiceCollection AddRabbitMQ(this IServiceCollection services, IConfiguration configuration, RabbitMQPackageResolver packageResolver, Action? addAction = null) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(packageResolver); if (!ConnectorFactoryShim.IsRegistered(packageResolver.ConnectionInterface.Type, services)) { diff --git a/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/ConnectionMultiplexerShim.cs b/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/ConnectionMultiplexerShim.cs index ed7e108be6..a76930b028 100644 --- a/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/ConnectionMultiplexerShim.cs +++ b/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/ConnectionMultiplexerShim.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.Redis.DynamicTypeAccess; @@ -18,7 +17,7 @@ public ConnectionMultiplexerShim(StackExchangeRedisPackageResolver packageResolv public static ConnectionMultiplexerInterfaceShim Connect(StackExchangeRedisPackageResolver packageResolver, string? configuration) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); object instance = packageResolver.ConnectionMultiplexerClass.InvokeMethodOverload("Connect", true, new[] { @@ -31,7 +30,7 @@ public static ConnectionMultiplexerInterfaceShim Connect(StackExchangeRedisPacka public static async Task ConnectAsync(StackExchangeRedisPackageResolver packageResolver, string? configuration) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); var task = (Task)packageResolver.ConnectionMultiplexerClass.InvokeMethodOverload("ConnectAsync", true, new[] { diff --git a/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheOptionsShim.cs b/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheOptionsShim.cs index f749d6c4b7..b5599e8b5e 100644 --- a/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheOptionsShim.cs +++ b/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheOptionsShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Reflection; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.Redis.DynamicTypeAccess; @@ -35,7 +34,7 @@ private RedisCacheOptionsShim(InstanceAccessor instanceAccessor) public static RedisCacheOptionsShim CreateInstance(MicrosoftRedisPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.RedisCacheOptionsClass.CreateInstance(null); return new RedisCacheOptionsShim(instanceAccessor); @@ -44,7 +43,7 @@ public static RedisCacheOptionsShim CreateInstance(MicrosoftRedisPackageResolver // Return type: Func> public object CreateTaskLambdaForConnectionMultiplexerFactory(ConnectionMultiplexerInterfaceShim connectionMultiplexer) { - ArgumentGuard.NotNull(connectionMultiplexer); + ArgumentNullException.ThrowIfNull(connectionMultiplexer); MethodInfo assignMethod = GetType().GetMethod(nameof(AssignConnectionMultiplexerFactory), BindingFlags.Static | BindingFlags.NonPublic)!; MethodInfo assignGenericMethod = assignMethod.MakeGenericMethod(connectionMultiplexer.DeclaredType); diff --git a/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheShim.cs b/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheShim.cs index 66f6bd0f40..c25446052c 100644 --- a/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheShim.cs +++ b/src/Connectors/src/Connectors/Redis/DynamicTypeAccess/RedisCacheShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.Redis.DynamicTypeAccess; @@ -22,8 +21,8 @@ private RedisCacheShim(InstanceAccessor instanceAccessor) public static RedisCacheShim CreateInstance(MicrosoftRedisPackageResolver packageResolver, RedisCacheOptionsShim redisCacheOptions) { - ArgumentGuard.NotNull(packageResolver); - ArgumentGuard.NotNull(redisCacheOptions); + ArgumentNullException.ThrowIfNull(packageResolver); + ArgumentNullException.ThrowIfNull(redisCacheOptions); Type optionsWrapperType = typeof(OptionsWrapper<>).MakeGenericType(redisCacheOptions.DeclaredType); object optionsWrapperInstance = Activator.CreateInstance(optionsWrapperType, redisCacheOptions.Instance)!; diff --git a/src/Connectors/src/Connectors/Redis/RedisConfigurationBuilderExtensions.cs b/src/Connectors/src/Connectors/Redis/RedisConfigurationBuilderExtensions.cs index 4e07f194b4..2f18b406ff 100644 --- a/src/Connectors/src/Connectors/Redis/RedisConfigurationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/Redis/RedisConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Connectors.Redis; @@ -37,7 +36,7 @@ public static IConfigurationBuilder ConfigureRedis(this IConfigurationBuilder bu /// public static IConfigurationBuilder ConfigureRedis(this IConfigurationBuilder builder, Action? configureAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); ConnectorConfigurer.Configure(builder, configureAction, new RedisConnectionStringPostProcessor()); return builder; diff --git a/src/Connectors/src/Connectors/Redis/RedisConnectionStringBuilder.cs b/src/Connectors/src/Connectors/Redis/RedisConnectionStringBuilder.cs index 10c3d9b534..9a52d50d80 100644 --- a/src/Connectors/src/Connectors/Redis/RedisConnectionStringBuilder.cs +++ b/src/Connectors/src/Connectors/Redis/RedisConnectionStringBuilder.cs @@ -4,7 +4,6 @@ using System.Diagnostics.CodeAnalysis; using System.Text; -using Steeltoe.Common; namespace Steeltoe.Connectors.Redis; @@ -28,7 +27,7 @@ public object? this[string keyword] { get { - ArgumentGuard.NotNull(keyword); + ArgumentException.ThrowIfNullOrWhiteSpace(keyword); // Allow getting unknown keyword, if it was set earlier. We don't pretend to know all valid keywords. if (_settings.TryGetValue(keyword, out string? value)) @@ -41,7 +40,7 @@ public object? this[string keyword] } set { - ArgumentGuard.NotNull(keyword); + ArgumentException.ThrowIfNullOrWhiteSpace(keyword); string? stringValue = value?.ToString(); diff --git a/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs b/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs index 57be40fb14..4a12abe90a 100644 --- a/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs +++ b/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs @@ -4,7 +4,6 @@ using System.Runtime.ExceptionServices; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -26,7 +25,7 @@ internal sealed class RedisHealthContributor : IHealthContributor, IDisposable public RedisHealthContributor(string? connectionString, ILogger logger) { - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(logger); _connectionString = connectionString; Host = GetHostNameFromConnectionString(connectionString); diff --git a/src/Connectors/src/Connectors/Redis/RedisHostApplicationBuilderExtensions.cs b/src/Connectors/src/Connectors/Redis/RedisHostApplicationBuilderExtensions.cs index c6a758fd6f..e6a3c98093 100644 --- a/src/Connectors/src/Connectors/Redis/RedisHostApplicationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/Redis/RedisHostApplicationBuilderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Hosting; -using Steeltoe.Common; namespace Steeltoe.Connectors.Redis; @@ -48,7 +47,7 @@ public static IHostApplicationBuilder AddRedis(this IHostApplicationBuilder buil public static IHostApplicationBuilder AddRedis(this IHostApplicationBuilder builder, Action? configureAction, Action? addAction) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Configuration.ConfigureRedis(configureAction); builder.Services.AddRedis(builder.Configuration, addAction); diff --git a/src/Connectors/src/Connectors/Redis/RedisServiceCollectionExtensions.cs b/src/Connectors/src/Connectors/Redis/RedisServiceCollectionExtensions.cs index 1444266973..2337c9d17d 100644 --- a/src/Connectors/src/Connectors/Redis/RedisServiceCollectionExtensions.cs +++ b/src/Connectors/src/Connectors/Redis/RedisServiceCollectionExtensions.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.Redis.DynamicTypeAccess; @@ -64,10 +63,10 @@ private static IServiceCollection AddRedis(this IServiceCollection services, ICo StackExchangeRedisPackageResolver stackExchangeRedisPackageResolver, MicrosoftRedisPackageResolver microsoftRedisPackageResolver, Action? addAction = null) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(stackExchangeRedisPackageResolver); - ArgumentGuard.NotNull(microsoftRedisPackageResolver); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(stackExchangeRedisPackageResolver); + ArgumentNullException.ThrowIfNull(microsoftRedisPackageResolver); if (!ConnectorFactoryShim.IsRegistered(stackExchangeRedisPackageResolver.ConnectionMultiplexerInterface.Type, services)) { diff --git a/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs b/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs index 7648ee7f3e..50f028966f 100644 --- a/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs +++ b/src/Connectors/src/Connectors/RelationalDatabaseHealthContributor.cs @@ -5,7 +5,6 @@ using System.Data.Common; using System.Runtime.ExceptionServices; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -23,8 +22,8 @@ internal sealed class RelationalDatabaseHealthContributor : IHealthContributor, public RelationalDatabaseHealthContributor(DbConnection connection, string? host, ILogger logger) { - ArgumentGuard.NotNull(connection); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(logger); _connection = connection; Host = host ?? string.Empty; diff --git a/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionShim.cs b/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionShim.cs index 4e8777066a..1810c953a5 100644 --- a/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionShim.cs +++ b/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Data.Common; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.SqlServer.RuntimeTypeAccess; @@ -19,7 +18,7 @@ private SqlConnectionShim(InstanceAccessor instanceAccessor) public static SqlConnectionShim CreateInstance(SqlServerPackageResolver packageResolver, string? connectionString) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.SqlConnectionClass.CreateInstance(connectionString); return new SqlConnectionShim(instanceAccessor); diff --git a/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionStringBuilderShim.cs b/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionStringBuilderShim.cs index d09dc7678e..eab20ae683 100644 --- a/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionStringBuilderShim.cs +++ b/src/Connectors/src/Connectors/SqlServer/RuntimeTypeAccess/SqlConnectionStringBuilderShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Data.Common; -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.SqlServer.RuntimeTypeAccess; @@ -19,7 +18,7 @@ private SqlConnectionStringBuilderShim(InstanceAccessor instanceAccessor) public static SqlConnectionStringBuilderShim CreateInstance(SqlServerPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); InstanceAccessor instanceAccessor = packageResolver.SqlConnectionStringBuilderClass.CreateInstance(null); return new SqlConnectionStringBuilderShim(instanceAccessor); diff --git a/src/Connectors/src/Connectors/SqlServer/SqlServerConfigurationBuilderExtensions.cs b/src/Connectors/src/Connectors/SqlServer/SqlServerConfigurationBuilderExtensions.cs index c93b8ae541..be87ec782c 100644 --- a/src/Connectors/src/Connectors/SqlServer/SqlServerConfigurationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/SqlServer/SqlServerConfigurationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Connectors.SqlServer.RuntimeTypeAccess; namespace Steeltoe.Connectors.SqlServer; @@ -44,8 +43,8 @@ public static IConfigurationBuilder ConfigureSqlServer(this IConfigurationBuilde internal static IConfigurationBuilder ConfigureSqlServer(this IConfigurationBuilder builder, SqlServerPackageResolver packageResolver, Action? configureAction = null) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(packageResolver); ConnectorConfigurer.Configure(builder, configureAction, new SqlServerConnectionStringPostProcessor(packageResolver)); return builder; diff --git a/src/Connectors/src/Connectors/SqlServer/SqlServerConnectionStringPostProcessor.cs b/src/Connectors/src/Connectors/SqlServer/SqlServerConnectionStringPostProcessor.cs index 710d54979e..4446e47e82 100644 --- a/src/Connectors/src/Connectors/SqlServer/SqlServerConnectionStringPostProcessor.cs +++ b/src/Connectors/src/Connectors/SqlServer/SqlServerConnectionStringPostProcessor.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Connectors.SqlServer.RuntimeTypeAccess; namespace Steeltoe.Connectors.SqlServer; @@ -15,7 +14,7 @@ internal sealed class SqlServerConnectionStringPostProcessor : ConnectionStringP public SqlServerConnectionStringPostProcessor(SqlServerPackageResolver packageResolver) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); _packageResolver = packageResolver; } diff --git a/src/Connectors/src/Connectors/SqlServer/SqlServerHostApplicationBuilderExtensions.cs b/src/Connectors/src/Connectors/SqlServer/SqlServerHostApplicationBuilderExtensions.cs index 02384d22a9..ebc360c57f 100644 --- a/src/Connectors/src/Connectors/SqlServer/SqlServerHostApplicationBuilderExtensions.cs +++ b/src/Connectors/src/Connectors/SqlServer/SqlServerHostApplicationBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Hosting; -using Steeltoe.Common; using Steeltoe.Connectors.SqlServer.RuntimeTypeAccess; namespace Steeltoe.Connectors.SqlServer; @@ -50,8 +49,8 @@ public static IHostApplicationBuilder AddSqlServer(this IHostApplicationBuilder internal static IHostApplicationBuilder AddSqlServer(this IHostApplicationBuilder builder, SqlServerPackageResolver packageResolver, Action? configureAction = null, Action? addAction = null) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(packageResolver); builder.Configuration.ConfigureSqlServer(packageResolver, configureAction); builder.Services.AddSqlServer(builder.Configuration, packageResolver, addAction); diff --git a/src/Connectors/src/Connectors/SqlServer/SqlServerServiceCollectionExtensions.cs b/src/Connectors/src/Connectors/SqlServer/SqlServerServiceCollectionExtensions.cs index 13dde0696b..937cb14a99 100644 --- a/src/Connectors/src/Connectors/SqlServer/SqlServerServiceCollectionExtensions.cs +++ b/src/Connectors/src/Connectors/SqlServer/SqlServerServiceCollectionExtensions.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.SqlServer.RuntimeTypeAccess; @@ -59,9 +58,9 @@ public static IServiceCollection AddSqlServer(this IServiceCollection services, internal static IServiceCollection AddSqlServer(this IServiceCollection services, IConfiguration configuration, SqlServerPackageResolver packageResolver, Action? addAction = null) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(packageResolver); if (!ConnectorFactoryShim.IsRegistered(packageResolver.SqlConnectionClass.Type, services)) { diff --git a/src/Connectors/src/EntityFrameworkCore/MigrateDbContextTask.cs b/src/Connectors/src/EntityFrameworkCore/MigrateDbContextTask.cs index 86019ae429..6280d77e0f 100644 --- a/src/Connectors/src/EntityFrameworkCore/MigrateDbContextTask.cs +++ b/src/Connectors/src/EntityFrameworkCore/MigrateDbContextTask.cs @@ -28,8 +28,8 @@ public sealed class MigrateDbContextTask : IApplicationTask public MigrateDbContextTask(TDbContext dbContext, ILogger> logger) { - ArgumentGuard.NotNull(dbContext); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(dbContext); + ArgumentNullException.ThrowIfNull(logger); _dbContext = dbContext; _logger = logger; @@ -38,11 +38,11 @@ public MigrateDbContextTask(TDbContext dbContext, ILogger(); + IList migrations = Array.Empty(); try { - migrations = (await _dbContext.Database.GetPendingMigrationsAsync(cancellationToken)).ToList(); + migrations = (await _dbContext.Database.GetPendingMigrationsAsync(cancellationToken)).ToArray(); } catch { @@ -55,7 +55,7 @@ public async Task RunAsync(CancellationToken cancellationToken) if (isNewDatabase) { - migrations = (await _dbContext.Database.GetAppliedMigrationsAsync(cancellationToken)).ToList(); + migrations = (await _dbContext.Database.GetAppliedMigrationsAsync(cancellationToken)).ToArray(); } if (migrations.Count > 0) diff --git a/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlDbContextOptionsExtensionsShim.cs b/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlDbContextOptionsExtensionsShim.cs index 96ac4e4e00..5a6b5c615f 100644 --- a/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlDbContextOptionsExtensionsShim.cs +++ b/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlDbContextOptionsExtensionsShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.EntityFrameworkCore; -using Steeltoe.Common; namespace Steeltoe.Connectors.EntityFrameworkCore.MySql.DynamicTypeAccess; @@ -12,7 +11,7 @@ internal static class MySqlDbContextOptionsExtensionsShim public static void UseMySql(MySqlEntityFrameworkCorePackageResolver packageResolver, DbContextOptionsBuilder optionsBuilder, string? connectionString, object? serverVersion, object? mySqlOptionsAction) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); bool isOraclePackage = packageResolver.MySqlDbContextOptionsExtensionsClass.Type.Name.StartsWith("MySQL", StringComparison.Ordinal); diff --git a/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlEntityFrameworkCorePackageResolver.cs b/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlEntityFrameworkCorePackageResolver.cs index 395b907e9f..17bfe9db43 100644 --- a/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlEntityFrameworkCorePackageResolver.cs +++ b/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/MySqlEntityFrameworkCorePackageResolver.cs @@ -26,7 +26,7 @@ internal sealed class MySqlEntityFrameworkCorePackageResolver : PackageResolver "MySql.Data" }; - public static readonly MySqlEntityFrameworkCorePackageResolver Default = new(PomeloAssemblyNames.Concat(OracleAssemblyNames).ToList(), new[] + public static readonly MySqlEntityFrameworkCorePackageResolver Default = new(PomeloAssemblyNames.Concat(OracleAssemblyNames).ToArray(), new[] { PomeloPackageName, OraclePackageName diff --git a/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/ServerVersionShim.cs b/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/ServerVersionShim.cs index e41709f89a..7842abc212 100644 --- a/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/ServerVersionShim.cs +++ b/src/Connectors/src/EntityFrameworkCore/MySql/DynamicTypeAccess/ServerVersionShim.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.DynamicTypeAccess; namespace Steeltoe.Connectors.EntityFrameworkCore.MySql.DynamicTypeAccess; @@ -16,7 +15,7 @@ public ServerVersionShim(MySqlEntityFrameworkCorePackageResolver packageResolver public static ServerVersionShim AutoDetect(MySqlEntityFrameworkCorePackageResolver packageResolver, string connectionString) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); object instance = packageResolver.ServerVersionClass.InvokeMethodOverload("AutoDetect", true, new[] { diff --git a/src/Connectors/src/EntityFrameworkCore/MySql/MySqlDbContextOptionsBuilderExtensions.cs b/src/Connectors/src/EntityFrameworkCore/MySql/MySqlDbContextOptionsBuilderExtensions.cs index 1a5db9c5eb..54d6442aa4 100644 --- a/src/Connectors/src/EntityFrameworkCore/MySql/MySqlDbContextOptionsBuilderExtensions.cs +++ b/src/Connectors/src/EntityFrameworkCore/MySql/MySqlDbContextOptionsBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.EntityFrameworkCore; -using Steeltoe.Common; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.EntityFrameworkCore.MySql.DynamicTypeAccess; using Steeltoe.Connectors.MySql; @@ -82,9 +81,9 @@ internal static DbContextOptionsBuilder UseMySql(this DbContextOptionsBuilder op MySqlEntityFrameworkCorePackageResolver packageResolver, string? serviceBindingName = null, object? serverVersion = null, Action? mySqlOptionsAction = null) { - ArgumentGuard.NotNull(optionsBuilder); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(optionsBuilder); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(packageResolver); string optionName = serviceBindingName ?? string.Empty; string? connectionString = GetConnectionString(serviceProvider, optionName, packageResolver); diff --git a/src/Connectors/src/EntityFrameworkCore/PostgreSql/DynamicTypeAccess/NpgsqlDbContextOptionsBuilderExtensionsShim.cs b/src/Connectors/src/EntityFrameworkCore/PostgreSql/DynamicTypeAccess/NpgsqlDbContextOptionsBuilderExtensionsShim.cs index 8e336f9140..6de391340b 100644 --- a/src/Connectors/src/EntityFrameworkCore/PostgreSql/DynamicTypeAccess/NpgsqlDbContextOptionsBuilderExtensionsShim.cs +++ b/src/Connectors/src/EntityFrameworkCore/PostgreSql/DynamicTypeAccess/NpgsqlDbContextOptionsBuilderExtensionsShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.EntityFrameworkCore; -using Steeltoe.Common; namespace Steeltoe.Connectors.EntityFrameworkCore.PostgreSql.DynamicTypeAccess; @@ -12,7 +11,7 @@ internal static class NpgsqlDbContextOptionsBuilderExtensionsShim public static void UseNpgsql(PostgreSqlEntityFrameworkCorePackageResolver packageResolver, DbContextOptionsBuilder optionsBuilder, string? connectionString, object? npgsqlOptionsAction) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); if (string.IsNullOrWhiteSpace(connectionString)) { diff --git a/src/Connectors/src/EntityFrameworkCore/PostgreSql/PostgreSqlDbContextOptionsBuilderExtensions.cs b/src/Connectors/src/EntityFrameworkCore/PostgreSql/PostgreSqlDbContextOptionsBuilderExtensions.cs index f80185a8c3..eb2ac09346 100644 --- a/src/Connectors/src/EntityFrameworkCore/PostgreSql/PostgreSqlDbContextOptionsBuilderExtensions.cs +++ b/src/Connectors/src/EntityFrameworkCore/PostgreSql/PostgreSqlDbContextOptionsBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.EntityFrameworkCore; -using Steeltoe.Common; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.EntityFrameworkCore.PostgreSql.DynamicTypeAccess; using Steeltoe.Connectors.PostgreSql; @@ -76,9 +75,9 @@ public static DbContextOptionsBuilder UseNpgsql(this DbContextOptionsBuilder opt private static DbContextOptionsBuilder UseNpgsql(this DbContextOptionsBuilder optionsBuilder, IServiceProvider serviceProvider, PostgreSqlEntityFrameworkCorePackageResolver packageResolver, string? serviceBindingName = null, Action? npgsqlOptionsAction = null) { - ArgumentGuard.NotNull(optionsBuilder); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(optionsBuilder); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(packageResolver); string optionName = serviceBindingName ?? string.Empty; string? connectionString = GetConnectionString(serviceProvider, optionName, packageResolver); diff --git a/src/Connectors/src/EntityFrameworkCore/SqlServer/DynamicTypeAccess/SqlServerDbContextOptionsExtensionsShim.cs b/src/Connectors/src/EntityFrameworkCore/SqlServer/DynamicTypeAccess/SqlServerDbContextOptionsExtensionsShim.cs index 854bda3abf..4546d22093 100644 --- a/src/Connectors/src/EntityFrameworkCore/SqlServer/DynamicTypeAccess/SqlServerDbContextOptionsExtensionsShim.cs +++ b/src/Connectors/src/EntityFrameworkCore/SqlServer/DynamicTypeAccess/SqlServerDbContextOptionsExtensionsShim.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.EntityFrameworkCore; -using Steeltoe.Common; namespace Steeltoe.Connectors.EntityFrameworkCore.SqlServer.DynamicTypeAccess; @@ -12,7 +11,7 @@ internal static class SqlServerDbContextOptionsExtensionsShim public static void UseSqlServer(SqlServerEntityFrameworkCorePackageResolver packageResolver, DbContextOptionsBuilder optionsBuilder, string? connectionString, object? sqlServerOptionsAction = null) { - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(packageResolver); Type sqlServerOptionsActionType = typeof(Action<>).MakeGenericType(packageResolver.SqlServerDbContextOptionsBuilderClass.Type); diff --git a/src/Connectors/src/EntityFrameworkCore/SqlServer/SqlServerDbContextOptionsBuilderExtensions.cs b/src/Connectors/src/EntityFrameworkCore/SqlServer/SqlServerDbContextOptionsBuilderExtensions.cs index d635a7c45b..c370c55475 100644 --- a/src/Connectors/src/EntityFrameworkCore/SqlServer/SqlServerDbContextOptionsBuilderExtensions.cs +++ b/src/Connectors/src/EntityFrameworkCore/SqlServer/SqlServerDbContextOptionsBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.EntityFrameworkCore; -using Steeltoe.Common; using Steeltoe.Connectors.DynamicTypeAccess; using Steeltoe.Connectors.EntityFrameworkCore.SqlServer.DynamicTypeAccess; using Steeltoe.Connectors.SqlServer; @@ -77,9 +76,9 @@ public static DbContextOptionsBuilder UseSqlServer(this DbContextOptionsBuilder private static DbContextOptionsBuilder UseSqlServer(this DbContextOptionsBuilder optionsBuilder, IServiceProvider serviceProvider, SqlServerEntityFrameworkCorePackageResolver packageResolver, string? serviceBindingName = null, Action? sqlServerOptionsAction = null) { - ArgumentGuard.NotNull(optionsBuilder); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(packageResolver); + ArgumentNullException.ThrowIfNull(optionsBuilder); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(packageResolver); string optionName = serviceBindingName ?? string.Empty; string? connectionString = GetConnectionString(serviceProvider, optionName, packageResolver); diff --git a/src/Connectors/test/Connectors.Test/MemoryFileProvider.cs b/src/Connectors/test/Connectors.Test/MemoryFileProvider.cs index 8b378ca68e..799b9a3fa1 100644 --- a/src/Connectors/test/Connectors.Test/MemoryFileProvider.cs +++ b/src/Connectors/test/Connectors.Test/MemoryFileProvider.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; namespace Steeltoe.Connectors.Test; @@ -24,7 +23,7 @@ internal sealed class MemoryFileProvider : IFileProvider public void IncludeDirectory(string path) { - ArgumentGuard.NotNullOrEmpty(path); + ArgumentException.ThrowIfNullOrEmpty(path); IEnumerable pathSegments = PathToSegments(path); _ = GetOrCreateDirectories(pathSegments); @@ -32,8 +31,8 @@ public void IncludeDirectory(string path) public void IncludeFile(string path, string contents) { - ArgumentGuard.NotNullOrEmpty(path); - ArgumentGuard.NotNull(contents); + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(contents); byte[] bytes = Encoding.UTF8.GetBytes(contents); IncludeFile(path, bytes); @@ -41,8 +40,8 @@ public void IncludeFile(string path, string contents) public void IncludeFile(string path, byte[] contents) { - ArgumentGuard.NotNullOrEmpty(path); - ArgumentGuard.NotNull(contents); + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(contents); string[] pathSegments = PathToSegments(path).ToArray(); string[] parentDirectories = pathSegments[..^1]; @@ -78,8 +77,8 @@ private MemoryFileSystemEntry GetOrCreateDirectories(IEnumerable pathSeg public void ReplaceFile(string path, string contents) { - ArgumentGuard.NotNullOrEmpty(path); - ArgumentGuard.NotNull(contents); + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(contents); byte[] bytes = Encoding.UTF8.GetBytes(contents); ReplaceFile(path, bytes); @@ -87,8 +86,8 @@ public void ReplaceFile(string path, string contents) public void ReplaceFile(string path, byte[] contents) { - ArgumentGuard.NotNullOrEmpty(path); - ArgumentGuard.NotNull(contents); + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(contents); MemoryFileSystemEntry? entry = Find(path); @@ -102,7 +101,7 @@ public void ReplaceFile(string path, byte[] contents) public IFileInfo GetFileInfo(string subpath) { - ArgumentGuard.NotNullOrEmpty(subpath); + ArgumentException.ThrowIfNullOrEmpty(subpath); MemoryFileSystemEntry? entry = Find(subpath); @@ -116,7 +115,7 @@ public IFileInfo GetFileInfo(string subpath) public IDirectoryContents GetDirectoryContents(string subpath) { - ArgumentGuard.NotNullOrEmpty(subpath); + ArgumentException.ThrowIfNullOrEmpty(subpath); MemoryFileSystemEntry? entry = Find(subpath); @@ -203,7 +202,7 @@ public Stream CreateReadStream() public void ReplaceContents(byte[] contents) { - ArgumentGuard.NotNull(contents); + ArgumentNullException.ThrowIfNull(contents); if (IsDirectory) { diff --git a/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs b/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs index 0c2c6ca189..46e68f360b 100644 --- a/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs @@ -779,7 +779,7 @@ private static void CleanupTempFiles(params string?[] connectionStrings) { if (!string.IsNullOrEmpty(connectionString)) { - foreach (string entry in connectionString.Split(';').ToArray()) + foreach (string entry in connectionString.Split(';')) { string[] pair = entry.Split('=', 2); string key = pair[0]; diff --git a/src/Discovery/src/Configuration/ConfigurationDiscoveryClient.cs b/src/Discovery/src/Configuration/ConfigurationDiscoveryClient.cs index 60025d94e5..86aaad4529 100644 --- a/src/Discovery/src/Configuration/ConfigurationDiscoveryClient.cs +++ b/src/Discovery/src/Configuration/ConfigurationDiscoveryClient.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Discovery; namespace Steeltoe.Discovery.Configuration; @@ -19,7 +18,7 @@ public sealed class ConfigurationDiscoveryClient : IDiscoveryClient public ConfigurationDiscoveryClient(IOptionsMonitor optionsMonitor) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); _optionsMonitor = optionsMonitor; } @@ -36,10 +35,10 @@ public Task> GetServiceIdsAsync(CancellationToken cancellationToken /// public Task> GetInstancesAsync(string serviceId, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(serviceId); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceId); IList instances = _optionsMonitor.CurrentValue.Services.Where(instance => - string.Equals(instance.ServiceId, serviceId, StringComparison.OrdinalIgnoreCase)).Cast().ToList(); + string.Equals(instance.ServiceId, serviceId, StringComparison.OrdinalIgnoreCase)).Cast().ToArray(); return Task.FromResult(instances); } diff --git a/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs b/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs index 4a9deac5a6..28decc1503 100644 --- a/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs +++ b/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; @@ -46,7 +45,7 @@ public static class ConfigurationServiceCollectionExtensions /// public static IServiceCollection AddConfigurationDiscoveryClient(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureReloadableOptions(ConfigurationDiscoveryOptions.ConfigurationPrefix); diff --git a/src/Discovery/src/Consul/ConsulClientFactory.cs b/src/Discovery/src/Consul/ConsulClientFactory.cs index ae95957f67..b18cd49b8b 100644 --- a/src/Discovery/src/Consul/ConsulClientFactory.cs +++ b/src/Discovery/src/Consul/ConsulClientFactory.cs @@ -4,7 +4,6 @@ using System.Net; using Consul; -using Steeltoe.Common; using Steeltoe.Discovery.Consul.Configuration; using Steeltoe.Discovery.Consul.Util; @@ -20,7 +19,7 @@ internal static class ConsulClientFactory /// public static IConsulClient CreateClient(ConsulOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); var client = new ConsulClient(configuration => { diff --git a/src/Discovery/src/Consul/ConsulDiscoveryClient.cs b/src/Discovery/src/Consul/ConsulDiscoveryClient.cs index ba1e54b458..871b6ccde2 100644 --- a/src/Discovery/src/Consul/ConsulDiscoveryClient.cs +++ b/src/Discovery/src/Consul/ConsulDiscoveryClient.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Discovery; using Steeltoe.Discovery.Consul.Configuration; using Steeltoe.Discovery.Consul.Registry; @@ -48,9 +47,9 @@ public sealed class ConsulDiscoveryClient : IDiscoveryClient public ConsulDiscoveryClient(IConsulClient client, IOptionsMonitor optionsMonitor, ConsulServiceRegistrar? registrar, ILogger logger) { - ArgumentGuard.NotNull(client); - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _client = client; _optionsMonitor = optionsMonitor; @@ -86,8 +85,8 @@ public Task> GetInstancesAsync(string serviceId, Cancell /// public async Task> GetInstancesAsync(string serviceId, QueryOptions queryOptions, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(serviceId); - ArgumentGuard.NotNull(queryOptions); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceId); + ArgumentNullException.ThrowIfNull(queryOptions); var instances = new List(); ConsulDiscoveryOptions options = _optionsMonitor.CurrentValue; @@ -114,7 +113,7 @@ public async Task> GetInstancesAsync(string serviceId, Q /// public async Task> GetAllInstancesAsync(QueryOptions queryOptions, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(queryOptions); + ArgumentNullException.ThrowIfNull(queryOptions); var instances = new List(); ConsulDiscoveryOptions options = _optionsMonitor.CurrentValue; @@ -152,7 +151,7 @@ public Task> GetServiceIdsAsync(CancellationToken cancellationToken /// public async Task> GetServiceIdsAsync(QueryOptions queryOptions, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(queryOptions); + ArgumentNullException.ThrowIfNull(queryOptions); ConsulDiscoveryOptions options = _optionsMonitor.CurrentValue; diff --git a/src/Discovery/src/Consul/ConsulHealthContributor.cs b/src/Discovery/src/Consul/ConsulHealthContributor.cs index ff4286ad71..b8724456d4 100644 --- a/src/Discovery/src/Consul/ConsulHealthContributor.cs +++ b/src/Discovery/src/Consul/ConsulHealthContributor.cs @@ -4,7 +4,6 @@ using Consul; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Discovery.Consul.Configuration; using HealthStatus = Steeltoe.Common.HealthChecks.HealthStatus; @@ -32,8 +31,8 @@ internal sealed class ConsulHealthContributor : IHealthContributor /// public ConsulHealthContributor(IConsulClient client, IOptionsMonitor optionsMonitor) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(client); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(client); _client = client; _optionsMonitor = optionsMonitor; diff --git a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs index ba345efb0f..e3d7148721 100644 --- a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs +++ b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs @@ -29,7 +29,7 @@ public static class ConsulServiceCollectionExtensions /// public static IServiceCollection AddConsulDiscoveryClient(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); ConfigureConsulServices(services); AddConsulServices(services); diff --git a/src/Discovery/src/Consul/ConsulServiceInstance.cs b/src/Discovery/src/Consul/ConsulServiceInstance.cs index b2e355598d..61522d536e 100644 --- a/src/Discovery/src/Consul/ConsulServiceInstance.cs +++ b/src/Discovery/src/Consul/ConsulServiceInstance.cs @@ -4,7 +4,6 @@ using System.Collections.ObjectModel; using Consul; -using Steeltoe.Common; using Steeltoe.Common.Discovery; using Steeltoe.Discovery.Consul.Util; @@ -43,7 +42,7 @@ public sealed class ConsulServiceInstance : IServiceInstance /// internal ConsulServiceInstance(ServiceEntry serviceEntry) { - ArgumentGuard.NotNull(serviceEntry); + ArgumentNullException.ThrowIfNull(serviceEntry); Host = ConsulServerUtils.FindHost(serviceEntry); Tags = serviceEntry.Service.Tags; diff --git a/src/Discovery/src/Consul/PeriodicHeartbeat.cs b/src/Discovery/src/Consul/PeriodicHeartbeat.cs index 3a2fd6ccf2..ea7e03124a 100644 --- a/src/Discovery/src/Consul/PeriodicHeartbeat.cs +++ b/src/Discovery/src/Consul/PeriodicHeartbeat.cs @@ -4,7 +4,6 @@ using Consul; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.Extensions; namespace Steeltoe.Discovery.Consul; @@ -22,9 +21,9 @@ internal sealed class PeriodicHeartbeat : IAsyncDisposable public PeriodicHeartbeat(string serviceId, TimeSpan interval, IConsulClient client, ILogger logger) { - ArgumentGuard.NotNull(serviceId); - ArgumentGuard.NotNull(client); - ArgumentGuard.NotNull(logger); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceId); + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(logger); _serviceId = serviceId; Interval = interval; diff --git a/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs b/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs index 717ce14772..8ec1c89668 100644 --- a/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs +++ b/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Http; using Steeltoe.Common.Net; using Steeltoe.Discovery.Consul.Configuration; @@ -19,8 +18,8 @@ internal sealed class PostConfigureConsulDiscoveryOptions : IPostConfigureOption public PostConfigureConsulDiscoveryOptions(IConfiguration configuration, InetUtils inetUtils) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(inetUtils); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(inetUtils); _configuration = configuration; _inetUtils = inetUtils; @@ -28,7 +27,7 @@ public PostConfigureConsulDiscoveryOptions(IConfiguration configuration, InetUti public void PostConfigure(string? name, ConsulDiscoveryOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); HostInfo? hostInfo = options.UseNetworkInterfaces ? _inetUtils.FindFirstNonLoopbackHostInfo() : null; options.HostName ??= hostInfo != null ? hostInfo.Hostname : DnsTools.ResolveHostName(); diff --git a/src/Discovery/src/Consul/Registry/ConsulRegistration.cs b/src/Discovery/src/Consul/Registry/ConsulRegistration.cs index 9ed873db69..2bf97b5ae3 100644 --- a/src/Discovery/src/Consul/Registry/ConsulRegistration.cs +++ b/src/Discovery/src/Consul/Registry/ConsulRegistration.cs @@ -60,8 +60,8 @@ public sealed class ConsulRegistration : IServiceInstance /// internal ConsulRegistration(AgentServiceRegistration innerRegistration, IOptionsMonitor optionsMonitor) { - ArgumentGuard.NotNull(innerRegistration); - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(innerRegistration); + ArgumentNullException.ThrowIfNull(optionsMonitor); InnerRegistration = innerRegistration; _optionsMonitor = optionsMonitor; @@ -85,8 +85,8 @@ internal ConsulRegistration(AgentServiceRegistration innerRegistration, IOptions /// internal static ConsulRegistration Create(IOptionsMonitor optionsMonitor, IApplicationInstanceInfo applicationInfo) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(applicationInfo); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(applicationInfo); ConsulDiscoveryOptions options = optionsMonitor.CurrentValue; diff --git a/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs b/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs index 00f36217e1..db2015772e 100644 --- a/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs +++ b/src/Discovery/src/Consul/Registry/ConsulServiceRegistrar.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Extensions; using Steeltoe.Discovery.Consul.Configuration; @@ -53,10 +52,10 @@ public sealed class ConsulServiceRegistrar : IAsyncDisposable public ConsulServiceRegistrar(ConsulServiceRegistry registry, IOptionsMonitor optionsMonitor, ConsulRegistration registration, ILogger logger) { - ArgumentGuard.NotNull(registry); - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(registration); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(registry); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(registration); + ArgumentNullException.ThrowIfNull(logger); _registry = registry; _optionsMonitor = optionsMonitor; @@ -115,7 +114,7 @@ private async Task DeregisterAsync(CancellationToken cancellationToken) private async Task DoWithRetryAsync(Func retryable, ConsulRetryOptions options, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(retryable); + ArgumentNullException.ThrowIfNull(retryable); _logger.LogDebug("Starting retryable action."); diff --git a/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs b/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs index a9a73d9fdb..aaec152de2 100644 --- a/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs +++ b/src/Discovery/src/Consul/Registry/ConsulServiceRegistry.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Extensions; using Steeltoe.Discovery.Consul.Configuration; @@ -45,9 +44,9 @@ public sealed class ConsulServiceRegistry : IAsyncDisposable public ConsulServiceRegistry(IConsulClient client, IOptionsMonitor optionsMonitor, TtlScheduler? scheduler, ILogger logger) { - ArgumentGuard.NotNull(client); - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _client = client; _optionsMonitor = optionsMonitor; @@ -66,7 +65,7 @@ public ConsulServiceRegistry(IConsulClient client, IOptionsMonitor public async Task RegisterAsync(ConsulRegistration registration, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(registration); + ArgumentNullException.ThrowIfNull(registration); _logger.LogInformation("Registering service {ServiceId} with Consul.", registration.ServiceId); @@ -102,7 +101,7 @@ public async Task RegisterAsync(ConsulRegistration registration, CancellationTok /// public async Task DeregisterAsync(ConsulRegistration registration, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(registration); + ArgumentNullException.ThrowIfNull(registration); try { @@ -134,8 +133,8 @@ public async Task DeregisterAsync(ConsulRegistration registration, CancellationT /// public async Task SetStatusAsync(ConsulRegistration registration, string status, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(registration); - ArgumentGuard.NotNull(status); + ArgumentNullException.ThrowIfNull(registration); + ArgumentException.ThrowIfNullOrWhiteSpace(status); if (string.Equals(status, OutOfService, StringComparison.OrdinalIgnoreCase)) { @@ -162,7 +161,7 @@ public async Task SetStatusAsync(ConsulRegistration registration, string status, /// public async Task GetStatusAsync(ConsulRegistration registration, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(registration); + ArgumentNullException.ThrowIfNull(registration); QueryResult queryResult = await _client.Health.Checks(registration.ServiceId, QueryOptions.Default, cancellationToken); diff --git a/src/Discovery/src/Consul/ThisServiceInstance.cs b/src/Discovery/src/Consul/ThisServiceInstance.cs index 15ccb5ccb0..6453bd6909 100644 --- a/src/Discovery/src/Consul/ThisServiceInstance.cs +++ b/src/Discovery/src/Consul/ThisServiceInstance.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.Discovery; using Steeltoe.Discovery.Consul.Registry; @@ -33,7 +32,7 @@ internal sealed class ThisServiceInstance : IServiceInstance public ThisServiceInstance(ConsulRegistration registration) { - ArgumentGuard.NotNull(registration); + ArgumentNullException.ThrowIfNull(registration); ServiceId = registration.ServiceId; Host = registration.Host; diff --git a/src/Discovery/src/Consul/TtlScheduler.cs b/src/Discovery/src/Consul/TtlScheduler.cs index 0eb0e59bca..23c18cac90 100644 --- a/src/Discovery/src/Consul/TtlScheduler.cs +++ b/src/Discovery/src/Consul/TtlScheduler.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Discovery.Consul.Configuration; namespace Steeltoe.Discovery.Consul; @@ -42,9 +41,9 @@ public sealed class TtlScheduler : IAsyncDisposable /// public TtlScheduler(IOptionsMonitor optionsMonitor, IConsulClient client, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(client); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _client = client; @@ -69,7 +68,7 @@ private void HandleOptionsChanged(ConsulDiscoveryOptions options) /// internal void Add(string instanceId) { - ArgumentGuard.NotNullOrWhiteSpace(instanceId); + ArgumentException.ThrowIfNullOrWhiteSpace(instanceId); ConsulHeartbeatOptions? heartbeatOptions = _optionsMonitor.CurrentValue.Heartbeat; @@ -106,7 +105,7 @@ private void AddOrUpdate(string instanceId, ConsulHeartbeatOptions heartbeatOpti /// internal async Task RemoveAsync(string instanceId) { - ArgumentGuard.NotNullOrWhiteSpace(instanceId); + ArgumentException.ThrowIfNullOrWhiteSpace(instanceId); if (ServiceHeartbeats.TryRemove(instanceId, out PeriodicHeartbeat? heartbeat)) { diff --git a/src/Discovery/src/Consul/Util/ConsulServerUtils.cs b/src/Discovery/src/Consul/Util/ConsulServerUtils.cs index e9605429cd..485ce720b4 100644 --- a/src/Discovery/src/Consul/Util/ConsulServerUtils.cs +++ b/src/Discovery/src/Consul/Util/ConsulServerUtils.cs @@ -6,7 +6,6 @@ using System.Net.Sockets; using System.Text; using Consul; -using Steeltoe.Common; namespace Steeltoe.Discovery.Consul.Util; @@ -14,7 +13,7 @@ internal static class ConsulServerUtils { public static string FindHost(ServiceEntry healthService) { - ArgumentGuard.NotNull(healthService); + ArgumentNullException.ThrowIfNull(healthService); AgentService service = healthService.Service; Node node = healthService.Node; @@ -34,7 +33,7 @@ public static string FindHost(ServiceEntry healthService) public static string FixIPv6Address(string address) { - ArgumentGuard.NotNull(address); + ArgumentException.ThrowIfNullOrWhiteSpace(address); if (IPAddress.TryParse(address, out IPAddress? parsed) && parsed.AddressFamily == AddressFamily.InterNetworkV6) { diff --git a/src/Discovery/src/Consul/Util/DateTimeConversions.cs b/src/Discovery/src/Consul/Util/DateTimeConversions.cs index 6b429a2194..988824e270 100644 --- a/src/Discovery/src/Consul/Util/DateTimeConversions.cs +++ b/src/Discovery/src/Consul/Util/DateTimeConversions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Globalization; -using Steeltoe.Common; namespace Steeltoe.Discovery.Consul.Util; @@ -11,7 +10,7 @@ internal static class DateTimeConversions { public static TimeSpan ToTimeSpan(string time) { - ArgumentGuard.NotNullOrWhiteSpace(time); + ArgumentException.ThrowIfNullOrWhiteSpace(time); #pragma warning disable S4040 // Strings should be normalized to uppercase time = time.ToLowerInvariant(); diff --git a/src/Discovery/src/Consul/ValidateConsulOptions.cs b/src/Discovery/src/Consul/ValidateConsulOptions.cs index 2bcd1684ed..f3c40e0d86 100644 --- a/src/Discovery/src/Consul/ValidateConsulOptions.cs +++ b/src/Discovery/src/Consul/ValidateConsulOptions.cs @@ -14,14 +14,14 @@ internal sealed class ValidateConsulOptions : IValidateOptions public ValidateConsulOptions(IOptionsMonitor discoveryOptionsMonitor) { - ArgumentGuard.NotNull(discoveryOptionsMonitor); + ArgumentNullException.ThrowIfNull(discoveryOptionsMonitor); _discoveryOptionsMonitor = discoveryOptionsMonitor; } public ValidateOptionsResult Validate(string? name, ConsulOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); if (_discoveryOptionsMonitor.CurrentValue.Enabled && (Platform.IsContainerized || Platform.IsCloudHosted) && options.Host == "localhost") { diff --git a/src/Discovery/src/Eureka/AppInfo/ApplicationInfo.cs b/src/Discovery/src/Eureka/AppInfo/ApplicationInfo.cs index bb0ed020db..983286e172 100644 --- a/src/Discovery/src/Eureka/AppInfo/ApplicationInfo.cs +++ b/src/Discovery/src/Eureka/AppInfo/ApplicationInfo.cs @@ -26,8 +26,8 @@ internal ApplicationInfo(string name) internal ApplicationInfo(string name, ICollection instances) { - ArgumentGuard.NotNullOrWhiteSpace(name); - ArgumentGuard.NotNull(instances); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(instances); ArgumentGuard.ElementsNotNull(instances); Name = name; @@ -40,7 +40,7 @@ internal ApplicationInfo(string name, ICollection instances) internal InstanceInfo? GetInstance(string instanceId) { - ArgumentGuard.NotNullOrWhiteSpace(instanceId); + ArgumentException.ThrowIfNullOrWhiteSpace(instanceId); return _instanceMap.GetValueOrDefault(instanceId); } @@ -53,14 +53,14 @@ public override string ToString() internal void Add(InstanceInfo instance) { - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(instance); _instanceMap[instance.InstanceId] = instance; } internal void Remove(InstanceInfo instance) { - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(instance); _instanceMap.TryRemove(instance.InstanceId, out _); } diff --git a/src/Discovery/src/Eureka/AppInfo/ApplicationInfoCollection.cs b/src/Discovery/src/Eureka/AppInfo/ApplicationInfoCollection.cs index 504668a1c7..43b3fc6f80 100644 --- a/src/Discovery/src/Eureka/AppInfo/ApplicationInfoCollection.cs +++ b/src/Discovery/src/Eureka/AppInfo/ApplicationInfoCollection.cs @@ -34,7 +34,7 @@ internal ApplicationInfoCollection() internal ApplicationInfoCollection(IList apps) { - ArgumentGuard.NotNull(apps); + ArgumentNullException.ThrowIfNull(apps); ArgumentGuard.ElementsNotNull(apps); foreach (ApplicationInfo app in apps) @@ -45,21 +45,21 @@ internal ApplicationInfoCollection(IList apps) internal ApplicationInfo? GetRegisteredApplication(string appName) { - ArgumentGuard.NotNullOrWhiteSpace(appName); + ArgumentException.ThrowIfNullOrWhiteSpace(appName); return ApplicationMap.GetValueOrDefault(appName.ToUpperInvariant()); } internal IReadOnlyList GetInstancesBySecureVipAddress(string secureVipAddress) { - ArgumentGuard.NotNullOrWhiteSpace(secureVipAddress); + ArgumentException.ThrowIfNullOrWhiteSpace(secureVipAddress); return GetByVipAddress(secureVipAddress, SecureVipInstanceMap); } internal IReadOnlyList GetInstancesByVipAddress(string vipAddress) { - ArgumentGuard.NotNullOrWhiteSpace(vipAddress); + ArgumentException.ThrowIfNullOrWhiteSpace(vipAddress); return GetByVipAddress(vipAddress, VipInstanceMap); } @@ -72,7 +72,7 @@ public override string ToString() internal void Add(ApplicationInfo app) { - ArgumentGuard.NotNull(app); + ArgumentNullException.ThrowIfNull(app); ApplicationMap.AddOrUpdate(app.Name.ToUpperInvariant(), app, (_, _) => app); @@ -118,12 +118,12 @@ private static ICollection ExpandVipAddresses(string? addresses) return []; } - return addresses.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).ToArray(); + return addresses.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); } internal void RemoveInstanceFromVip(InstanceInfo instance) { - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(instance); foreach (string vipAddress in ExpandVipAddresses(instance.VipAddress)) { @@ -157,7 +157,7 @@ private void RemoveInstanceFromVip(InstanceInfo instance, string address, internal void UpdateFromDelta(ApplicationInfoCollection delta) { - ArgumentGuard.NotNull(delta); + ArgumentNullException.ThrowIfNull(delta); foreach (ApplicationInfo app in delta.RegisteredApplications) { diff --git a/src/Discovery/src/Eureka/AppInfo/InstanceInfo.cs b/src/Discovery/src/Eureka/AppInfo/InstanceInfo.cs index a76aa27e2e..15bce53be3 100644 --- a/src/Discovery/src/Eureka/AppInfo/InstanceInfo.cs +++ b/src/Discovery/src/Eureka/AppInfo/InstanceInfo.cs @@ -4,7 +4,6 @@ using System.Collections.ObjectModel; using System.Text.Json; -using Steeltoe.Common; using Steeltoe.Discovery.Eureka.Configuration; using Steeltoe.Discovery.Eureka.Transport; using Steeltoe.Discovery.Eureka.Util; @@ -161,7 +160,7 @@ public InstanceStatus EffectiveStatus get => _metadata; init { - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(value); _metadata = WithoutEmptyMetadataValues(value); } } @@ -228,11 +227,11 @@ internal set internal InstanceInfo(string instanceId, string appName, string hostName, string ipAddress, DataCenterInfo dataCenterInfo) { // These are required to register an instance to Eureka server, so they should always be available. - ArgumentGuard.NotNullOrWhiteSpace(instanceId); - ArgumentGuard.NotNullOrWhiteSpace(appName); - ArgumentGuard.NotNullOrWhiteSpace(hostName); - ArgumentGuard.NotNullOrWhiteSpace(ipAddress); - ArgumentGuard.NotNull(dataCenterInfo); + ArgumentException.ThrowIfNullOrWhiteSpace(instanceId); + ArgumentException.ThrowIfNullOrWhiteSpace(appName); + ArgumentException.ThrowIfNullOrWhiteSpace(hostName); + ArgumentException.ThrowIfNullOrWhiteSpace(ipAddress); + ArgumentNullException.ThrowIfNull(dataCenterInfo); InstanceId = instanceId; AppName = appName; @@ -269,7 +268,7 @@ public override string ToString() internal static InstanceInfo FromConfiguration(EurekaInstanceOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); if (string.IsNullOrWhiteSpace(options.IPAddress)) { @@ -474,7 +473,7 @@ internal JsonInstanceInfo ToJson() internal void DetectChanges(InstanceInfo previousInstance) { - ArgumentGuard.NotNull(previousInstance); + ArgumentNullException.ThrowIfNull(previousInstance); if (previousInstance.IsDirty) { @@ -508,7 +507,7 @@ internal void DetectChanges(InstanceInfo previousInstance) internal void ReplaceMetadata(IReadOnlyDictionary newMetadata) { - ArgumentGuard.NotNull(newMetadata); + ArgumentNullException.ThrowIfNull(newMetadata); newMetadata = WithoutEmptyMetadataValues(newMetadata); bool hasChanged = !ReferenceEquals(Metadata, newMetadata) && !Metadata.SequenceEqual(newMetadata); diff --git a/src/Discovery/src/Eureka/AppInfo/LeaseInfo.cs b/src/Discovery/src/Eureka/AppInfo/LeaseInfo.cs index b97087dbd4..ecab87747e 100644 --- a/src/Discovery/src/Eureka/AppInfo/LeaseInfo.cs +++ b/src/Discovery/src/Eureka/AppInfo/LeaseInfo.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json; -using Steeltoe.Common; using Steeltoe.Discovery.Eureka.Configuration; using Steeltoe.Discovery.Eureka.Transport; using Steeltoe.Discovery.Eureka.Util; @@ -78,7 +77,7 @@ public override string ToString() internal static LeaseInfo FromConfiguration(EurekaInstanceOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); return new LeaseInfo { diff --git a/src/Discovery/src/Eureka/ApplicationsFetchedEventArgs.cs b/src/Discovery/src/Eureka/ApplicationsFetchedEventArgs.cs index 39cf112c07..152858922d 100644 --- a/src/Discovery/src/Eureka/ApplicationsFetchedEventArgs.cs +++ b/src/Discovery/src/Eureka/ApplicationsFetchedEventArgs.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Discovery.Eureka.AppInfo; namespace Steeltoe.Discovery.Eureka; @@ -16,7 +15,7 @@ public sealed class ApplicationsFetchedEventArgs : EventArgs public ApplicationsFetchedEventArgs(ApplicationInfoCollection applications) { - ArgumentGuard.NotNull(applications); + ArgumentNullException.ThrowIfNull(applications); Applications = applications; } diff --git a/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs b/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs index 227ebac2a2..8a9daecc0e 100644 --- a/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs +++ b/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs @@ -10,7 +10,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; using Steeltoe.Discovery.Eureka.Configuration; namespace Steeltoe.Discovery.Eureka; @@ -26,9 +25,9 @@ internal sealed class DynamicPortAssignmentHostedService : IHostedLifecycleServi public DynamicPortAssignmentHostedService(IServer server, AspNetServerListenState listenState, EurekaInstanceOptionsChangeTokenSource changeTokenSource) { - ArgumentGuard.NotNull(server); - ArgumentGuard.NotNull(listenState); - ArgumentGuard.NotNull(changeTokenSource); + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(listenState); + ArgumentNullException.ThrowIfNull(changeTokenSource); _server = server; _listenState = listenState; @@ -37,7 +36,7 @@ public DynamicPortAssignmentHostedService(IServer server, AspNetServerListenStat public static void Wire(IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); // Skip wire-up when running from a Hosted Service project instead of an ASP.NET project. if (services.Any(descriptor => descriptor.ServiceType == typeof(IServer))) @@ -124,8 +123,8 @@ internal sealed class EurekaInstanceDynamicPortsPostConfigureOptions : IPostConf public EurekaInstanceDynamicPortsPostConfigureOptions(AspNetServerListenState listenState, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(listenState); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(listenState); + ArgumentNullException.ThrowIfNull(loggerFactory); _listenState = listenState; _optionsLogger = loggerFactory.CreateLogger(); @@ -133,7 +132,7 @@ public EurekaInstanceDynamicPortsPostConfigureOptions(AspNetServerListenState li public void PostConfigure(string? name, EurekaInstanceOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); if (_listenState.ListenOnAddresses != null) { diff --git a/src/Discovery/src/Eureka/EurekaApplicationInfoManager.cs b/src/Discovery/src/Eureka/EurekaApplicationInfoManager.cs index 5b77eebc15..ced392a5f0 100644 --- a/src/Discovery/src/Eureka/EurekaApplicationInfoManager.cs +++ b/src/Discovery/src/Eureka/EurekaApplicationInfoManager.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Discovery.Eureka.AppInfo; using Steeltoe.Discovery.Eureka.Configuration; @@ -38,9 +37,9 @@ public sealed class EurekaApplicationInfoManager : IDisposable public EurekaApplicationInfoManager(IOptionsMonitor clientOptionsMonitor, IOptionsMonitor instanceOptionsMonitor, ILogger logger) { - ArgumentGuard.NotNull(clientOptionsMonitor); - ArgumentGuard.NotNull(instanceOptionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(clientOptionsMonitor); + ArgumentNullException.ThrowIfNull(instanceOptionsMonitor); + ArgumentNullException.ThrowIfNull(logger); if (!clientOptionsMonitor.CurrentValue.Enabled) { diff --git a/src/Discovery/src/Eureka/EurekaApplicationsHealthContributor.cs b/src/Discovery/src/Eureka/EurekaApplicationsHealthContributor.cs index 9cff86c730..24c555fbca 100644 --- a/src/Discovery/src/Eureka/EurekaApplicationsHealthContributor.cs +++ b/src/Discovery/src/Eureka/EurekaApplicationsHealthContributor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.HealthChecks; using Steeltoe.Discovery.Eureka.AppInfo; @@ -23,8 +22,8 @@ public sealed class EurekaApplicationsHealthContributor : IHealthContributor public EurekaApplicationsHealthContributor(EurekaDiscoveryClient discoveryClient, IOptionsMonitor clientOptionsMonitor) { - ArgumentGuard.NotNull(discoveryClient); - ArgumentGuard.NotNull(clientOptionsMonitor); + ArgumentNullException.ThrowIfNull(discoveryClient); + ArgumentNullException.ThrowIfNull(clientOptionsMonitor); _discoveryClient = discoveryClient; _clientOptionsMonitor = clientOptionsMonitor; @@ -92,7 +91,7 @@ private IList GetMonitoredApplications() return configuredApplications; } - return _discoveryClient.Applications.RegisteredApplications.Select(app => app.Name).ToList(); + return _discoveryClient.Applications.RegisteredApplications.Select(app => app.Name).ToArray(); } internal IList? GetApplicationsFromConfiguration() @@ -103,7 +102,7 @@ private IList GetMonitoredApplications() if (monitoredApps is { Length: > 0 }) { - return monitoredApps.ToList(); + return monitoredApps.ToArray(); } return null; diff --git a/src/Discovery/src/Eureka/EurekaClient.cs b/src/Discovery/src/Eureka/EurekaClient.cs index a3e25822a6..cf6cc7d833 100644 --- a/src/Discovery/src/Eureka/EurekaClient.cs +++ b/src/Discovery/src/Eureka/EurekaClient.cs @@ -60,10 +60,10 @@ public sealed class EurekaClient public EurekaClient(IHttpClientFactory httpClientFactory, IOptionsMonitor optionsMonitor, EurekaServiceUriStateManager eurekaServiceUriStateManager, ILogger logger) { - ArgumentGuard.NotNull(httpClientFactory); - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(eurekaServiceUriStateManager); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(httpClientFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(eurekaServiceUriStateManager); + ArgumentNullException.ThrowIfNull(logger); _httpClientFactory = httpClientFactory; _optionsMonitor = optionsMonitor; @@ -85,7 +85,7 @@ public EurekaClient(IHttpClientFactory httpClientFactory, IOptionsMonitor public async Task RegisterAsync(InstanceInfo instance, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(instance); if ((Platform.IsContainerized || Platform.IsCloudHosted) && string.Equals(instance.HostName, "localhost", StringComparison.OrdinalIgnoreCase)) { @@ -119,8 +119,8 @@ public async Task RegisterAsync(InstanceInfo instance, CancellationToken cancell /// public async Task DeregisterAsync(string appName, string instanceId, CancellationToken cancellationToken) { - ArgumentGuard.NotNullOrWhiteSpace(appName); - ArgumentGuard.NotNullOrWhiteSpace(instanceId); + ArgumentException.ThrowIfNullOrWhiteSpace(appName); + ArgumentException.ThrowIfNullOrWhiteSpace(instanceId); string path = $"apps/{WebUtility.UrlEncode(appName)}/{WebUtility.UrlEncode(instanceId)}"; await ExecuteRequestAsync(HttpMethod.Delete, path, null, null, cancellationToken); @@ -146,8 +146,8 @@ public async Task DeregisterAsync(string appName, string instanceId, Cancellatio /// public async Task HeartbeatAsync(string appName, string instanceId, DateTime? lastDirtyTimeUtc, CancellationToken cancellationToken) { - ArgumentGuard.NotNullOrWhiteSpace(appName); - ArgumentGuard.NotNullOrWhiteSpace(instanceId); + ArgumentException.ThrowIfNullOrWhiteSpace(appName); + ArgumentException.ThrowIfNullOrWhiteSpace(instanceId); // NOTES: // - The 'status' query string parameter is always ignored by Eureka Server. @@ -212,7 +212,7 @@ public Task GetDeltaAsync(CancellationToken cancellat /// public Task GetByVipAsync(string vipAddress, CancellationToken cancellationToken) { - ArgumentGuard.NotNullOrWhiteSpace(vipAddress); + ArgumentException.ThrowIfNullOrWhiteSpace(vipAddress); string path = $"vips/{WebUtility.UrlEncode(vipAddress)}"; return GetApplicationsAtPathAsync(path, cancellationToken); diff --git a/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs b/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs index 937ce22da9..0153c3b47d 100644 --- a/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs +++ b/src/Discovery/src/Eureka/EurekaDiscoveryClient.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Discovery; using Steeltoe.Common.Extensions; using Steeltoe.Discovery.Eureka.AppInfo; @@ -68,11 +67,11 @@ internal ApplicationInfoCollection Applications public EurekaDiscoveryClient(EurekaApplicationInfoManager appInfoManager, EurekaClient eurekaClient, IOptionsMonitor clientOptionsMonitor, HealthCheckHandlerProvider healthCheckHandlerProvider, ILogger logger) { - ArgumentGuard.NotNull(appInfoManager); - ArgumentGuard.NotNull(eurekaClient); - ArgumentGuard.NotNull(clientOptionsMonitor); - ArgumentGuard.NotNull(healthCheckHandlerProvider); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(appInfoManager); + ArgumentNullException.ThrowIfNull(eurekaClient); + ArgumentNullException.ThrowIfNull(clientOptionsMonitor); + ArgumentNullException.ThrowIfNull(healthCheckHandlerProvider); + ArgumentNullException.ThrowIfNull(logger); _appInfoManager = appInfoManager; _eurekaClient = eurekaClient; @@ -139,14 +138,14 @@ public EurekaDiscoveryClient(EurekaApplicationInfoManager appInfoManager, Eureka internal ApplicationInfo? GetApplication(string appName) { - ArgumentGuard.NotNullOrWhiteSpace(appName); + ArgumentException.ThrowIfNullOrWhiteSpace(appName); return Applications.GetRegisteredApplication(appName); } internal IReadOnlyList GetInstancesByVipAddress(string vipAddress, bool secure) { - ArgumentGuard.NotNullOrWhiteSpace(vipAddress); + ArgumentException.ThrowIfNullOrWhiteSpace(vipAddress); return secure ? Applications.GetInstancesBySecureVipAddress(vipAddress) : Applications.GetInstancesByVipAddress(vipAddress); } @@ -515,13 +514,13 @@ public Task> GetServiceIdsAsync(CancellationToken cancellationToken /// public Task> GetInstancesAsync(string serviceId, CancellationToken cancellationToken) { - ArgumentGuard.NotNullOrWhiteSpace(serviceId); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceId); IReadOnlyList nonSecureInstances = GetInstancesByVipAddress(serviceId, false); IReadOnlyList secureInstances = GetInstancesByVipAddress(serviceId, true); InstanceInfo[] instances = secureInstances.Concat(nonSecureInstances).DistinctBy(instance => instance.InstanceId).ToArray(); - IList serviceInstances = instances.Select(instance => new EurekaServiceInstance(instance)).Cast().ToList(); + IList serviceInstances = instances.Select(instance => new EurekaServiceInstance(instance)).Cast().ToArray(); _logger.LogDebug("Returning {Count} service instances: {ServiceInstances}", serviceInstances.Count, string.Join(", ", serviceInstances.Select(instance => $"{instance.ServiceId}={instance.Uri}"))); diff --git a/src/Discovery/src/Eureka/EurekaHealthCheckHandler.cs b/src/Discovery/src/Eureka/EurekaHealthCheckHandler.cs index e206b01984..2b0fbb3f1b 100644 --- a/src/Discovery/src/Eureka/EurekaHealthCheckHandler.cs +++ b/src/Discovery/src/Eureka/EurekaHealthCheckHandler.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Discovery.Eureka.AppInfo; using HealthCheckResult = Steeltoe.Common.HealthChecks.HealthCheckResult; @@ -34,9 +33,9 @@ internal sealed class EurekaHealthCheckHandler : IHealthCheckHandler public EurekaHealthCheckHandler(IHealthAggregator healthAggregator, IOptionsMonitor healthOptionsMonitor, IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(healthAggregator); - ArgumentGuard.NotNull(healthOptionsMonitor); - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(healthAggregator); + ArgumentNullException.ThrowIfNull(healthOptionsMonitor); + ArgumentNullException.ThrowIfNull(serviceProvider); _healthAggregator = healthAggregator; _healthOptionsMonitor = healthOptionsMonitor; diff --git a/src/Discovery/src/Eureka/EurekaHttpClientHandlerConfigurer.cs b/src/Discovery/src/Eureka/EurekaHttpClientHandlerConfigurer.cs index a09d2f7039..965cc9c5f7 100644 --- a/src/Discovery/src/Eureka/EurekaHttpClientHandlerConfigurer.cs +++ b/src/Discovery/src/Eureka/EurekaHttpClientHandlerConfigurer.cs @@ -4,7 +4,6 @@ using System.Net; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Http.HttpClientPooling; using Steeltoe.Discovery.Eureka.Configuration; @@ -19,14 +18,14 @@ internal sealed class EurekaHttpClientHandlerConfigurer : IHttpClientHandlerConf public EurekaHttpClientHandlerConfigurer(IOptionsMonitor optionsMonitor) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); _optionsMonitor = optionsMonitor; } public void Configure(HttpClientHandler handler) { - ArgumentGuard.NotNull(handler); + ArgumentNullException.ThrowIfNull(handler); EurekaClientOptions clientOptions = _optionsMonitor.CurrentValue; diff --git a/src/Discovery/src/Eureka/EurekaServerHealthContributor.cs b/src/Discovery/src/Eureka/EurekaServerHealthContributor.cs index d35cda072a..9cab4f81c0 100644 --- a/src/Discovery/src/Eureka/EurekaServerHealthContributor.cs +++ b/src/Discovery/src/Eureka/EurekaServerHealthContributor.cs @@ -4,7 +4,6 @@ using System.Globalization; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.HealthChecks; using Steeltoe.Discovery.Eureka.AppInfo; @@ -26,9 +25,9 @@ internal sealed class EurekaServerHealthContributor : IHealthContributor public EurekaServerHealthContributor(EurekaDiscoveryClient discoveryClient, IOptionsMonitor clientOptionsMonitor, IOptionsMonitor instanceOptionsMonitor) { - ArgumentGuard.NotNull(discoveryClient); - ArgumentGuard.NotNull(clientOptionsMonitor); - ArgumentGuard.NotNull(instanceOptionsMonitor); + ArgumentNullException.ThrowIfNull(discoveryClient); + ArgumentNullException.ThrowIfNull(clientOptionsMonitor); + ArgumentNullException.ThrowIfNull(instanceOptionsMonitor); _discoveryClient = discoveryClient; _clientOptionsMonitor = clientOptionsMonitor; diff --git a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs index d75a9d2ffd..ac3fd0ca9b 100644 --- a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs +++ b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Certificates; using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; @@ -30,7 +29,7 @@ public static class EurekaServiceCollectionExtensions /// public static IServiceCollection AddEurekaDiscoveryClient(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); if (services.All(descriptor => descriptor.ImplementationType != typeof(EurekaDiscoveryClient))) { diff --git a/src/Discovery/src/Eureka/EurekaServiceInstance.cs b/src/Discovery/src/Eureka/EurekaServiceInstance.cs index f6346229ba..e6ac9e1928 100644 --- a/src/Discovery/src/Eureka/EurekaServiceInstance.cs +++ b/src/Discovery/src/Eureka/EurekaServiceInstance.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.Discovery; using Steeltoe.Discovery.Eureka.AppInfo; @@ -22,7 +21,7 @@ internal sealed class EurekaServiceInstance : IServiceInstance public EurekaServiceInstance(InstanceInfo instance) { - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(instance); ServiceId = instance.AppName; Host = instance.HostName; diff --git a/src/Discovery/src/Eureka/EurekaServiceUriStateManager.cs b/src/Discovery/src/Eureka/EurekaServiceUriStateManager.cs index ea46bc1e74..50f02f4e98 100644 --- a/src/Discovery/src/Eureka/EurekaServiceUriStateManager.cs +++ b/src/Discovery/src/Eureka/EurekaServiceUriStateManager.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Discovery.Eureka.Configuration; using Steeltoe.Discovery.Eureka.Transport; @@ -24,8 +23,8 @@ public sealed class EurekaServiceUriStateManager public EurekaServiceUriStateManager(IOptionsMonitor optionsMonitor, ILogger logger) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _optionsMonitor = optionsMonitor; _logger = logger; @@ -81,7 +80,7 @@ private IList GetAvailableServiceUris() } } - return availableServiceUris.ToList(); + return availableServiceUris.ToArray(); } private ISet GetConfiguredServiceUris() @@ -103,7 +102,7 @@ private static Uri EnsureTrailingSlash(string url) /// internal void MarkWorkingServiceUri(Uri serviceUri) { - ArgumentGuard.NotNull(serviceUri); + ArgumentNullException.ThrowIfNull(serviceUri); lock (_lockObject) { @@ -120,7 +119,7 @@ internal void MarkWorkingServiceUri(Uri serviceUri) /// internal void MarkFailingServiceUri(Uri serviceUri) { - ArgumentGuard.NotNull(serviceUri); + ArgumentNullException.ThrowIfNull(serviceUri); lock (_lockObject) { diff --git a/src/Discovery/src/Eureka/GatedAction.cs b/src/Discovery/src/Eureka/GatedAction.cs index c41ee23b0f..6c21787fa2 100644 --- a/src/Discovery/src/Eureka/GatedAction.cs +++ b/src/Discovery/src/Eureka/GatedAction.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Discovery.Eureka; /// @@ -16,7 +14,7 @@ internal sealed class GatedAction public GatedAction(Action action) { - ArgumentGuard.NotNull(action); + ArgumentNullException.ThrowIfNull(action); _action = action; } diff --git a/src/Discovery/src/Eureka/HealthCheckHandlerProvider.cs b/src/Discovery/src/Eureka/HealthCheckHandlerProvider.cs index d0b5f7ad86..21e96fb79f 100644 --- a/src/Discovery/src/Eureka/HealthCheckHandlerProvider.cs +++ b/src/Discovery/src/Eureka/HealthCheckHandlerProvider.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Discovery.Eureka; @@ -16,7 +15,7 @@ public sealed class HealthCheckHandlerProvider public HealthCheckHandlerProvider(IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; } diff --git a/src/Discovery/src/Eureka/InstanceChangedEventArgs.cs b/src/Discovery/src/Eureka/InstanceChangedEventArgs.cs index d88024b3a4..6295ebc225 100644 --- a/src/Discovery/src/Eureka/InstanceChangedEventArgs.cs +++ b/src/Discovery/src/Eureka/InstanceChangedEventArgs.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Discovery.Eureka.AppInfo; namespace Steeltoe.Discovery.Eureka; @@ -17,8 +16,8 @@ internal sealed class InstanceChangedEventArgs : EventArgs public InstanceChangedEventArgs(InstanceInfo newInstance, InstanceInfo previousInstance) { - ArgumentGuard.NotNull(newInstance); - ArgumentGuard.NotNull(previousInstance); + ArgumentNullException.ThrowIfNull(newInstance); + ArgumentNullException.ThrowIfNull(previousInstance); NewInstance = newInstance; PreviousInstance = previousInstance; diff --git a/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs b/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs index 07dedf79c1..57a585e4e1 100644 --- a/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs +++ b/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs @@ -31,10 +31,10 @@ internal sealed class PostConfigureEurekaInstanceOptions : IPostConfigureOptions public PostConfigureEurekaInstanceOptions(IServiceProvider serviceProvider, IConfiguration configuration, IApplicationInstanceInfo appInfo, InetUtils inetUtils) { - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(appInfo); - ArgumentGuard.NotNull(inetUtils); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(appInfo); + ArgumentNullException.ThrowIfNull(inetUtils); _serviceProvider = serviceProvider; _configuration = configuration; @@ -44,7 +44,7 @@ public PostConfigureEurekaInstanceOptions(IServiceProvider serviceProvider, ICon public void PostConfigure(string? name, EurekaInstanceOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); SetRegistrationMethod(options); SetHostNameAndIpAddress(options); diff --git a/src/Discovery/src/Eureka/ValidateEurekaClientOptions.cs b/src/Discovery/src/Eureka/ValidateEurekaClientOptions.cs index 530a0d3230..9e6f98ed91 100644 --- a/src/Discovery/src/Eureka/ValidateEurekaClientOptions.cs +++ b/src/Discovery/src/Eureka/ValidateEurekaClientOptions.cs @@ -12,7 +12,7 @@ internal sealed class ValidateEurekaClientOptions : IValidateOptions(this IHttpClientBuilder builder) where TLoadBalancer : class, ILoadBalancer { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (typeof(TLoadBalancer) == typeof(RandomLoadBalancer) || typeof(TLoadBalancer) == typeof(RoundRobinLoadBalancer)) { diff --git a/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs b/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs index 8ea9901397..51378cf1d4 100644 --- a/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs +++ b/src/Discovery/src/HttpClients/DiscoveryHttpClientHandler.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.Extensions; using Steeltoe.Discovery.HttpClients.LoadBalancers; @@ -23,7 +22,7 @@ public sealed class DiscoveryHttpClientHandler : HttpClientHandler /// public DiscoveryHttpClientHandler(ILoadBalancer loadBalancer) { - ArgumentGuard.NotNull(loadBalancer); + ArgumentNullException.ThrowIfNull(loadBalancer); _loadBalancer = loadBalancer; } @@ -31,7 +30,7 @@ public DiscoveryHttpClientHandler(ILoadBalancer loadBalancer) /// protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); Uri? requestUri = request.RequestUri; Uri? serviceInstanceUri = null; diff --git a/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs b/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs index c4b73f3c7a..7bb91fbc19 100644 --- a/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs +++ b/src/Discovery/src/HttpClients/DiscoveryHttpDelegatingHandler.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; using Steeltoe.Common.Extensions; using Steeltoe.Discovery.HttpClients.LoadBalancers; @@ -28,7 +27,7 @@ public sealed class DiscoveryHttpDelegatingHandler : DelegatingHa /// public DiscoveryHttpDelegatingHandler(IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; } @@ -36,7 +35,7 @@ public DiscoveryHttpDelegatingHandler(IServiceProvider serviceProvider) /// protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); // We can't inject the load balancer, because a user may configure to use service discovery for *all* HTTP clients. // That would result in EurekaDiscoveryClient trying to use this handler for sending requests to Eureka, resulting in an infinite loop. diff --git a/src/Discovery/src/HttpClients/LoadBalancers/RandomLoadBalancer.cs b/src/Discovery/src/HttpClients/LoadBalancers/RandomLoadBalancer.cs index 7a1e7bacfd..1e358786fa 100644 --- a/src/Discovery/src/HttpClients/LoadBalancers/RandomLoadBalancer.cs +++ b/src/Discovery/src/HttpClients/LoadBalancers/RandomLoadBalancer.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Common.Discovery; namespace Steeltoe.Discovery.HttpClients.LoadBalancers; @@ -28,8 +27,8 @@ public sealed class RandomLoadBalancer : ILoadBalancer /// public RandomLoadBalancer(ServiceInstancesResolver serviceInstancesResolver, ILogger logger) { - ArgumentGuard.NotNull(serviceInstancesResolver); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(serviceInstancesResolver); + ArgumentNullException.ThrowIfNull(logger); _serviceInstancesResolver = serviceInstancesResolver; _logger = logger; @@ -38,7 +37,7 @@ public RandomLoadBalancer(ServiceInstancesResolver serviceInstancesResolver, ILo /// public async Task ResolveServiceInstanceAsync(Uri requestUri, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(requestUri); + ArgumentNullException.ThrowIfNull(requestUri); string serviceName = requestUri.Host; _logger.LogTrace("Resolving service instance for '{ServiceName}'.", serviceName); diff --git a/src/Discovery/src/HttpClients/LoadBalancers/RoundRobinLoadBalancer.cs b/src/Discovery/src/HttpClients/LoadBalancers/RoundRobinLoadBalancer.cs index af69269670..6f9b816e13 100644 --- a/src/Discovery/src/HttpClients/LoadBalancers/RoundRobinLoadBalancer.cs +++ b/src/Discovery/src/HttpClients/LoadBalancers/RoundRobinLoadBalancer.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Steeltoe.Common; using Steeltoe.Common.Discovery; namespace Steeltoe.Discovery.HttpClients.LoadBalancers; @@ -55,8 +54,8 @@ public RoundRobinLoadBalancer(ServiceInstancesResolver serviceInstancesResolver, public RoundRobinLoadBalancer(ServiceInstancesResolver serviceInstancesResolver, IDistributedCache? distributedCache, DistributedCacheEntryOptions? cacheEntryOptions, ILogger logger) { - ArgumentGuard.NotNull(serviceInstancesResolver); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(serviceInstancesResolver); + ArgumentNullException.ThrowIfNull(logger); _serviceInstancesResolver = serviceInstancesResolver; _distributedCache = distributedCache; @@ -67,7 +66,7 @@ public RoundRobinLoadBalancer(ServiceInstancesResolver serviceInstancesResolver, /// public async Task ResolveServiceInstanceAsync(Uri requestUri, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(requestUri); + ArgumentNullException.ThrowIfNull(requestUri); string serviceName = requestUri.Host; _logger.LogTrace("Resolving service instance for '{ServiceName}'.", serviceName); diff --git a/src/Discovery/src/HttpClients/LoadBalancers/ServiceInstancesResolver.cs b/src/Discovery/src/HttpClients/LoadBalancers/ServiceInstancesResolver.cs index a78e5d0a0d..8757223fb7 100644 --- a/src/Discovery/src/HttpClients/LoadBalancers/ServiceInstancesResolver.cs +++ b/src/Discovery/src/HttpClients/LoadBalancers/ServiceInstancesResolver.cs @@ -53,10 +53,13 @@ public ServiceInstancesResolver(IEnumerable discoveryClients, public ServiceInstancesResolver(IEnumerable discoveryClients, IDistributedCache? distributedCache, DistributedCacheEntryOptions? cacheEntryOptions, ILogger logger) { - ArgumentGuard.NotNull(discoveryClients); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(discoveryClients); + ArgumentNullException.ThrowIfNull(logger); - _discoveryClients = discoveryClients.ToArray(); + IDiscoveryClient[] discoveryClientArray = discoveryClients.ToArray(); + ArgumentGuard.ElementsNotNull(discoveryClientArray); + + _discoveryClients = discoveryClientArray; _distributedCache = distributedCache; _cacheEntryOptions = cacheEntryOptions ?? new DistributedCacheEntryOptions(); _logger = logger; @@ -69,7 +72,7 @@ public ServiceInstancesResolver(IEnumerable discoveryClients, public async Task> ResolveInstancesAsync(string serviceId, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(serviceId); + ArgumentException.ThrowIfNullOrWhiteSpace(serviceId); string cacheKey = $"Steeltoe:Discovery:ServiceInstances:{serviceId}"; @@ -126,7 +129,7 @@ public async Task> ResolveInstancesAsync(string serviceI private static byte[] ToCacheValue(IEnumerable instances) { - List serializableInstances = instances.Select(JsonSerializableServiceInstance.CopyFrom).ToList(); + JsonSerializableServiceInstance[] serializableInstances = instances.Select(JsonSerializableServiceInstance.CopyFrom).ToArray(); return JsonSerializer.SerializeToUtf8Bytes(serializableInstances); } @@ -143,7 +146,7 @@ private sealed class JsonSerializableServiceInstance : IServiceInstance public static JsonSerializableServiceInstance CopyFrom(IServiceInstance instance) { - ArgumentGuard.NotNull(instance); + ArgumentNullException.ThrowIfNull(instance); return new JsonSerializableServiceInstance { diff --git a/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpClientHandlerTest.cs b/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpClientHandlerTest.cs index 3cd035141b..675d1667c7 100644 --- a/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpClientHandlerTest.cs +++ b/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpClientHandlerTest.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Data; -using Steeltoe.Common; using Steeltoe.Discovery.HttpClients.LoadBalancers; namespace Steeltoe.Discovery.HttpClients.Test.LoadBalancers; @@ -58,8 +57,8 @@ public Task ResolveServiceInstanceAsync(Uri requestUri, CancellationToken c public Task UpdateStatisticsAsync(Uri requestUri, Uri serviceInstanceUri, TimeSpan? responseTime, Exception? exception, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(requestUri); - ArgumentGuard.NotNull(serviceInstanceUri); + ArgumentNullException.ThrowIfNull(requestUri); + ArgumentNullException.ThrowIfNull(serviceInstanceUri); Statistics.Add(new LoadBalancerStatistic(requestUri, serviceInstanceUri, responseTime, exception)); return Task.CompletedTask; diff --git a/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpDelegatingHandlerTest.cs b/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpDelegatingHandlerTest.cs index e78aefd73e..4bcdccd160 100644 --- a/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpDelegatingHandlerTest.cs +++ b/src/Discovery/test/HttpClients.Test/LoadBalancers/DiscoveryHttpDelegatingHandlerTest.cs @@ -5,7 +5,6 @@ using System.Data; using System.Net; using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; using Steeltoe.Discovery.HttpClients.LoadBalancers; namespace Steeltoe.Discovery.HttpClients.Test.LoadBalancers; @@ -157,8 +156,8 @@ public Task ResolveServiceInstanceAsync(Uri requestUri, CancellationToken c public Task UpdateStatisticsAsync(Uri requestUri, Uri serviceInstanceUri, TimeSpan? responseTime, Exception? exception, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(requestUri); - ArgumentGuard.NotNull(serviceInstanceUri); + ArgumentNullException.ThrowIfNull(requestUri); + ArgumentNullException.ThrowIfNull(serviceInstanceUri); Statistics.Add(new LoadBalancerStatistic(requestUri, serviceInstanceUri, responseTime, exception)); return Task.CompletedTask; diff --git a/src/Discovery/test/HttpClients.Test/LoadBalancers/FakeLoadBalancer.cs b/src/Discovery/test/HttpClients.Test/LoadBalancers/FakeLoadBalancer.cs index d9519355be..a2c868ab90 100644 --- a/src/Discovery/test/HttpClients.Test/LoadBalancers/FakeLoadBalancer.cs +++ b/src/Discovery/test/HttpClients.Test/LoadBalancers/FakeLoadBalancer.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Discovery.HttpClients.LoadBalancers; namespace Steeltoe.Discovery.HttpClients.Test.LoadBalancers; @@ -16,7 +15,7 @@ internal sealed class FakeLoadBalancer : ILoadBalancer public Task ResolveServiceInstanceAsync(Uri requestUri, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(requestUri); + ArgumentNullException.ThrowIfNull(requestUri); string replacementUri = requestUri.AbsoluteUri.Replace("replace-me", "some-resolved-host:1234", StringComparison.Ordinal); return Task.FromResult(new Uri(replacementUri)); @@ -24,8 +23,8 @@ public Task ResolveServiceInstanceAsync(Uri requestUri, CancellationToken c public Task UpdateStatisticsAsync(Uri requestUri, Uri serviceInstanceUri, TimeSpan? responseTime, Exception? exception, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(requestUri); - ArgumentGuard.NotNull(serviceInstanceUri); + ArgumentNullException.ThrowIfNull(requestUri); + ArgumentNullException.ThrowIfNull(serviceInstanceUri); Statistics.Add(new LoadBalancerStatistic(requestUri, serviceInstanceUri, responseTime, exception)); return Task.CompletedTask; diff --git a/src/Logging/src/Abstractions/DynamicLoggerConfiguration.cs b/src/Logging/src/Abstractions/DynamicLoggerConfiguration.cs index 7996a6cfd7..a5a6bc2478 100644 --- a/src/Logging/src/Abstractions/DynamicLoggerConfiguration.cs +++ b/src/Logging/src/Abstractions/DynamicLoggerConfiguration.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Logging; @@ -41,7 +40,7 @@ public sealed class DynamicLoggerConfiguration /// public DynamicLoggerConfiguration(string categoryName, LogLevel? configurationMinLevel, LogLevel effectiveMinLevel) { - ArgumentGuard.NotNullOrEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); CategoryName = categoryName; ConfigurationMinLevel = configurationMinLevel; diff --git a/src/Logging/src/Abstractions/DynamicLoggerProvider.cs b/src/Logging/src/Abstractions/DynamicLoggerProvider.cs index 4f408f563d..bf542a05f7 100644 --- a/src/Logging/src/Abstractions/DynamicLoggerProvider.cs +++ b/src/Logging/src/Abstractions/DynamicLoggerProvider.cs @@ -22,7 +22,7 @@ public abstract class DynamicLoggerProvider : IDynamicLoggerProvider private LoggerFilter _defaultFilter; protected ILoggerProvider InnerLoggerProvider { get; } - protected IEnumerable MessageProcessors { get; } + protected ICollection MessageProcessors { get; } /// /// Initializes a new instance of the class. @@ -39,21 +39,24 @@ public abstract class DynamicLoggerProvider : IDynamicLoggerProvider protected DynamicLoggerProvider(ILoggerProvider innerLoggerProvider, LoggerFilterConfiguration loggerFilterConfiguration, IEnumerable messageProcessors) { - ArgumentGuard.NotNull(innerLoggerProvider); - ArgumentGuard.NotNull(loggerFilterConfiguration); - ArgumentGuard.NotNull(messageProcessors); + ArgumentNullException.ThrowIfNull(innerLoggerProvider); + ArgumentNullException.ThrowIfNull(loggerFilterConfiguration); + ArgumentNullException.ThrowIfNull(messageProcessors); + + IDynamicMessageProcessor[] messageProcessorArray = messageProcessors.ToArray(); + ArgumentGuard.ElementsNotNull(messageProcessorArray); InnerLoggerProvider = innerLoggerProvider; _configurationMinLevels = loggerFilterConfiguration.ConfigurationMinLevels; _effectiveFiltersPerCategory = new ConcurrentDictionary(loggerFilterConfiguration.EffectiveFilters, StringComparer.Ordinal); _defaultFilter = loggerFilterConfiguration.DefaultFilter; - MessageProcessors = messageProcessors; + MessageProcessors = messageProcessorArray; } /// public ILogger CreateLogger(string categoryName) { - ArgumentGuard.NotNullOrEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); return _activeLoggersPerCategory.GetOrAdd(categoryName, CreateMessageProcessingLogger(categoryName)); } @@ -86,7 +89,7 @@ public ICollection GetLoggerConfigurations() /// public void SetLogLevel(string categoryName, LogLevel? minLevel) { - ArgumentGuard.NotNullOrEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); LoggerFilter? filter = minLevel != null ? level => level >= minLevel : null; @@ -171,7 +174,7 @@ protected virtual void Dispose(bool disposing) protected virtual MessageProcessingLogger CreateMessageProcessingLogger(string categoryName) { - ArgumentGuard.NotNullOrEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); ILogger logger = InnerLoggerProvider.CreateLogger(categoryName); LoggerFilter filter = GetFilter(categoryName); @@ -181,7 +184,7 @@ protected virtual MessageProcessingLogger CreateMessageProcessingLogger(string c protected LoggerFilter GetFilter(string categoryName) { - ArgumentGuard.NotNullOrEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); foreach (string name in GetCategoryNameWithParents(categoryName)) { diff --git a/src/Logging/src/Abstractions/LoggerFilterConfiguration.cs b/src/Logging/src/Abstractions/LoggerFilterConfiguration.cs index 9f1021f5ae..3f3eaafa11 100644 --- a/src/Logging/src/Abstractions/LoggerFilterConfiguration.cs +++ b/src/Logging/src/Abstractions/LoggerFilterConfiguration.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Logging; @@ -42,8 +41,8 @@ public sealed class LoggerFilterConfiguration public LoggerFilterConfiguration(IReadOnlyDictionary configurationMinLevels, IReadOnlyDictionary effectiveFilters, LoggerFilter defaultFilter) { - ArgumentGuard.NotNull(configurationMinLevels); - ArgumentGuard.NotNull(effectiveFilters); + ArgumentNullException.ThrowIfNull(configurationMinLevels); + ArgumentNullException.ThrowIfNull(effectiveFilters); ConfigurationMinLevels = configurationMinLevels; EffectiveFilters = effectiveFilters; diff --git a/src/Logging/src/Abstractions/MessageProcessingLogger.cs b/src/Logging/src/Abstractions/MessageProcessingLogger.cs index 7e6ba96f94..ee89074640 100644 --- a/src/Logging/src/Abstractions/MessageProcessingLogger.cs +++ b/src/Logging/src/Abstractions/MessageProcessingLogger.cs @@ -13,9 +13,10 @@ namespace Steeltoe.Logging; /// public class MessageProcessingLogger : ILogger { - private readonly IEnumerable _messageProcessors; private LoggerFilter _filter; + protected ICollection MessageProcessors { get; } + protected internal ILogger InnerLogger { get; } /// @@ -32,13 +33,16 @@ public class MessageProcessingLogger : ILogger /// public MessageProcessingLogger(ILogger innerLogger, LoggerFilter filter, IEnumerable messageProcessors) { - ArgumentGuard.NotNull(innerLogger); - ArgumentGuard.NotNull(filter); - ArgumentGuard.NotNull(messageProcessors); + ArgumentNullException.ThrowIfNull(innerLogger); + ArgumentNullException.ThrowIfNull(filter); + ArgumentNullException.ThrowIfNull(messageProcessors); + + IDynamicMessageProcessor[] messageProcessorArray = messageProcessors.ToArray(); + ArgumentGuard.ElementsNotNull(messageProcessorArray); InnerLogger = innerLogger; _filter = filter; - _messageProcessors = messageProcessors; + MessageProcessors = messageProcessorArray; } /// @@ -49,7 +53,7 @@ public MessageProcessingLogger(ILogger innerLogger, LoggerFilter filter, IEnumer /// public void ChangeFilter(LoggerFilter filter) { - ArgumentGuard.NotNull(filter); + ArgumentNullException.ThrowIfNull(filter); _filter = filter; } @@ -75,7 +79,7 @@ public bool IsEnabled(LogLevel logLevel) /// public virtual void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { - ArgumentGuard.NotNull(formatter); + ArgumentNullException.ThrowIfNull(formatter); if (!IsEnabled(logLevel)) { @@ -83,7 +87,7 @@ public virtual void Log(LogLevel logLevel, EventId eventId, TState state } Func compositeFormatter = (innerState, innerException) => - ApplyMessageProcessors(innerState, innerException, formatter, _messageProcessors); + ApplyMessageProcessors(innerState, innerException, formatter, MessageProcessors); InnerLogger.Log(logLevel, eventId, state, exception, compositeFormatter); } diff --git a/src/Logging/src/Abstractions/PublicAPI.Unshipped.txt b/src/Logging/src/Abstractions/PublicAPI.Unshipped.txt index e0e19a6c12..d9a7614f76 100644 --- a/src/Logging/src/Abstractions/PublicAPI.Unshipped.txt +++ b/src/Logging/src/Abstractions/PublicAPI.Unshipped.txt @@ -14,7 +14,7 @@ Steeltoe.Logging.DynamicLoggerProvider.DynamicLoggerProvider(Microsoft.Extension Steeltoe.Logging.DynamicLoggerProvider.GetFilter(string! categoryName) -> Steeltoe.Logging.LoggerFilter! Steeltoe.Logging.DynamicLoggerProvider.GetLoggerConfigurations() -> System.Collections.Generic.ICollection! Steeltoe.Logging.DynamicLoggerProvider.InnerLoggerProvider.get -> Microsoft.Extensions.Logging.ILoggerProvider! -Steeltoe.Logging.DynamicLoggerProvider.MessageProcessors.get -> System.Collections.Generic.IEnumerable! +Steeltoe.Logging.DynamicLoggerProvider.MessageProcessors.get -> System.Collections.Generic.ICollection! Steeltoe.Logging.DynamicLoggerProvider.SetLogLevel(string! categoryName, Microsoft.Extensions.Logging.LogLevel? minLevel) -> void Steeltoe.Logging.IDynamicLoggerProvider Steeltoe.Logging.IDynamicLoggerProvider.GetLoggerConfigurations() -> System.Collections.Generic.ICollection! @@ -33,6 +33,7 @@ Steeltoe.Logging.MessageProcessingLogger.ChangeFilter(Steeltoe.Logging.LoggerFil Steeltoe.Logging.MessageProcessingLogger.InnerLogger.get -> Microsoft.Extensions.Logging.ILogger! Steeltoe.Logging.MessageProcessingLogger.IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) -> bool Steeltoe.Logging.MessageProcessingLogger.MessageProcessingLogger(Microsoft.Extensions.Logging.ILogger! innerLogger, Steeltoe.Logging.LoggerFilter! filter, System.Collections.Generic.IEnumerable! messageProcessors) -> void +Steeltoe.Logging.MessageProcessingLogger.MessageProcessors.get -> System.Collections.Generic.ICollection! virtual Steeltoe.Logging.DynamicLoggerProvider.CreateMessageProcessingLogger(string! categoryName) -> Steeltoe.Logging.MessageProcessingLogger! virtual Steeltoe.Logging.DynamicLoggerProvider.Dispose(bool disposing) -> void virtual Steeltoe.Logging.MessageProcessingLogger.Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, System.Exception? exception, System.Func! formatter) -> void diff --git a/src/Logging/src/DynamicLogger/DynamicConsoleLoggerProvider.cs b/src/Logging/src/DynamicLogger/DynamicConsoleLoggerProvider.cs index eafdddc00b..ea8ae05000 100644 --- a/src/Logging/src/DynamicLogger/DynamicConsoleLoggerProvider.cs +++ b/src/Logging/src/DynamicLogger/DynamicConsoleLoggerProvider.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Logging.DynamicLogger; @@ -23,7 +22,7 @@ public DynamicConsoleLoggerProvider(IOptionsMonitor filterO private static LoggerFilterConfiguration GetMinimumLevelsFromOptions(IOptionsMonitor filterOptionsMonitor) { - ArgumentGuard.NotNull(filterOptionsMonitor); + ArgumentNullException.ThrowIfNull(filterOptionsMonitor); var effectiveFilters = new Dictionary(); var configurationMinLevels = new Dictionary(); @@ -60,7 +59,7 @@ private static bool IsConsoleProvider(LoggerFilterRule rule) void ISupportExternalScope.SetScopeProvider(IExternalScopeProvider scopeProvider) { - ArgumentGuard.NotNull(scopeProvider); + ArgumentNullException.ThrowIfNull(scopeProvider); ((ConsoleLoggerProvider)InnerLoggerProvider).SetScopeProvider(scopeProvider); } diff --git a/src/Logging/src/DynamicLogger/LoggingBuilderExtensions.cs b/src/Logging/src/DynamicLogger/LoggingBuilderExtensions.cs index 92505fdfa6..962b2179ab 100644 --- a/src/Logging/src/DynamicLogger/LoggingBuilderExtensions.cs +++ b/src/Logging/src/DynamicLogger/LoggingBuilderExtensions.cs @@ -25,7 +25,7 @@ public static class LoggingBuilderExtensions /// public static ILoggingBuilder AddDynamicConsole(this ILoggingBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (!IsDynamicLoggerProviderAlreadyRegistered(builder)) { diff --git a/src/Logging/src/DynamicSerilog/DynamicSerilogLoggerProvider.cs b/src/Logging/src/DynamicSerilog/DynamicSerilogLoggerProvider.cs index f3dfeea70d..ea2b3cd075 100644 --- a/src/Logging/src/DynamicSerilog/DynamicSerilogLoggerProvider.cs +++ b/src/Logging/src/DynamicSerilog/DynamicSerilogLoggerProvider.cs @@ -7,7 +7,6 @@ using Serilog.Core; using Serilog.Events; using Serilog.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Logging.DynamicSerilog; @@ -38,7 +37,7 @@ internal static void ClearLogger() protected override MessageProcessingLogger CreateMessageProcessingLogger(string categoryName) { - ArgumentGuard.NotNullOrEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); ILogger logger = InnerLoggerProvider.CreateLogger(categoryName); LoggerFilter filter = GetFilter(categoryName); @@ -48,7 +47,7 @@ protected override MessageProcessingLogger CreateMessageProcessingLogger(string private static ILoggerProvider CreateSerilogLogger(IOptionsMonitor serilogOptionsMonitor) { - ArgumentGuard.NotNull(serilogOptionsMonitor); + ArgumentNullException.ThrowIfNull(serilogOptionsMonitor); lock (LoggerLock) { @@ -60,7 +59,7 @@ private static ILoggerProvider CreateSerilogLogger(IOptionsMonitor serilogOptionsMonitor) { - ArgumentGuard.NotNull(serilogOptionsMonitor); + ArgumentNullException.ThrowIfNull(serilogOptionsMonitor); SerilogOptions options = serilogOptionsMonitor.CurrentValue; var defaultMinLevel = (LogLevel)options.MinimumLevel!.Default; diff --git a/src/Logging/src/DynamicSerilog/HostBuilderWrapperExtensions.cs b/src/Logging/src/DynamicSerilog/HostBuilderWrapperExtensions.cs index a3cded6829..6a310e5755 100644 --- a/src/Logging/src/DynamicSerilog/HostBuilderWrapperExtensions.cs +++ b/src/Logging/src/DynamicSerilog/HostBuilderWrapperExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Serilog; -using Steeltoe.Common; using Steeltoe.Common.Hosting; namespace Steeltoe.Logging.DynamicSerilog; @@ -13,7 +12,7 @@ internal static class HostBuilderWrapperExtensions public static HostBuilderWrapper AddDynamicSerilog(this HostBuilderWrapper wrapper, Action? configureLogger, bool preserveDefaultConsole) { - ArgumentGuard.NotNull(wrapper); + ArgumentNullException.ThrowIfNull(wrapper); wrapper.ConfigureLogging((hostContext, loggingBuilder) => { diff --git a/src/Logging/src/DynamicSerilog/SerilogConfigurationExtensions.cs b/src/Logging/src/DynamicSerilog/SerilogConfigurationExtensions.cs index 38df5c1a2d..65155f6a3c 100644 --- a/src/Logging/src/DynamicSerilog/SerilogConfigurationExtensions.cs +++ b/src/Logging/src/DynamicSerilog/SerilogConfigurationExtensions.cs @@ -4,7 +4,6 @@ using Serilog; using Serilog.Events; -using Steeltoe.Common; namespace Steeltoe.Logging.DynamicSerilog; @@ -16,8 +15,8 @@ internal static class SerilogConfigurationExtensions /// public static LoggerConfiguration ClearLevels(this LoggerConfiguration loggerConfiguration, MinimumLevel minimumLevel) { - ArgumentGuard.NotNull(loggerConfiguration); - ArgumentGuard.NotNull(minimumLevel); + ArgumentNullException.ThrowIfNull(loggerConfiguration); + ArgumentNullException.ThrowIfNull(minimumLevel); foreach (KeyValuePair overrideLevel in minimumLevel.Override) { diff --git a/src/Logging/src/DynamicSerilog/SerilogHostApplicationBuilderExtensions.cs b/src/Logging/src/DynamicSerilog/SerilogHostApplicationBuilderExtensions.cs index b7828b838f..f7cfd7e5fd 100644 --- a/src/Logging/src/DynamicSerilog/SerilogHostApplicationBuilderExtensions.cs +++ b/src/Logging/src/DynamicSerilog/SerilogHostApplicationBuilderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Hosting; using Serilog; -using Steeltoe.Common; using Steeltoe.Common.Hosting; namespace Steeltoe.Logging.DynamicSerilog; @@ -78,7 +77,7 @@ public static IHostApplicationBuilder AddDynamicSerilog(this IHostApplicationBui public static IHostApplicationBuilder AddDynamicSerilog(this IHostApplicationBuilder builder, Action? configureLogger, bool preserveDefaultConsole) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddDynamicSerilog(HostBuilderContextWrapper.WrapAction(configureLogger), preserveDefaultConsole); diff --git a/src/Logging/src/DynamicSerilog/SerilogHostBuilderExtensions.cs b/src/Logging/src/DynamicSerilog/SerilogHostBuilderExtensions.cs index a05ab6c80a..ef874e391b 100644 --- a/src/Logging/src/DynamicSerilog/SerilogHostBuilderExtensions.cs +++ b/src/Logging/src/DynamicSerilog/SerilogHostBuilderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Hosting; using Serilog; -using Steeltoe.Common; using Steeltoe.Common.Hosting; namespace Steeltoe.Logging.DynamicSerilog; @@ -77,7 +76,7 @@ public static IHostBuilder AddDynamicSerilog(this IHostBuilder builder, bool pre public static IHostBuilder AddDynamicSerilog(this IHostBuilder builder, Action? configureLogger, bool preserveDefaultConsole) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddDynamicSerilog(HostBuilderContextWrapper.WrapAction(configureLogger), preserveDefaultConsole); diff --git a/src/Logging/src/DynamicSerilog/SerilogLoggingBuilderExtensions.cs b/src/Logging/src/DynamicSerilog/SerilogLoggingBuilderExtensions.cs index d956f405b8..df60b864be 100644 --- a/src/Logging/src/DynamicSerilog/SerilogLoggingBuilderExtensions.cs +++ b/src/Logging/src/DynamicSerilog/SerilogLoggingBuilderExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Serilog; -using Steeltoe.Common; namespace Steeltoe.Logging.DynamicSerilog; @@ -78,7 +77,7 @@ public static ILoggingBuilder AddDynamicSerilog(this ILoggingBuilder builder, bo /// public static ILoggingBuilder AddDynamicSerilog(this ILoggingBuilder builder, LoggerConfiguration? serilogConfiguration, bool preserveDefaultConsole) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (builder.Services.Any(descriptor => descriptor.ServiceType == typeof(IDynamicLoggerProvider))) { diff --git a/src/Logging/src/DynamicSerilog/SerilogMessageProcessingLogger.cs b/src/Logging/src/DynamicSerilog/SerilogMessageProcessingLogger.cs index f090b3cf5c..fcfea7c011 100644 --- a/src/Logging/src/DynamicSerilog/SerilogMessageProcessingLogger.cs +++ b/src/Logging/src/DynamicSerilog/SerilogMessageProcessingLogger.cs @@ -3,24 +3,20 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Logging.DynamicSerilog; public sealed class SerilogMessageProcessingLogger : MessageProcessingLogger { - private readonly IEnumerable _messageProcessors; - public SerilogMessageProcessingLogger(ILogger innerLogger, LoggerFilter filter, IEnumerable messageProcessors) : base(innerLogger, filter, messageProcessors) { - _messageProcessors = messageProcessors; } /// public override void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { - ArgumentGuard.NotNull(formatter); + ArgumentNullException.ThrowIfNull(formatter); if (!IsEnabled(logLevel)) { @@ -34,7 +30,7 @@ public override void Log(LogLevel logLevel, EventId eventId, TState stat string scopeMessage = string.Empty; - foreach (IDynamicMessageProcessor processor in _messageProcessors) + foreach (IDynamicMessageProcessor processor in MessageProcessors) { scopeMessage = processor.Process(scopeMessage); } diff --git a/src/Logging/src/DynamicSerilog/SerilogOptions.cs b/src/Logging/src/DynamicSerilog/SerilogOptions.cs index ebcfd789b4..a5c066287d 100644 --- a/src/Logging/src/DynamicSerilog/SerilogOptions.cs +++ b/src/Logging/src/DynamicSerilog/SerilogOptions.cs @@ -6,7 +6,6 @@ using Serilog; using Serilog.Core; using Serilog.Events; -using Steeltoe.Common; using Steeltoe.Logging.DynamicSerilog.DynamicTypeAccess; namespace Steeltoe.Logging.DynamicSerilog; @@ -31,7 +30,7 @@ public sealed class SerilogOptions /// internal void SetSerilogOptions(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); IConfigurationSection section = configuration.GetSection("Serilog"); section.Bind(this); @@ -64,7 +63,7 @@ internal void SetSerilogOptions(IConfiguration configuration) /// internal void SetSerilogOptions(LoggerConfiguration loggerConfiguration) { - ArgumentGuard.NotNull(loggerConfiguration); + ArgumentNullException.ThrowIfNull(loggerConfiguration); var shim = new LoggerConfigurationShim(loggerConfiguration); diff --git a/src/Logging/src/DynamicSerilog/SerilogWebHostBuilderExtensions.cs b/src/Logging/src/DynamicSerilog/SerilogWebHostBuilderExtensions.cs index ea2d85c58c..656cacc982 100644 --- a/src/Logging/src/DynamicSerilog/SerilogWebHostBuilderExtensions.cs +++ b/src/Logging/src/DynamicSerilog/SerilogWebHostBuilderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Hosting; using Serilog; -using Steeltoe.Common; using Steeltoe.Common.Hosting; namespace Steeltoe.Logging.DynamicSerilog; @@ -77,7 +76,7 @@ public static IWebHostBuilder AddDynamicSerilog(this IWebHostBuilder builder, bo public static IWebHostBuilder AddDynamicSerilog(this IWebHostBuilder builder, Action? configureLogger, bool preserveDefaultConsole) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddDynamicSerilog(HostBuilderContextWrapper.WrapAction(configureLogger), preserveDefaultConsole); diff --git a/src/Logging/test/DynamicSerilog.Test/LoggerSinkConfigurationExtensions.cs b/src/Logging/test/DynamicSerilog.Test/LoggerSinkConfigurationExtensions.cs index 0905fd52b3..c1eb4b6eb5 100644 --- a/src/Logging/test/DynamicSerilog.Test/LoggerSinkConfigurationExtensions.cs +++ b/src/Logging/test/DynamicSerilog.Test/LoggerSinkConfigurationExtensions.cs @@ -5,7 +5,6 @@ using Serilog; using Serilog.Configuration; using Serilog.Events; -using Steeltoe.Common; namespace Steeltoe.Logging.DynamicSerilog.Test; @@ -16,7 +15,7 @@ public static class LoggerSinkConfigurationExtensions { public static LoggerConfiguration TestSink(this LoggerSinkConfiguration loggerConfiguration) { - ArgumentGuard.NotNull(loggerConfiguration); + ArgumentNullException.ThrowIfNull(loggerConfiguration); return loggerConfiguration.Sink(Test.TestSink.GetCurrentSink(), LogEventLevel.Verbose); } diff --git a/src/Management/src/Abstractions/Diagnostics/DiagnosticObserver.cs b/src/Management/src/Abstractions/Diagnostics/DiagnosticObserver.cs index fb9d327eff..0c75e61a55 100644 --- a/src/Management/src/Abstractions/Diagnostics/DiagnosticObserver.cs +++ b/src/Management/src/Abstractions/Diagnostics/DiagnosticObserver.cs @@ -5,7 +5,6 @@ using System.Diagnostics; using System.Reflection; using Microsoft.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Management.Diagnostics; @@ -19,9 +18,9 @@ public abstract class DiagnosticObserver : IDiagnosticObserver protected DiagnosticObserver(string name, string listenerName, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNullOrEmpty(name); - ArgumentGuard.NotNullOrEmpty(listenerName); - ArgumentGuard.NotNull(loggerFactory); + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(listenerName); + ArgumentNullException.ThrowIfNull(loggerFactory); ObserverName = name; ListenerName = listenerName; @@ -47,7 +46,7 @@ protected virtual void Dispose(bool disposing) public void Subscribe(DiagnosticListener listener) { - ArgumentGuard.NotNull(listener); + ArgumentNullException.ThrowIfNull(listener); if (ListenerName == listener.Name) { @@ -85,8 +84,8 @@ public virtual void OnNext(KeyValuePair @event) private protected static T? GetPropertyOrDefault(object instance, string name) { - ArgumentGuard.NotNull(instance); - ArgumentGuard.NotNull(name); + ArgumentNullException.ThrowIfNull(instance); + ArgumentException.ThrowIfNullOrWhiteSpace(name); PropertyInfo? property = instance.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public); diff --git a/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs b/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs index 67c5e23a30..0a36e2ddd5 100755 --- a/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs +++ b/src/Management/src/Abstractions/Diagnostics/DiagnosticsManager.cs @@ -28,16 +28,25 @@ internal sealed class DiagnosticsManager : IObserver, IDispo public DiagnosticsManager(IOptionsMonitor observerOptions, IEnumerable runtimeSources, IEnumerable observers, IEnumerable eventListeners, ILogger logger) { - ArgumentGuard.NotNull(observerOptions); - ArgumentGuard.NotNull(runtimeSources); - ArgumentGuard.NotNull(observers); - ArgumentGuard.NotNull(eventListeners); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(observerOptions); + ArgumentNullException.ThrowIfNull(runtimeSources); + ArgumentNullException.ThrowIfNull(observers); + ArgumentNullException.ThrowIfNull(eventListeners); + ArgumentNullException.ThrowIfNull(logger); + + IDiagnosticObserver[] observerArray = observers.ToArray(); + ArgumentGuard.ElementsNotNull(observerArray); + + List runtimeSourceList = runtimeSources.ToList(); + ArgumentGuard.ElementsNotNull(runtimeSourceList); + + List eventListenerList = eventListeners.ToList(); + ArgumentGuard.ElementsNotNull(eventListenerList); _logger = logger; var filteredObservers = new List(); - foreach (IDiagnosticObserver observer in observers) + foreach (IDiagnosticObserver observer in observerArray) { if (observerOptions.CurrentValue.IncludeObserver(observer.ObserverName)) { @@ -46,8 +55,8 @@ public DiagnosticsManager(IOptionsMonitor observerOption } _observers = filteredObservers; - _runtimeSources = runtimeSources.ToList(); - _eventListeners = eventListeners.ToList(); + _runtimeSources = runtimeSourceList; + _eventListeners = eventListenerList; } public void OnCompleted() diff --git a/src/Management/src/Abstractions/Info/ConfigurationContributor.cs b/src/Management/src/Abstractions/Info/ConfigurationContributor.cs index 5f2d3d885e..7e5030dd80 100644 --- a/src/Management/src/Abstractions/Info/ConfigurationContributor.cs +++ b/src/Management/src/Abstractions/Info/ConfigurationContributor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Management.Info; @@ -18,8 +17,8 @@ protected ConfigurationContributor(IConfiguration? configuration) protected void Contribute(IInfoBuilder builder, string prefix, bool keepPrefix) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(prefix); + ArgumentNullException.ThrowIfNull(builder); + ArgumentException.ThrowIfNullOrEmpty(prefix); Dictionary dictionary = CreateDictionary(prefix, keepPrefix); builder.WithInfo(dictionary); @@ -70,8 +69,8 @@ private void AddChildren(IDictionary dictionary, IEnumerable dictionary, string key, string value) { - ArgumentGuard.NotNull(dictionary); - ArgumentGuard.NotNull(key); + ArgumentNullException.ThrowIfNull(dictionary); + ArgumentException.ThrowIfNullOrEmpty(key); dictionary[key] = value; } diff --git a/src/Management/src/Abstractions/Info/InfoBuilder.cs b/src/Management/src/Abstractions/Info/InfoBuilder.cs index c1d63f3ce7..9d53de236a 100644 --- a/src/Management/src/Abstractions/Info/InfoBuilder.cs +++ b/src/Management/src/Abstractions/Info/InfoBuilder.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Info; public sealed class InfoBuilder : IInfoBuilder @@ -17,7 +15,7 @@ public IDictionary Build() public IInfoBuilder WithInfo(string key, object value) { - ArgumentGuard.NotNullOrEmpty(key); + ArgumentException.ThrowIfNullOrWhiteSpace(key); _info[key] = value; @@ -26,7 +24,7 @@ public IInfoBuilder WithInfo(string key, object value) public IInfoBuilder WithInfo(IDictionary details) { - ArgumentGuard.NotNull(details); + ArgumentNullException.ThrowIfNull(details); foreach (KeyValuePair pair in details) { diff --git a/src/Management/src/Endpoint/ActuatorConventionBuilder.cs b/src/Management/src/Endpoint/ActuatorConventionBuilder.cs index 2d4eff9b3d..094df129f4 100644 --- a/src/Management/src/Endpoint/ActuatorConventionBuilder.cs +++ b/src/Management/src/Endpoint/ActuatorConventionBuilder.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.AspNetCore.Builder; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint; @@ -13,7 +12,7 @@ public sealed class ActuatorConventionBuilder : IEndpointConventionBuilder public void Add(Action convention) { - ArgumentGuard.NotNull(convention); + ArgumentNullException.ThrowIfNull(convention); foreach (IEndpointConventionBuilder builder in _builders) { @@ -23,7 +22,7 @@ public void Add(Action convention) public void Add(IEndpointConventionBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); _builders.Add(builder); } diff --git a/src/Management/src/Endpoint/ActuatorEndpointMapper.cs b/src/Management/src/Endpoint/ActuatorEndpointMapper.cs index 02e787bd67..949f144329 100755 --- a/src/Management/src/Endpoint/ActuatorEndpointMapper.cs +++ b/src/Management/src/Endpoint/ActuatorEndpointMapper.cs @@ -18,25 +18,28 @@ namespace Steeltoe.Management.Endpoint; internal sealed class ActuatorEndpointMapper { private readonly IOptionsMonitor _managementOptionsMonitor; - private readonly IList _middlewares; + private readonly ICollection _middlewares; private readonly ILogger _logger; public ActuatorEndpointMapper(IOptionsMonitor managementOptionsMonitor, IEnumerable middlewares, ILogger logger) { - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(middlewares); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(middlewares); + ArgumentNullException.ThrowIfNull(logger); + + IEndpointMiddleware[] middlewareArray = middlewares.ToArray(); + ArgumentGuard.ElementsNotNull(middlewareArray); _managementOptionsMonitor = managementOptionsMonitor; - _middlewares = middlewares.ToList(); + _middlewares = middlewareArray; _logger = logger; } public void Map(IEndpointRouteBuilder endpointRouteBuilder, ActuatorConventionBuilder conventionBuilder) { - ArgumentGuard.NotNull(endpointRouteBuilder); - ArgumentGuard.NotNull(conventionBuilder); + ArgumentNullException.ThrowIfNull(endpointRouteBuilder); + ArgumentNullException.ThrowIfNull(conventionBuilder); InnerMap(middleware => endpointRouteBuilder.CreateApplicationBuilder().UseMiddleware(middleware.GetType()).Build(), (middleware, requestPath, pipeline) => @@ -48,7 +51,7 @@ public void Map(IEndpointRouteBuilder endpointRouteBuilder, ActuatorConventionBu public void Map(IRouteBuilder routeBuilder) { - ArgumentGuard.NotNull(routeBuilder); + ArgumentNullException.ThrowIfNull(routeBuilder); InnerMap(middleware => routeBuilder.ApplicationBuilder.UseMiddleware(middleware.GetType()).Build(), (middleware, requestPath, pipeline) => { diff --git a/src/Management/src/Endpoint/ActuatorMediaTypes.cs b/src/Management/src/Endpoint/ActuatorMediaTypes.cs index 87c7b9443a..7f676c747b 100644 --- a/src/Management/src/Endpoint/ActuatorMediaTypes.cs +++ b/src/Management/src/Endpoint/ActuatorMediaTypes.cs @@ -14,9 +14,10 @@ internal static class ActuatorMediaTypes public const string AppJson = "application/json"; public const string Any = "*/*"; - internal static string GetContentHeaders(IList acceptHeaders, MediaTypeVersion version) + internal static string GetContentHeaders(ICollection acceptHeaders, MediaTypeVersion version) { - ArgumentGuard.NotNull(acceptHeaders); + ArgumentNullException.ThrowIfNull(acceptHeaders); + ArgumentGuard.ElementsNotNullOrWhiteSpace(acceptHeaders); string contentHeader = AppJson; string versionContentHeader = GetContentTypeHeaderForVersion(version); diff --git a/src/Management/src/Endpoint/ActuatorRouteBuilderExtensions.cs b/src/Management/src/Endpoint/ActuatorRouteBuilderExtensions.cs index aad88fdcc2..b2c79ab2fe 100644 --- a/src/Management/src/Endpoint/ActuatorRouteBuilderExtensions.cs +++ b/src/Management/src/Endpoint/ActuatorRouteBuilderExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint; @@ -39,7 +38,7 @@ public static IEndpointConventionBuilder MapAllActuators(this IEndpointRouteBuil /// public static IEndpointConventionBuilder MapAllActuators(this IEndpointRouteBuilder routeBuilder, ActuatorConventionBuilder? conventionBuilder) { - ArgumentGuard.NotNull(routeBuilder); + ArgumentNullException.ThrowIfNull(routeBuilder); IServiceProvider serviceProvider = routeBuilder.ServiceProvider; @@ -62,7 +61,7 @@ public static IEndpointConventionBuilder MapAllActuators(this IEndpointRouteBuil /// public static IRouteBuilder MapAllActuators(this IRouteBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); IServiceProvider serviceProvider = builder.ServiceProvider; diff --git a/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs b/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs index bcbd107baf..85ec2ce514 100644 --- a/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs @@ -33,7 +33,7 @@ public static class ActuatorServiceCollectionExtensions { public static void AddCommonActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddScoped(); @@ -44,7 +44,7 @@ internal static void ConfigureEndpointOptions(this where TOptions : EndpointOptions where TConfigureOptions : class, IConfigureOptionsWithKey { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureOptionsWithChangeTokenSource(); @@ -87,7 +87,7 @@ public static IServiceCollection AddAllActuators(this IServiceCollection service public static IServiceCollection AddAllActuators(this IServiceCollection services, MediaTypeVersion version, Action? buildCorsPolicy) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddSteeltoeCors(buildCorsPolicy); @@ -116,7 +116,7 @@ public static IServiceCollection AddAllActuators(this IServiceCollection service private static void AddSteeltoeCors(this IServiceCollection services, Action? buildCorsPolicy = null) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCors(setup => { @@ -149,7 +149,7 @@ private static void AddSteeltoeCors(this IServiceCollection services, Action public static IEndpointConventionBuilder ActivateActuatorEndpoints(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); var actuatorConventionBuilder = new ActuatorConventionBuilder(); diff --git a/src/Management/src/Endpoint/AllActuatorsStartupFilter.cs b/src/Management/src/Endpoint/AllActuatorsStartupFilter.cs index f06a7c3a8d..be2896ebae 100644 --- a/src/Management/src/Endpoint/AllActuatorsStartupFilter.cs +++ b/src/Management/src/Endpoint/AllActuatorsStartupFilter.cs @@ -21,7 +21,7 @@ public sealed class AllActuatorsStartupFilter : IStartupFilter public AllActuatorsStartupFilter(ActuatorConventionBuilder conventionBuilder) { - ArgumentGuard.NotNull(conventionBuilder); + ArgumentNullException.ThrowIfNull(conventionBuilder); _conventionBuilder = conventionBuilder; } diff --git a/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs b/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs index d17f7d8960..7bc391cb4d 100755 --- a/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs +++ b/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointHandler.cs @@ -27,20 +27,23 @@ public CloudFoundryEndpointHandler(IOptionsMonitor management IOptionsMonitor endpointOptionsMonitor, IEnumerable endpointOptionsCollection, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsCollection); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsCollection); + ArgumentNullException.ThrowIfNull(loggerFactory); + + EndpointOptions[] endpointOptionsArray = endpointOptionsCollection.ToArray(); + ArgumentGuard.ElementsNotNull(endpointOptionsArray); _managementOptionsMonitor = managementOptionsMonitor; _endpointOptionsMonitor = endpointOptionsMonitor; - _endpointOptionsCollection = endpointOptionsCollection.ToList(); + _endpointOptionsCollection = endpointOptionsArray; _hypermediaServiceLogger = loggerFactory.CreateLogger(); } public async Task InvokeAsync(string baseUrl, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(baseUrl); + ArgumentException.ThrowIfNullOrWhiteSpace(baseUrl); var hypermediaService = new HypermediaService(_managementOptionsMonitor, _endpointOptionsMonitor, _endpointOptionsCollection, _hypermediaServiceLogger); Links result = hypermediaService.Invoke(baseUrl); diff --git a/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointMiddleware.cs b/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointMiddleware.cs index c339dbac2f..ab0217f7b5 100644 --- a/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/CloudFoundry/CloudFoundryEndpointMiddleware.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; using Steeltoe.Management.Endpoint.Options; using Steeltoe.Management.Endpoint.Web.Hypermedia; @@ -30,7 +29,7 @@ public CloudFoundryEndpointMiddleware(ICloudFoundryEndpointHandler endpointHandl protected override async Task InvokeEndpointHandlerAsync(HttpContext context, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); _logger.LogDebug("InvokeAsync({Method}, {Path})", context.Request.Method, context.Request.Path.Value); string uri = GetRequestUri(context); diff --git a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs index 2f3c286289..4e14e7bbbb 100644 --- a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs +++ b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityMiddleware.cs @@ -27,15 +27,18 @@ public CloudFoundrySecurityMiddleware(IOptionsMonitor managem IOptionsMonitor endpointOptionsMonitor, IEnumerable endpointOptionsCollection, PermissionsProvider permissionsProvider, ILogger logger, RequestDelegate? next) { - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsCollection); - ArgumentGuard.NotNull(permissionsProvider); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsCollection); + ArgumentNullException.ThrowIfNull(permissionsProvider); + ArgumentNullException.ThrowIfNull(logger); + + EndpointOptions[] endpointOptionsArray = endpointOptionsCollection.ToArray(); + ArgumentGuard.ElementsNotNull(endpointOptionsArray); _managementOptionsMonitor = managementOptionsMonitor; _endpointOptionsMonitor = endpointOptionsMonitor; - _endpointOptionsCollection = endpointOptionsCollection.Where(options => options is not HypermediaEndpointOptions).ToList(); + _endpointOptionsCollection = endpointOptionsArray.Where(options => options is not HypermediaEndpointOptions).ToArray(); _permissionsProvider = permissionsProvider; _logger = logger; _next = next; @@ -43,7 +46,7 @@ public CloudFoundrySecurityMiddleware(IOptionsMonitor managem public async Task InvokeAsync(HttpContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); _logger.LogDebug("InvokeAsync({RequestPath})", context.Request.Path.Value); CloudFoundryEndpointOptions endpointOptions = _endpointOptionsMonitor.CurrentValue; diff --git a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs index 8a1c085335..1186b55df6 100644 --- a/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/CloudFoundry/CloudFoundrySecurityServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Common.Http.HttpClientPooling; namespace Steeltoe.Management.Endpoint.CloudFoundry; @@ -13,7 +12,7 @@ public static class CloudFoundrySecurityServiceCollectionExtensions { public static IServiceCollection AddCloudFoundrySecurity(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddSingleton(); ConfigureHttpClient(services); diff --git a/src/Management/src/Endpoint/CloudFoundry/ConfigureCloudFoundryEndpointOptions.cs b/src/Management/src/Endpoint/CloudFoundry/ConfigureCloudFoundryEndpointOptions.cs index 56e73eef07..83249e6531 100644 --- a/src/Management/src/Endpoint/CloudFoundry/ConfigureCloudFoundryEndpointOptions.cs +++ b/src/Management/src/Endpoint/CloudFoundry/ConfigureCloudFoundryEndpointOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint.CloudFoundry; @@ -21,7 +20,7 @@ public ConfigureCloudFoundryEndpointOptions(IConfiguration configuration) public override void Configure(CloudFoundryEndpointOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); base.Configure(options); options.ApplicationId = Configuration[VcapApplicationIdKey]; diff --git a/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs b/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs index 9efdda688d..d95563a763 100644 --- a/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs +++ b/src/Management/src/Endpoint/CloudFoundry/EndpointApplicationBuilderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.CloudFoundry; @@ -18,7 +17,7 @@ public static class EndpointApplicationBuilderExtensions /// public static void UseCloudFoundrySecurity(this IApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); if (builder.ApplicationServices.GetService() == null) { diff --git a/src/Management/src/Endpoint/CloudFoundry/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/CloudFoundry/EndpointServiceCollectionExtensions.cs index 0a60f60dcd..d01068ff7c 100644 --- a/src/Management/src/Endpoint/CloudFoundry/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/CloudFoundry/EndpointServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.CloudFoundry; @@ -11,7 +10,7 @@ public static class EndpointServiceCollectionExtensions { public static void AddCloudFoundryActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddCloudFoundryActuatorServices(); diff --git a/src/Management/src/Endpoint/CloudFoundry/PermissionsProvider.cs b/src/Management/src/Endpoint/CloudFoundry/PermissionsProvider.cs index 5d05912816..ed61e51d4b 100644 --- a/src/Management/src/Endpoint/CloudFoundry/PermissionsProvider.cs +++ b/src/Management/src/Endpoint/CloudFoundry/PermissionsProvider.cs @@ -34,11 +34,12 @@ internal sealed class PermissionsProvider private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; - public PermissionsProvider(IOptionsMonitor optionsMonitor, IHttpClientFactory httpClientFactory, ILogger logger) + public PermissionsProvider(IOptionsMonitor optionsMonitor, IHttpClientFactory httpClientFactory, + ILogger logger) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(httpClientFactory); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(httpClientFactory); + ArgumentNullException.ThrowIfNull(logger); _optionsMonitor = optionsMonitor; _httpClientFactory = httpClientFactory; @@ -47,8 +48,6 @@ public PermissionsProvider(IOptionsMonitor optionsM public static bool IsCloudFoundryRequest(PathString requestPath) { - ArgumentGuard.NotNull(requestPath); - return requestPath.StartsWithSegments(ConfigureManagementOptions.DefaultCloudFoundryPath); } @@ -94,7 +93,7 @@ public async Task GetPermissionsAsync(string accessToken, Cancel public async Task GetPermissionsAsync(HttpResponseMessage response, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(response); + ArgumentNullException.ThrowIfNull(response); string json = string.Empty; var permissions = Permissions.None; diff --git a/src/Management/src/Endpoint/CloudFoundry/SecurityResult.cs b/src/Management/src/Endpoint/CloudFoundry/SecurityResult.cs index cbb89c1b04..0c2c008122 100644 --- a/src/Management/src/Endpoint/CloudFoundry/SecurityResult.cs +++ b/src/Management/src/Endpoint/CloudFoundry/SecurityResult.cs @@ -4,7 +4,6 @@ using System.Net; using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.CloudFoundry; @@ -28,7 +27,7 @@ public SecurityResult(Permissions level) public SecurityResult(HttpStatusCode code, string message) { - ArgumentGuard.NotNull(message); + ArgumentException.ThrowIfNullOrWhiteSpace(message); Code = code; Message = message; diff --git a/src/Management/src/Endpoint/CloudFoundry/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/CloudFoundry/ServiceCollectionExtensions.cs index 8d70895190..ccbabadc9e 100644 --- a/src/Management/src/Endpoint/CloudFoundry/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/CloudFoundry/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.CloudFoundry; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddCloudFoundryActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.ConfigureEndpointOptions(); diff --git a/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs b/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs index d0e3578393..464152bc4c 100644 --- a/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs +++ b/src/Management/src/Endpoint/ContentNegotiation/ContentNegotiationExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Http.Headers; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.ContentNegotiation; @@ -14,8 +13,8 @@ internal static class ContentNegotiationExtensions { public static void HandleContentNegotiation(this HttpContext context, ILogger logger) { - ArgumentGuard.NotNull(context); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(logger); SetContentType(context.Request.Headers, context.Response.Headers, logger); } @@ -24,7 +23,7 @@ private static void SetContentType(IHeaderDictionary requestHeaders, IHeaderDict MediaTypeVersion version = MediaTypeVersion.V2) { var headers = new RequestHeaders(requestHeaders); - List acceptMediaTypes = headers.Accept.Select(header => header.MediaType.Value!).ToList(); + string[] acceptMediaTypes = headers.Accept.Select(header => header.MediaType.Value!).ToArray(); string contentType = ActuatorMediaTypes.GetContentHeaders(acceptMediaTypes, version); responseHeaders.Append("Content-Type", contentType); diff --git a/src/Management/src/Endpoint/DbMigrations/DbMigrationsEndpointHandler.cs b/src/Management/src/Endpoint/DbMigrations/DbMigrationsEndpointHandler.cs index f9bbf9eee8..4dfe9e8030 100755 --- a/src/Management/src/Endpoint/DbMigrations/DbMigrationsEndpointHandler.cs +++ b/src/Management/src/Endpoint/DbMigrations/DbMigrationsEndpointHandler.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.DbMigrations; @@ -23,10 +22,10 @@ internal sealed class DbMigrationsEndpointHandler : IDbMigrationsEndpointHandler public DbMigrationsEndpointHandler(IOptionsMonitor optionsMonitor, IServiceProvider serviceProvider, IDatabaseMigrationScanner scanner, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(scanner); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(scanner); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _serviceProvider = serviceProvider; @@ -48,7 +47,7 @@ public async Task> InvokeAsync(object // @formatter:wrap_chained_method_calls chop_always // @formatter:wrap_after_property_in_chained_method_calls true - List knownDbContextTypes = _scanner.AssemblyToScan + Type[] knownDbContextTypes = _scanner.AssemblyToScan .GetReferencedAssemblies() .Select(Assembly.Load) .SelectMany(assembly => assembly.DefinedTypes) @@ -56,7 +55,7 @@ public async Task> InvokeAsync(object .Where(type => !type.IsAbstract && type.AsType() != dbContextType && dbContextType.GetTypeInfo() .IsAssignableFrom(type.AsType())) .Select(typeInfo => typeInfo.AsType()) - .ToList(); + .ToArray(); // @formatter:wrap_after_property_in_chained_method_calls restore // @formatter:wrap_chained_method_calls restore @@ -94,9 +93,6 @@ public async Task> InvokeAsync(object private static void AddRange(IList source, IEnumerable items) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(items); - if (source is List list) { list.AddRange(items); diff --git a/src/Management/src/Endpoint/DbMigrations/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/DbMigrations/EndpointServiceCollectionExtensions.cs index b42d1cb047..ce768b793e 100644 --- a/src/Management/src/Endpoint/DbMigrations/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/DbMigrations/EndpointServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.DbMigrations; @@ -17,7 +16,7 @@ public static class EndpointServiceCollectionExtensions /// public static void AddDbMigrationsActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddDbMigrationsActuatorServices(); diff --git a/src/Management/src/Endpoint/DbMigrations/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/DbMigrations/ServiceCollectionExtensions.cs index 2cd41252ca..12813b7e2a 100644 --- a/src/Management/src/Endpoint/DbMigrations/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/DbMigrations/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.DbMigrations; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddDbMigrationsActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); diff --git a/src/Management/src/Endpoint/Diagnostics/DiagnosticsService.cs b/src/Management/src/Endpoint/Diagnostics/DiagnosticsService.cs index 1d02c50e87..c197d22f50 100644 --- a/src/Management/src/Endpoint/Diagnostics/DiagnosticsService.cs +++ b/src/Management/src/Endpoint/Diagnostics/DiagnosticsService.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; namespace Steeltoe.Management.Endpoint.Diagnostics; @@ -16,8 +15,8 @@ internal sealed class DiagnosticsService : IHostedService public DiagnosticsService(IDiagnosticsManager observerManager, ILogger logger) { - ArgumentGuard.NotNull(observerManager); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(observerManager); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; _observerManager = observerManager; diff --git a/src/Management/src/Endpoint/EndpointOptionsExtensions.cs b/src/Management/src/Endpoint/EndpointOptionsExtensions.cs index c9d526b272..aef0793400 100644 --- a/src/Management/src/Endpoint/EndpointOptionsExtensions.cs +++ b/src/Management/src/Endpoint/EndpointOptionsExtensions.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint; @@ -11,8 +10,8 @@ internal static class EndpointOptionsExtensions { public static bool IsEnabled(this EndpointOptions endpointOptions, ManagementOptions managementOptions) { - ArgumentGuard.NotNull(endpointOptions); - ArgumentGuard.NotNull(managementOptions); + ArgumentNullException.ThrowIfNull(endpointOptions); + ArgumentNullException.ThrowIfNull(managementOptions); if (endpointOptions.Enabled != null) { @@ -29,8 +28,8 @@ public static bool IsEnabled(this EndpointOptions endpointOptions, ManagementOpt public static bool IsExposed(this EndpointOptions endpointOptions, ManagementOptions managementOptions) { - ArgumentGuard.NotNull(endpointOptions); - ArgumentGuard.NotNull(managementOptions); + ArgumentNullException.ThrowIfNull(endpointOptions); + ArgumentNullException.ThrowIfNull(managementOptions); if (!string.IsNullOrEmpty(endpointOptions.Id) && managementOptions.Exposure != null) { @@ -52,8 +51,8 @@ public static bool IsExposed(this EndpointOptions endpointOptions, ManagementOpt public static string GetPathMatchPattern(this EndpointOptions endpointOptions, ManagementOptions managementOptions, string? baseRequestPath) { - ArgumentGuard.NotNull(endpointOptions); - ArgumentGuard.NotNull(managementOptions); + ArgumentNullException.ThrowIfNull(endpointOptions); + ArgumentNullException.ThrowIfNull(managementOptions); string? path = baseRequestPath; diff --git a/src/Management/src/Endpoint/Environment/ConfigureEnvironmentEndpointOptions.cs b/src/Management/src/Endpoint/Environment/ConfigureEnvironmentEndpointOptions.cs index a80636f27b..40c351bda7 100644 --- a/src/Management/src/Endpoint/Environment/ConfigureEnvironmentEndpointOptions.cs +++ b/src/Management/src/Endpoint/Environment/ConfigureEnvironmentEndpointOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint.Environment; @@ -29,7 +28,7 @@ public ConfigureEnvironmentEndpointOptions(IConfiguration configuration) public override void Configure(EnvironmentEndpointOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); base.Configure(options); diff --git a/src/Management/src/Endpoint/Environment/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Environment/EndpointServiceCollectionExtensions.cs index 58bfc1c218..8b656cf64d 100644 --- a/src/Management/src/Endpoint/Environment/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Environment/EndpointServiceCollectionExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Environment; @@ -20,7 +19,7 @@ public static class EndpointServiceCollectionExtensions /// public static IServiceCollection AddEnvironmentActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(provider => provider.GetRequiredService()); diff --git a/src/Management/src/Endpoint/Environment/EnvironmentEndpointHandler.cs b/src/Management/src/Endpoint/Environment/EnvironmentEndpointHandler.cs index 035c053948..592fc603b3 100755 --- a/src/Management/src/Endpoint/Environment/EnvironmentEndpointHandler.cs +++ b/src/Management/src/Endpoint/Environment/EnvironmentEndpointHandler.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Configuration; namespace Steeltoe.Management.Endpoint.Environment; @@ -24,10 +23,10 @@ internal sealed class EnvironmentEndpointHandler : IEnvironmentEndpointHandler public EnvironmentEndpointHandler(IOptionsMonitor optionsMonitor, IConfiguration configuration, IHostEnvironment environment, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(environment); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(environment); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _configuration = configuration; @@ -76,7 +75,7 @@ internal IList GetPropertySources() public PropertySourceDescriptor GetPropertySourceDescriptor(IConfigurationProvider provider) { - ArgumentGuard.NotNull(provider); + ArgumentNullException.ThrowIfNull(provider); var properties = new Dictionary(); string sourceName = GetPropertySourceName(provider); @@ -100,7 +99,7 @@ public PropertySourceDescriptor GetPropertySourceDescriptor(IConfigurationProvid public string GetPropertySourceName(IConfigurationProvider provider) { - ArgumentGuard.NotNull(provider); + ArgumentNullException.ThrowIfNull(provider); return provider is FileConfigurationProvider fileProvider ? $"{provider.GetType().Name}: [{fileProvider.Source.Path}]" : provider.GetType().Name; } diff --git a/src/Management/src/Endpoint/Environment/EnvironmentResponse.cs b/src/Management/src/Endpoint/Environment/EnvironmentResponse.cs index cf446e1a95..cadc0f50b8 100755 --- a/src/Management/src/Endpoint/Environment/EnvironmentResponse.cs +++ b/src/Management/src/Endpoint/Environment/EnvironmentResponse.cs @@ -17,8 +17,9 @@ public sealed class EnvironmentResponse public EnvironmentResponse(IList activeProfiles, IList sources) { - ArgumentGuard.NotNull(activeProfiles); - ArgumentGuard.NotNull(sources); + ArgumentNullException.ThrowIfNull(activeProfiles); + ArgumentGuard.ElementsNotNullOrWhiteSpace(activeProfiles); + ArgumentNullException.ThrowIfNull(sources); ActiveProfiles = activeProfiles; PropertySources = sources; diff --git a/src/Management/src/Endpoint/Environment/PropertySourceDescriptor.cs b/src/Management/src/Endpoint/Environment/PropertySourceDescriptor.cs index aa216fdac6..73c5131747 100644 --- a/src/Management/src/Endpoint/Environment/PropertySourceDescriptor.cs +++ b/src/Management/src/Endpoint/Environment/PropertySourceDescriptor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Environment; @@ -17,8 +16,8 @@ public sealed class PropertySourceDescriptor public PropertySourceDescriptor(string name, IDictionary properties) { - ArgumentGuard.NotNullOrEmpty(name); - ArgumentGuard.NotNull(properties); + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentNullException.ThrowIfNull(properties); Name = name; Properties = properties; diff --git a/src/Management/src/Endpoint/Environment/Sanitizer.cs b/src/Management/src/Endpoint/Environment/Sanitizer.cs index 21bbca6367..e55593a96a 100644 --- a/src/Management/src/Endpoint/Environment/Sanitizer.cs +++ b/src/Management/src/Endpoint/Environment/Sanitizer.cs @@ -21,7 +21,8 @@ internal sealed class Sanitizer public Sanitizer(ICollection keysToSanitize) { - ArgumentGuard.NotNull(keysToSanitize); + ArgumentNullException.ThrowIfNull(keysToSanitize); + ArgumentGuard.ElementsNotNullOrEmpty(keysToSanitize); foreach (string key in keysToSanitize) { diff --git a/src/Management/src/Endpoint/Environment/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Environment/ServiceCollectionExtensions.cs index c34d29c96f..c39d80dfde 100644 --- a/src/Management/src/Endpoint/Environment/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Environment/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.Environment; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddEnvironmentActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); diff --git a/src/Management/src/Endpoint/Health/Availability/ApplicationAvailability.cs b/src/Management/src/Endpoint/Health/Availability/ApplicationAvailability.cs index c34bbf9f7c..272bda764c 100644 --- a/src/Management/src/Endpoint/Health/Availability/ApplicationAvailability.cs +++ b/src/Management/src/Endpoint/Health/Availability/ApplicationAvailability.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Health.Availability; @@ -20,7 +19,7 @@ public sealed class ApplicationAvailability public ApplicationAvailability(ILogger logger) { - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; } diff --git a/src/Management/src/Endpoint/Health/Availability/AvailabilityEventArgs.cs b/src/Management/src/Endpoint/Health/Availability/AvailabilityEventArgs.cs index 2e7b99c9a6..11a0681645 100644 --- a/src/Management/src/Endpoint/Health/Availability/AvailabilityEventArgs.cs +++ b/src/Management/src/Endpoint/Health/Availability/AvailabilityEventArgs.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Health.Availability; public sealed class AvailabilityEventArgs : EventArgs @@ -12,7 +10,7 @@ public sealed class AvailabilityEventArgs : EventArgs public AvailabilityEventArgs(AvailabilityState availabilityState) { - ArgumentGuard.NotNull(availabilityState); + ArgumentNullException.ThrowIfNull(availabilityState); NewState = availabilityState; } diff --git a/src/Management/src/Endpoint/Health/Availability/AvailabilityHealthContributor.cs b/src/Management/src/Endpoint/Health/Availability/AvailabilityHealthContributor.cs index 01d5d9519f..46ade3aa38 100644 --- a/src/Management/src/Endpoint/Health/Availability/AvailabilityHealthContributor.cs +++ b/src/Management/src/Endpoint/Health/Availability/AvailabilityHealthContributor.cs @@ -3,22 +3,21 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Management.Endpoint.Health.Availability; public abstract class AvailabilityHealthContributor : IHealthContributor { - private readonly Dictionary _stateMappings; + private readonly IDictionary _stateMappings; private readonly ILogger _logger; public abstract string Id { get; } - protected AvailabilityHealthContributor(Dictionary stateMappings, ILoggerFactory loggerFactory) + protected AvailabilityHealthContributor(IDictionary stateMappings, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(stateMappings); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(stateMappings); + ArgumentNullException.ThrowIfNull(loggerFactory); _stateMappings = stateMappings; _logger = loggerFactory.CreateLogger(); diff --git a/src/Management/src/Endpoint/Health/Availability/AvailabilityState.cs b/src/Management/src/Endpoint/Health/Availability/AvailabilityState.cs index c3ebe05b07..9e7412e5a4 100644 --- a/src/Management/src/Endpoint/Health/Availability/AvailabilityState.cs +++ b/src/Management/src/Endpoint/Health/Availability/AvailabilityState.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Health.Availability; public abstract class AvailabilityState @@ -12,7 +10,7 @@ public abstract class AvailabilityState protected AvailabilityState(string value) { - ArgumentGuard.NotNull(value); + ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } diff --git a/src/Management/src/Endpoint/Health/Availability/LivenessHealthContributor.cs b/src/Management/src/Endpoint/Health/Availability/LivenessHealthContributor.cs index f264ccbafe..c47df690fc 100644 --- a/src/Management/src/Endpoint/Health/Availability/LivenessHealthContributor.cs +++ b/src/Management/src/Endpoint/Health/Availability/LivenessHealthContributor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Management.Endpoint.Health.Availability; @@ -21,7 +20,7 @@ public LivenessHealthContributor(ApplicationAvailability availability, ILoggerFa { LivenessState.Broken, HealthStatus.Down } }, loggerFactory) { - ArgumentGuard.NotNull(availability); + ArgumentNullException.ThrowIfNull(availability); _availability = availability; } diff --git a/src/Management/src/Endpoint/Health/Availability/ReadinessHealthContributor.cs b/src/Management/src/Endpoint/Health/Availability/ReadinessHealthContributor.cs index 82025820d7..75afd3efea 100644 --- a/src/Management/src/Endpoint/Health/Availability/ReadinessHealthContributor.cs +++ b/src/Management/src/Endpoint/Health/Availability/ReadinessHealthContributor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Management.Endpoint.Health.Availability; @@ -21,7 +20,7 @@ public ReadinessHealthContributor(ApplicationAvailability availability, ILoggerF { ReadinessState.RefusingTraffic, HealthStatus.OutOfService } }, loggerFactory) { - ArgumentGuard.NotNull(availability); + ArgumentNullException.ThrowIfNull(availability); _availability = availability; } diff --git a/src/Management/src/Endpoint/Health/ConfigureHealthEndpointOptions.cs b/src/Management/src/Endpoint/Health/ConfigureHealthEndpointOptions.cs index b273383cf7..c34c458321 100644 --- a/src/Management/src/Endpoint/Health/ConfigureHealthEndpointOptions.cs +++ b/src/Management/src/Endpoint/Health/ConfigureHealthEndpointOptions.cs @@ -4,7 +4,6 @@ using System.Security.Claims; using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; using Steeltoe.Management.Endpoint.Security; @@ -21,7 +20,7 @@ public ConfigureHealthEndpointOptions(IConfiguration configuration) public override void Configure(HealthEndpointOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); base.Configure(options); diff --git a/src/Management/src/Endpoint/Health/Contributor/ConfigureDiskSpaceContributorOptions.cs b/src/Management/src/Endpoint/Health/Contributor/ConfigureDiskSpaceContributorOptions.cs index 9ff8ac30c8..e8cfe31c9d 100644 --- a/src/Management/src/Endpoint/Health/Contributor/ConfigureDiskSpaceContributorOptions.cs +++ b/src/Management/src/Endpoint/Health/Contributor/ConfigureDiskSpaceContributorOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint.Health.Contributor; @@ -17,14 +16,14 @@ internal sealed class ConfigureDiskSpaceContributorOptions : IConfigureOptionsWi public ConfigureDiskSpaceContributorOptions(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); _configuration = configuration; } public void Configure(DiskSpaceContributorOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _configuration.GetSection(ManagementInfoPrefix).Bind(options); } diff --git a/src/Management/src/Endpoint/Health/Contributor/DiskSpaceContributor.cs b/src/Management/src/Endpoint/Health/Contributor/DiskSpaceContributor.cs index 58846e941e..cd9b52ea32 100644 --- a/src/Management/src/Endpoint/Health/Contributor/DiskSpaceContributor.cs +++ b/src/Management/src/Endpoint/Health/Contributor/DiskSpaceContributor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.HealthChecks; @@ -17,7 +16,7 @@ internal sealed class DiskSpaceContributor : IHealthContributor public DiskSpaceContributor(IOptionsMonitor optionsMonitor) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); _optionsMonitor = optionsMonitor; } diff --git a/src/Management/src/Endpoint/Health/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Health/EndpointServiceCollectionExtensions.cs index 827ee16bb3..8a26c70c69 100644 --- a/src/Management/src/Endpoint/Health/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Health/EndpointServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; using Steeltoe.Management.Endpoint.Health.Availability; using Steeltoe.Management.Endpoint.Health.Contributor; @@ -24,7 +23,7 @@ public static class EndpointServiceCollectionExtensions /// public static IServiceCollection AddHealthActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddHealthActuatorServices(); @@ -59,7 +58,7 @@ private static void RegisterDefaultHealthContributors(IServiceCollection service public static IServiceCollection AddHealthContributor(this IServiceCollection services) where T : class, IHealthContributor { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddEnumerable(ServiceDescriptor.Scoped()); @@ -80,8 +79,8 @@ public static IServiceCollection AddHealthContributor(this IServiceCollection /// public static IServiceCollection AddHealthContributor(this IServiceCollection services, Type healthContributorType) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(healthContributorType); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(healthContributorType); services.TryAddEnumerable(ServiceDescriptor.Scoped(typeof(IHealthContributor), healthContributorType)); diff --git a/src/Management/src/Endpoint/Health/HealthConverter.cs b/src/Management/src/Endpoint/Health/HealthConverter.cs index 1f9c23647c..a7cfae2aa9 100644 --- a/src/Management/src/Endpoint/Health/HealthConverter.cs +++ b/src/Management/src/Endpoint/Health/HealthConverter.cs @@ -4,7 +4,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -using Steeltoe.Common; using Steeltoe.Common.CasingConventions; using Steeltoe.Common.HealthChecks; @@ -19,7 +18,7 @@ public override HealthEndpointResponse Read(ref Utf8JsonReader reader, Type type public override void Write(Utf8JsonWriter writer, HealthEndpointResponse value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); + ArgumentNullException.ThrowIfNull(writer); writer.WriteStartObject(); writer.WriteString("status", value.Status.ToSnakeCaseString(SnakeCaseStyle.AllCaps)); diff --git a/src/Management/src/Endpoint/Health/HealthConverterV3.cs b/src/Management/src/Endpoint/Health/HealthConverterV3.cs index aa04bf8e07..91e2ea1e36 100644 --- a/src/Management/src/Endpoint/Health/HealthConverterV3.cs +++ b/src/Management/src/Endpoint/Health/HealthConverterV3.cs @@ -4,7 +4,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Health; @@ -17,7 +16,7 @@ public override HealthEndpointResponse Read(ref Utf8JsonReader reader, Type type public override void Write(Utf8JsonWriter writer, HealthEndpointResponse value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); + ArgumentNullException.ThrowIfNull(writer); writer.WriteStartObject(); writer.WriteString("status", value.Status.ToString()); diff --git a/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs b/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs index 1f1a1b16d5..2b64c9d99d 100755 --- a/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs +++ b/src/Management/src/Endpoint/Health/HealthEndpointHandler.cs @@ -16,7 +16,7 @@ internal sealed class HealthEndpointHandler : IHealthEndpointHandler { private readonly IOptionsMonitor _endpointOptionsMonitor; private readonly IHealthAggregator _healthAggregator; - private readonly IList _healthContributors; + private readonly ICollection _healthContributors; private readonly IOptionsMonitor _healthOptionsMonitor; private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; @@ -27,16 +27,19 @@ public HealthEndpointHandler(IOptionsMonitor endpointOpti IEnumerable healthContributors, IOptionsMonitor healthOptionsMonitor, IServiceProvider serviceProvider, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(endpointOptionsMonitor); - ArgumentGuard.NotNull(healthAggregator); - ArgumentGuard.NotNull(healthContributors); - ArgumentGuard.NotNull(healthOptionsMonitor); - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(endpointOptionsMonitor); + ArgumentNullException.ThrowIfNull(healthAggregator); + ArgumentNullException.ThrowIfNull(healthContributors); + ArgumentNullException.ThrowIfNull(healthOptionsMonitor); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(loggerFactory); + + IHealthContributor[] healthContributorArray = healthContributors.ToArray(); + ArgumentGuard.ElementsNotNull(healthContributorArray); _endpointOptionsMonitor = endpointOptionsMonitor; _healthAggregator = healthAggregator; - _healthContributors = healthContributors.ToList(); + _healthContributors = healthContributorArray; _healthOptionsMonitor = healthOptionsMonitor; _serviceProvider = serviceProvider; _logger = loggerFactory.CreateLogger(); @@ -44,7 +47,7 @@ public HealthEndpointHandler(IOptionsMonitor endpointOpti public int GetStatusCode(HealthEndpointResponse response) { - ArgumentGuard.NotNull(response); + ArgumentNullException.ThrowIfNull(response); return response.Status is HealthStatus.Down or HealthStatus.OutOfService ? 503 : 200; } @@ -54,7 +57,7 @@ public async Task InvokeAsync(HealthEndpointRequest heal string groupName = healthRequest.GroupName; HealthEndpointOptions endpointOptions = _endpointOptionsMonitor.CurrentValue; - IList filteredContributors; + ICollection filteredContributors; ICollection healthCheckRegistrations; if (!string.IsNullOrEmpty(groupName) && groupName != endpointOptions.Id) @@ -76,7 +79,7 @@ public async Task InvokeAsync(HealthEndpointRequest heal if (showDetails != ShowDetails.Never && (showDetails != ShowDetails.WhenAuthorized || healthRequest.HasClaim)) { - foreach (string group in endpointOptions.Groups.Select(group => group.Key).ToList()) + foreach (string group in endpointOptions.Groups.Select(group => group.Key)) { response.Groups.Add(group); } @@ -91,10 +94,10 @@ private ICollection GetFilteredHealthCheckServiceOption { if (_endpointOptionsMonitor.CurrentValue.Groups.TryGetValue(requestedGroup, out HealthGroupOptions? groupOptions) && groupOptions.Include != null) { - List includedContributors = groupOptions.Include.Split(',').ToList(); + string[] includedContributors = groupOptions.Include.Split(','); return _healthOptionsMonitor.CurrentValue.Registrations - .Where(registration => includedContributors.Contains(registration.Name, StringComparer.OrdinalIgnoreCase)).ToList(); + .Where(registration => includedContributors.Contains(registration.Name, StringComparer.OrdinalIgnoreCase)).ToArray(); } _logger.LogInformation("Health check requested for a group that is not configured"); @@ -118,14 +121,14 @@ private ICollection GetFilteredHealthCheckServiceOption /// /// If group can't be parsed or is not configured, returns all health contributors. /// - private IList GetFilteredContributors(string requestedGroup) + private ICollection GetFilteredContributors(string requestedGroup) { if (!string.IsNullOrEmpty(requestedGroup)) { if (_endpointOptionsMonitor.CurrentValue.Groups.TryGetValue(requestedGroup, out HealthGroupOptions? groupOptions) && groupOptions.Include != null) { - List includedContributors = groupOptions.Include.Split(',').ToList(); - return _healthContributors.Where(contributor => includedContributors.Contains(contributor.Id, StringComparer.OrdinalIgnoreCase)).ToList(); + string[] includedContributors = groupOptions.Include.Split(','); + return _healthContributors.Where(contributor => includedContributors.Contains(contributor.Id, StringComparer.OrdinalIgnoreCase)).ToArray(); } _logger.LogInformation("Health check requested for a group that is not configured"); diff --git a/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs b/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs index 59c694c660..026ad4d5ab 100644 --- a/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Health/HealthEndpointMiddleware.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; using Steeltoe.Management.Endpoint.Options; using Steeltoe.Management.Endpoint.Security; @@ -23,7 +22,7 @@ public HealthEndpointMiddleware(IHealthEndpointHandler endpointHandler, IOptions IOptionsMonitor managementOptionsMonitor, ILoggerFactory loggerFactory) : base(endpointHandler, managementOptionsMonitor, loggerFactory) { - ArgumentGuard.NotNull(endpointOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsMonitor); _endpointOptionsMonitor = endpointOptionsMonitor; _logger = loggerFactory.CreateLogger(); @@ -52,7 +51,7 @@ protected override async Task InvokeEndpointHandlerAsync /// private string GetRequestedHealthGroup(PathString requestPath) { - string[] requestComponents = requestPath.Value?.Split('/') ?? Array.Empty(); + string[] requestComponents = requestPath.Value?.Split('/') ?? []; if (requestComponents.Length > 0) { diff --git a/src/Management/src/Endpoint/Health/HealthEndpointRequest.cs b/src/Management/src/Endpoint/Health/HealthEndpointRequest.cs index 53ff46dc0a..b7c95a1eee 100644 --- a/src/Management/src/Endpoint/Health/HealthEndpointRequest.cs +++ b/src/Management/src/Endpoint/Health/HealthEndpointRequest.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Health; public sealed class HealthEndpointRequest @@ -13,7 +11,7 @@ public sealed class HealthEndpointRequest public HealthEndpointRequest(string groupName, bool hasClaim) { - ArgumentGuard.NotNull(groupName); + ArgumentNullException.ThrowIfNull(groupName); GroupName = groupName; HasClaim = hasClaim; diff --git a/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs b/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs index 4d6329e8f7..738dee0618 100644 --- a/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs +++ b/src/Management/src/Endpoint/Health/HealthEndpointResponse.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; using Steeltoe.Common.HealthChecks; namespace Steeltoe.Management.Endpoint.Health; @@ -40,7 +39,7 @@ public HealthEndpointResponse() public HealthEndpointResponse(HealthCheckResult result) { - ArgumentGuard.NotNull(result); + ArgumentNullException.ThrowIfNull(result); Status = result.Status; Description = result.Description; diff --git a/src/Management/src/Endpoint/Health/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Health/ServiceCollectionExtensions.cs index 3adb1c53ed..b79ec5f02c 100644 --- a/src/Management/src/Endpoint/Health/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Health/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Health.Contributor; using Steeltoe.Management.Endpoint.Middleware; @@ -26,7 +25,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddHealthActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.ConfigureOptionsWithChangeTokenSource(); diff --git a/src/Management/src/Endpoint/Health/ServiceProviderExtensions.cs b/src/Management/src/Endpoint/Health/ServiceProviderExtensions.cs index 97f7dcc8cd..0cc1adaadf 100644 --- a/src/Management/src/Endpoint/Health/ServiceProviderExtensions.cs +++ b/src/Management/src/Endpoint/Health/ServiceProviderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Health.Availability; namespace Steeltoe.Management.Endpoint.Health; @@ -19,7 +18,7 @@ public static class ServiceProviderExtensions /// public static IServiceProvider InitializeAvailability(this IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceProvider); var availability = serviceProvider.GetService(); diff --git a/src/Management/src/Endpoint/HeapDump/ConfigureHeapDumpEndpointOptions.cs b/src/Management/src/Endpoint/HeapDump/ConfigureHeapDumpEndpointOptions.cs index d015c0c6e7..56b161d960 100644 --- a/src/Management/src/Endpoint/HeapDump/ConfigureHeapDumpEndpointOptions.cs +++ b/src/Management/src/Endpoint/HeapDump/ConfigureHeapDumpEndpointOptions.cs @@ -17,7 +17,7 @@ internal sealed class ConfigureHeapDumpEndpointOptions : ConfigureEndpointOption public ConfigureHeapDumpEndpointOptions(IConfiguration configuration, ILogger logger) : base(configuration, ManagementInfoPrefix, "heapdump") { - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; } diff --git a/src/Management/src/Endpoint/HeapDump/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/HeapDump/EndpointServiceCollectionExtensions.cs index ff3e0c6039..a5f26d6e56 100644 --- a/src/Management/src/Endpoint/HeapDump/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/HeapDump/EndpointServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.HeapDump; @@ -18,7 +17,7 @@ public static class EndpointServiceCollectionExtensions /// public static void AddHeapDumpActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddHeapDumpActuatorServices(); diff --git a/src/Management/src/Endpoint/HeapDump/HeapDumpEndpointHandler.cs b/src/Management/src/Endpoint/HeapDump/HeapDumpEndpointHandler.cs index 2f86e96ad4..fc99515f32 100755 --- a/src/Management/src/Endpoint/HeapDump/HeapDumpEndpointHandler.cs +++ b/src/Management/src/Endpoint/HeapDump/HeapDumpEndpointHandler.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.HeapDump; @@ -18,9 +17,9 @@ internal sealed class HeapDumpEndpointHandler : IHeapDumpEndpointHandler public HeapDumpEndpointHandler(IOptionsMonitor optionsMonitor, HeapDumper heapDumper, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(heapDumper); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(heapDumper); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _heapDumper = heapDumper; diff --git a/src/Management/src/Endpoint/HeapDump/HeapDumper.cs b/src/Management/src/Endpoint/HeapDump/HeapDumper.cs index b76c41f190..09ec177a11 100644 --- a/src/Management/src/Endpoint/HeapDump/HeapDumper.cs +++ b/src/Management/src/Endpoint/HeapDump/HeapDumper.cs @@ -8,7 +8,6 @@ using Microsoft.Diagnostics.Tools.GCDump; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.HeapDump; @@ -25,8 +24,8 @@ public HeapDumper(IOptionsMonitor optionsMonitor, ILogg public HeapDumper(IOptionsMonitor optionsMonitor, string? basePathOverride, ILogger logger) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _optionsMonitor = optionsMonitor; _logger = logger; diff --git a/src/Management/src/Endpoint/HeapDump/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/HeapDump/ServiceCollectionExtensions.cs index b15bcbbfce..8001165ba7 100644 --- a/src/Management/src/Endpoint/HeapDump/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/HeapDump/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.HeapDump; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddHeapDumpActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); diff --git a/src/Management/src/Endpoint/Info/Contributor/BuildInfoContributor.cs b/src/Management/src/Endpoint/Info/Contributor/BuildInfoContributor.cs index bfae1d086a..e4e755f70e 100755 --- a/src/Management/src/Endpoint/Info/Contributor/BuildInfoContributor.cs +++ b/src/Management/src/Endpoint/Info/Contributor/BuildInfoContributor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Reflection; -using Steeltoe.Common; using Steeltoe.Management.Info; namespace Steeltoe.Management.Endpoint.Info.Contributor; @@ -15,7 +14,7 @@ internal sealed class BuildInfoContributor : IInfoContributor public Task ContributeAsync(IInfoBuilder builder, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.WithInfo("applicationVersionInfo", GetImportantDetails(_applicationAssembly)); builder.WithInfo("steeltoeVersionInfo", GetImportantDetails(_steeltoeAssembly)); diff --git a/src/Management/src/Endpoint/Info/Contributor/GitInfoContributor.cs b/src/Management/src/Endpoint/Info/Contributor/GitInfoContributor.cs index d657ff5191..058630d33b 100755 --- a/src/Management/src/Endpoint/Info/Contributor/GitInfoContributor.cs +++ b/src/Management/src/Endpoint/Info/Contributor/GitInfoContributor.cs @@ -5,7 +5,6 @@ using System.Globalization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Management.Info; namespace Steeltoe.Management.Endpoint.Info.Contributor; @@ -28,11 +27,11 @@ public GitInfoContributor(ILogger logger) { } - private GitInfoContributor(string propertiesPath, ILogger logger) + public GitInfoContributor(string propertiesPath, ILogger logger) : base(null) { - ArgumentGuard.NotNull(propertiesPath); - ArgumentGuard.NotNull(logger); + ArgumentException.ThrowIfNullOrWhiteSpace(propertiesPath); + ArgumentNullException.ThrowIfNull(logger); _propertiesPath = propertiesPath; _logger = logger; @@ -40,19 +39,17 @@ private GitInfoContributor(string propertiesPath, ILogger lo public async Task ContributeAsync(IInfoBuilder builder, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); - Configuration = await ReadGitPropertiesAsync(_propertiesPath, cancellationToken); + Configuration = await ReadGitPropertiesAsync(cancellationToken); Contribute(builder, GitSettingsPrefix, true); } - public async Task ReadGitPropertiesAsync(string propertiesPath, CancellationToken cancellationToken) + public async Task ReadGitPropertiesAsync(CancellationToken cancellationToken) { - ArgumentGuard.NotNull(propertiesPath); - - if (File.Exists(propertiesPath)) + if (File.Exists(_propertiesPath)) { - string[] lines = await File.ReadAllLinesAsync(propertiesPath, cancellationToken); + string[] lines = await File.ReadAllLinesAsync(_propertiesPath, cancellationToken); if (lines.Length > 0) { @@ -85,7 +82,7 @@ public async Task ContributeAsync(IInfoBuilder builder, CancellationToken cancel } else { - _logger.LogWarning("Unable to locate GitInfo at {GitInfoLocation}", propertiesPath); + _logger.LogWarning("Unable to locate GitInfo at {GitInfoLocation}", _propertiesPath); } return null; @@ -93,8 +90,8 @@ public async Task ContributeAsync(IInfoBuilder builder, CancellationToken cancel protected override void AddKeyValue(IDictionary dictionary, string key, string value) { - ArgumentGuard.NotNull(dictionary); - ArgumentGuard.NotNull(key); + ArgumentNullException.ThrowIfNull(dictionary); + ArgumentException.ThrowIfNullOrEmpty(key); object valueToInsert = value; diff --git a/src/Management/src/Endpoint/Info/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Info/EndpointServiceCollectionExtensions.cs index 2cdf1c79a5..3aca939f3b 100644 --- a/src/Management/src/Endpoint/Info/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Info/EndpointServiceCollectionExtensions.cs @@ -20,7 +20,7 @@ public static class EndpointServiceCollectionExtensions /// public static void AddInfoActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); @@ -41,8 +41,9 @@ public static void AddInfoActuator(this IServiceCollection services) /// public static void AddInfoActuator(this IServiceCollection services, params IInfoContributor[] contributors) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(contributors); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(contributors); + ArgumentGuard.ElementsNotNull(contributors); AddContributors(services, contributors); services.AddInfoActuator(); diff --git a/src/Management/src/Endpoint/Info/EpochSecondsDateTimeConverter.cs b/src/Management/src/Endpoint/Info/EpochSecondsDateTimeConverter.cs index 82437ba708..fe2ea37d8a 100644 --- a/src/Management/src/Endpoint/Info/EpochSecondsDateTimeConverter.cs +++ b/src/Management/src/Endpoint/Info/EpochSecondsDateTimeConverter.cs @@ -5,7 +5,6 @@ using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Info; @@ -28,7 +27,7 @@ public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, Jso public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); + ArgumentNullException.ThrowIfNull(writer); DateTime utc = value.ToUniversalTime(); long valueToInsert = (utc.Ticks - BaseTime.Ticks) / 10000; diff --git a/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs b/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs index 1d950f2e37..a10bc627c1 100755 --- a/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs +++ b/src/Management/src/Endpoint/Info/InfoEndpointHandler.cs @@ -20,12 +20,15 @@ internal sealed class InfoEndpointHandler : IInfoEndpointHandler public InfoEndpointHandler(IOptionsMonitor optionsMonitor, IEnumerable contributors, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(contributors); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(contributors); + ArgumentNullException.ThrowIfNull(loggerFactory); + + IInfoContributor[] contributorArray = contributors.ToArray(); + ArgumentGuard.ElementsNotNull(contributorArray); _optionsMonitor = optionsMonitor; - _contributors = contributors.ToList(); + _contributors = contributorArray; _logger = loggerFactory.CreateLogger(); } diff --git a/src/Management/src/Endpoint/Info/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Info/ServiceCollectionExtensions.cs index 195f798a44..79c32fd156 100644 --- a/src/Management/src/Endpoint/Info/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Info/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.Info; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddInfoActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); diff --git a/src/Management/src/Endpoint/Loggers/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Loggers/EndpointServiceCollectionExtensions.cs index 14d4b23158..e2ba891898 100644 --- a/src/Management/src/Endpoint/Loggers/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Loggers/EndpointServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Loggers; @@ -17,7 +16,7 @@ public static class EndpointServiceCollectionExtensions /// public static void AddLoggersActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddLoggersActuatorServices(); diff --git a/src/Management/src/Endpoint/Loggers/LoggersEndpointHandler.cs b/src/Management/src/Endpoint/Loggers/LoggersEndpointHandler.cs index c055328ea0..c7be0bd499 100755 --- a/src/Management/src/Endpoint/Loggers/LoggersEndpointHandler.cs +++ b/src/Management/src/Endpoint/Loggers/LoggersEndpointHandler.cs @@ -31,9 +31,9 @@ internal sealed class LoggersEndpointHandler : ILoggersEndpointHandler public LoggersEndpointHandler(IOptionsMonitor optionsMonitor, IDynamicLoggerProvider dynamicLoggerProvider, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(dynamicLoggerProvider); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(dynamicLoggerProvider); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _dynamicLoggerProvider = dynamicLoggerProvider; @@ -42,7 +42,7 @@ public LoggersEndpointHandler(IOptionsMonitor optionsMon public Task InvokeAsync(LoggersRequest request, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); _logger.LogDebug("Invoke({Request})", SecurityUtilities.SanitizeInput(request.ToString())); diff --git a/src/Management/src/Endpoint/Loggers/LoggersRequest.cs b/src/Management/src/Endpoint/Loggers/LoggersRequest.cs index ad7bb4d9aa..70f8b8333d 100644 --- a/src/Management/src/Endpoint/Loggers/LoggersRequest.cs +++ b/src/Management/src/Endpoint/Loggers/LoggersRequest.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Loggers; public sealed class LoggersRequest @@ -39,7 +37,7 @@ public LoggersRequest() /// public LoggersRequest(string name, string? level) { - ArgumentGuard.NotNullOrEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(name); Type = LoggersRequestType.Change; Name = name; diff --git a/src/Management/src/Endpoint/Loggers/LoggersResponse.cs b/src/Management/src/Endpoint/Loggers/LoggersResponse.cs index c6c3800904..0ece114a2d 100644 --- a/src/Management/src/Endpoint/Loggers/LoggersResponse.cs +++ b/src/Management/src/Endpoint/Loggers/LoggersResponse.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Loggers; public sealed class LoggersResponse @@ -13,7 +11,7 @@ public sealed class LoggersResponse public LoggersResponse(IDictionary data, bool hasError) { - ArgumentGuard.NotNull(data); + ArgumentNullException.ThrowIfNull(data); HasError = hasError; Data = data; diff --git a/src/Management/src/Endpoint/Loggers/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Loggers/ServiceCollectionExtensions.cs index efc8e29fce..4126d7bc25 100644 --- a/src/Management/src/Endpoint/Loggers/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Loggers/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.Loggers; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddLoggersActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); diff --git a/src/Management/src/Endpoint/ManagementHostApplicationBuilderExtensions.cs b/src/Management/src/Endpoint/ManagementHostApplicationBuilderExtensions.cs index fa7b11cf12..2ef1f0ef53 100644 --- a/src/Management/src/Endpoint/ManagementHostApplicationBuilderExtensions.cs +++ b/src/Management/src/Endpoint/ManagementHostApplicationBuilderExtensions.cs @@ -24,7 +24,7 @@ public static class ManagementHostApplicationBuilderExtensions /// public static IHostApplicationBuilder AddDbMigrationsActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddDbMigrationsActuator(); @@ -43,7 +43,7 @@ public static IHostApplicationBuilder AddDbMigrationsActuator(this IHostApplicat /// public static IHostApplicationBuilder AddEnvironmentActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddEnvironmentActuator(); @@ -62,7 +62,7 @@ public static IHostApplicationBuilder AddEnvironmentActuator(this IHostApplicati /// public static IHostApplicationBuilder AddHealthActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHealthActuator(); @@ -81,7 +81,7 @@ public static IHostApplicationBuilder AddHealthActuator(this IHostApplicationBui /// public static IHostApplicationBuilder AddHeapDumpActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHeapDumpActuator(); @@ -100,7 +100,7 @@ public static IHostApplicationBuilder AddHeapDumpActuator(this IHostApplicationB /// public static IHostApplicationBuilder AddHypermediaActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHypermediaActuator(); @@ -119,7 +119,7 @@ public static IHostApplicationBuilder AddHypermediaActuator(this IHostApplicatio /// public static IHostApplicationBuilder AddInfoActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddInfoActuator(); @@ -141,8 +141,9 @@ public static IHostApplicationBuilder AddInfoActuator(this IHostApplicationBuild /// public static IHostApplicationBuilder AddInfoActuator(this IHostApplicationBuilder builder, params IInfoContributor[] contributors) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(contributors); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(contributors); + ArgumentGuard.ElementsNotNull(contributors); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddInfoActuator(contributors); @@ -161,7 +162,7 @@ public static IHostApplicationBuilder AddInfoActuator(this IHostApplicationBuild /// public static IHostApplicationBuilder AddLoggersActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddLoggersActuator(); @@ -180,7 +181,7 @@ public static IHostApplicationBuilder AddLoggersActuator(this IHostApplicationBu /// public static IHostApplicationBuilder AddMappingsActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddMappingsActuator(); @@ -199,7 +200,7 @@ public static IHostApplicationBuilder AddMappingsActuator(this IHostApplicationB /// public static IHostApplicationBuilder AddMetricsActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddMetricsActuator(); @@ -218,7 +219,7 @@ public static IHostApplicationBuilder AddMetricsActuator(this IHostApplicationBu /// public static IHostApplicationBuilder AddRefreshActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddRefreshActuator(); @@ -254,7 +255,7 @@ public static IHostApplicationBuilder AddThreadDumpActuator(this IHostApplicatio /// public static IHostApplicationBuilder AddThreadDumpActuator(this IHostApplicationBuilder builder, MediaTypeVersion mediaTypeVersion) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddThreadDumpActuator(mediaTypeVersion); @@ -290,7 +291,7 @@ public static IHostApplicationBuilder AddTraceActuator(this IHostApplicationBuil /// public static IHostApplicationBuilder AddTraceActuator(this IHostApplicationBuilder builder, MediaTypeVersion mediaTypeVersion) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddTraceActuator(mediaTypeVersion); @@ -309,7 +310,7 @@ public static IHostApplicationBuilder AddTraceActuator(this IHostApplicationBuil /// public static IHostApplicationBuilder AddServicesActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddServicesActuator(); @@ -328,7 +329,7 @@ public static IHostApplicationBuilder AddServicesActuator(this IHostApplicationB /// public static IHostApplicationBuilder AddCloudFoundryActuator(this IHostApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddCloudFoundryActuator(); @@ -388,7 +389,7 @@ public static IHostApplicationBuilder AddAllActuators(this IHostApplicationBuild public static IHostApplicationBuilder AddAllActuators(this IHostApplicationBuilder builder, Action? configureEndpoints, MediaTypeVersion mediaTypeVersion, Action? buildCorsPolicy) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddAllActuators(configureEndpoints, mediaTypeVersion, buildCorsPolicy); diff --git a/src/Management/src/Endpoint/ManagementHostBuilderExtensions.cs b/src/Management/src/Endpoint/ManagementHostBuilderExtensions.cs index c7b8c08238..9bf04977e3 100644 --- a/src/Management/src/Endpoint/ManagementHostBuilderExtensions.cs +++ b/src/Management/src/Endpoint/ManagementHostBuilderExtensions.cs @@ -24,7 +24,7 @@ public static class ManagementHostBuilderExtensions /// public static IHostBuilder AddDbMigrationsActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddDbMigrationsActuator(); @@ -43,7 +43,7 @@ public static IHostBuilder AddDbMigrationsActuator(this IHostBuilder builder) /// public static IHostBuilder AddEnvironmentActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddEnvironmentActuator(); @@ -62,7 +62,7 @@ public static IHostBuilder AddEnvironmentActuator(this IHostBuilder builder) /// public static IHostBuilder AddHealthActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHealthActuator(); @@ -81,7 +81,7 @@ public static IHostBuilder AddHealthActuator(this IHostBuilder builder) /// public static IHostBuilder AddHeapDumpActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHeapDumpActuator(); @@ -100,7 +100,7 @@ public static IHostBuilder AddHeapDumpActuator(this IHostBuilder builder) /// public static IHostBuilder AddHypermediaActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHypermediaActuator(); @@ -119,7 +119,7 @@ public static IHostBuilder AddHypermediaActuator(this IHostBuilder builder) /// public static IHostBuilder AddInfoActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddInfoActuator(); @@ -141,8 +141,9 @@ public static IHostBuilder AddInfoActuator(this IHostBuilder builder) /// public static IHostBuilder AddInfoActuator(this IHostBuilder builder, params IInfoContributor[] contributors) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(contributors); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(contributors); + ArgumentGuard.ElementsNotNull(contributors); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddInfoActuator(contributors); @@ -161,7 +162,7 @@ public static IHostBuilder AddInfoActuator(this IHostBuilder builder, params IIn /// public static IHostBuilder AddLoggersActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddLoggersActuator(); @@ -180,7 +181,7 @@ public static IHostBuilder AddLoggersActuator(this IHostBuilder builder) /// public static IHostBuilder AddMappingsActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddMappingsActuator(); @@ -199,7 +200,7 @@ public static IHostBuilder AddMappingsActuator(this IHostBuilder builder) /// public static IHostBuilder AddMetricsActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddMetricsActuator(); @@ -218,7 +219,7 @@ public static IHostBuilder AddMetricsActuator(this IHostBuilder builder) /// public static IHostBuilder AddRefreshActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddRefreshActuator(); @@ -254,7 +255,7 @@ public static IHostBuilder AddThreadDumpActuator(this IHostBuilder builder) /// public static IHostBuilder AddThreadDumpActuator(this IHostBuilder builder, MediaTypeVersion mediaTypeVersion) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddThreadDumpActuator(mediaTypeVersion); @@ -290,7 +291,7 @@ public static IHostBuilder AddTraceActuator(this IHostBuilder builder) /// public static IHostBuilder AddTraceActuator(this IHostBuilder builder, MediaTypeVersion mediaTypeVersion) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddTraceActuator(mediaTypeVersion); @@ -309,7 +310,7 @@ public static IHostBuilder AddTraceActuator(this IHostBuilder builder, MediaType /// public static IHostBuilder AddServicesActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddServicesActuator(); @@ -328,7 +329,7 @@ public static IHostBuilder AddServicesActuator(this IHostBuilder builder) /// public static IHostBuilder AddCloudFoundryActuator(this IHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddCloudFoundryActuator(); @@ -397,7 +398,7 @@ public static IHostBuilder AddAllActuators(this IHostBuilder builder, Action? configureEndpoints, MediaTypeVersion mediaTypeVersion, Action? buildCorsPolicy) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddAllActuators(configureEndpoints, mediaTypeVersion, buildCorsPolicy); diff --git a/src/Management/src/Endpoint/ManagementOptionsExtensions.cs b/src/Management/src/Endpoint/ManagementOptionsExtensions.cs index ae48ce7109..d497039ef6 100644 --- a/src/Management/src/Endpoint/ManagementOptionsExtensions.cs +++ b/src/Management/src/Endpoint/ManagementOptionsExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.AspNetCore.Http; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint; @@ -12,8 +11,8 @@ internal static class ManagementOptionsExtensions { public static string? GetBaseRequestPath(this ManagementOptions managementOptions, HttpRequest httpRequest) { - ArgumentGuard.NotNull(managementOptions); - ArgumentGuard.NotNull(httpRequest); + ArgumentNullException.ThrowIfNull(managementOptions); + ArgumentNullException.ThrowIfNull(httpRequest); return httpRequest.Path.StartsWithSegments(ConfigureManagementOptions.DefaultCloudFoundryPath) ? ConfigureManagementOptions.DefaultCloudFoundryPath diff --git a/src/Management/src/Endpoint/ManagementPort/ManagementPortMiddleware.cs b/src/Management/src/Endpoint/ManagementPort/ManagementPortMiddleware.cs index 7fe088357b..f67f5ccabf 100644 --- a/src/Management/src/Endpoint/ManagementPort/ManagementPortMiddleware.cs +++ b/src/Management/src/Endpoint/ManagementPort/ManagementPortMiddleware.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint.ManagementPort; @@ -20,8 +19,8 @@ internal sealed class ManagementPortMiddleware public ManagementPortMiddleware(IOptionsMonitor managementOptionsMonitor, RequestDelegate? next, ILogger logger) { - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _managementOptionsMonitor = managementOptionsMonitor; _next = next; @@ -30,7 +29,7 @@ public ManagementPortMiddleware(IOptionsMonitor managementOpt public async Task InvokeAsync(HttpContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); ManagementOptions managementOptions = _managementOptionsMonitor.CurrentValue; _logger.LogDebug("InvokeAsync({RequestPath}), OptionsPath: {OptionsPath}", context.Request.Path.Value, managementOptions.Path); diff --git a/src/Management/src/Endpoint/ManagementPort/ManagementPortStartupFilter.cs b/src/Management/src/Endpoint/ManagementPort/ManagementPortStartupFilter.cs index a081d84551..dde5fc56b8 100644 --- a/src/Management/src/Endpoint/ManagementPort/ManagementPortStartupFilter.cs +++ b/src/Management/src/Endpoint/ManagementPort/ManagementPortStartupFilter.cs @@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.ManagementPort; @@ -30,14 +29,14 @@ internal sealed class ManagementPortStartupFilter : IStartupFilter public ManagementPortStartupFilter(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); _configuration = configuration; } public Action Configure(Action next) { - ArgumentGuard.NotNull(next); + ArgumentNullException.ThrowIfNull(next); return applicationBuilder => { diff --git a/src/Management/src/Endpoint/ManagementWebHostBuilderExtensions.cs b/src/Management/src/Endpoint/ManagementWebHostBuilderExtensions.cs index 56d24a78df..4c0666a50f 100755 --- a/src/Management/src/Endpoint/ManagementWebHostBuilderExtensions.cs +++ b/src/Management/src/Endpoint/ManagementWebHostBuilderExtensions.cs @@ -24,7 +24,7 @@ public static class ManagementWebHostBuilderExtensions /// public static IWebHostBuilder AddDbMigrationsActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddDbMigrationsActuator(); @@ -43,7 +43,7 @@ public static IWebHostBuilder AddDbMigrationsActuator(this IWebHostBuilder build /// public static IWebHostBuilder AddEnvironmentActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddEnvironmentActuator(); @@ -62,7 +62,7 @@ public static IWebHostBuilder AddEnvironmentActuator(this IWebHostBuilder builde /// public static IWebHostBuilder AddHealthActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHealthActuator(); @@ -81,7 +81,7 @@ public static IWebHostBuilder AddHealthActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddHeapDumpActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHeapDumpActuator(); @@ -100,7 +100,7 @@ public static IWebHostBuilder AddHeapDumpActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddHypermediaActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddHypermediaActuator(); @@ -119,7 +119,7 @@ public static IWebHostBuilder AddHypermediaActuator(this IWebHostBuilder builder /// public static IWebHostBuilder AddInfoActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddInfoActuator(); @@ -141,8 +141,9 @@ public static IWebHostBuilder AddInfoActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddInfoActuator(this IWebHostBuilder builder, params IInfoContributor[] contributors) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(contributors); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(contributors); + ArgumentGuard.ElementsNotNull(contributors); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddInfoActuator(contributors); @@ -161,7 +162,7 @@ public static IWebHostBuilder AddInfoActuator(this IWebHostBuilder builder, para /// public static IWebHostBuilder AddLoggersActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddLoggersActuator(); @@ -180,7 +181,7 @@ public static IWebHostBuilder AddLoggersActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddMappingsActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddMappingsActuator(); @@ -199,7 +200,7 @@ public static IWebHostBuilder AddMappingsActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddMetricsActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddMetricsActuator(); @@ -218,7 +219,7 @@ public static IWebHostBuilder AddMetricsActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddRefreshActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddRefreshActuator(); @@ -254,7 +255,7 @@ public static IWebHostBuilder AddThreadDumpActuator(this IWebHostBuilder builder /// public static IWebHostBuilder AddThreadDumpActuator(this IWebHostBuilder builder, MediaTypeVersion mediaTypeVersion) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddThreadDumpActuator(mediaTypeVersion); @@ -290,7 +291,7 @@ public static IWebHostBuilder AddTraceActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddTraceActuator(this IWebHostBuilder builder, MediaTypeVersion mediaTypeVersion) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddTraceActuator(mediaTypeVersion); @@ -309,7 +310,7 @@ public static IWebHostBuilder AddTraceActuator(this IWebHostBuilder builder, Med /// public static IWebHostBuilder AddServicesActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddServicesActuator(); @@ -328,7 +329,7 @@ public static IWebHostBuilder AddServicesActuator(this IWebHostBuilder builder) /// public static IWebHostBuilder AddCloudFoundryActuator(this IWebHostBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddCloudFoundryActuator(); @@ -388,7 +389,7 @@ public static IWebHostBuilder AddAllActuators(this IWebHostBuilder builder, Acti public static IWebHostBuilder AddAllActuators(this IWebHostBuilder builder, Action? configureEndpoints, MediaTypeVersion mediaTypeVersion, Action? buildCorsPolicy) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); wrapper.AddAllActuators(configureEndpoints, mediaTypeVersion, buildCorsPolicy); diff --git a/src/Management/src/Endpoint/Metrics/ConfigureMetricsObserverOptions.cs b/src/Management/src/Endpoint/Metrics/ConfigureMetricsObserverOptions.cs index 4250b378f5..2777b10db4 100644 --- a/src/Management/src/Endpoint/Metrics/ConfigureMetricsObserverOptions.cs +++ b/src/Management/src/Endpoint/Metrics/ConfigureMetricsObserverOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; using Steeltoe.Management.Endpoint.Options; @@ -23,14 +22,14 @@ internal sealed class ConfigureMetricsObserverOptions : IConfigureOptionsWithKey public ConfigureMetricsObserverOptions(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); _configuration = configuration; } public void Configure(MetricsObserverOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _configuration.GetSection(ManagementMetricsPrefix).Bind(options); diff --git a/src/Management/src/Endpoint/Metrics/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Metrics/EndpointServiceCollectionExtensions.cs index ec7e0d4103..9b934705cc 100644 --- a/src/Management/src/Endpoint/Metrics/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Metrics/EndpointServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using System.Diagnostics.Tracing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; using Steeltoe.Management.Endpoint.Diagnostics; using Steeltoe.Management.Endpoint.Metrics.Observer; @@ -16,7 +15,7 @@ public static class EndpointServiceCollectionExtensions { public static void AddMetricsActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); services.AddHostedService(); @@ -29,7 +28,7 @@ public static void AddMetricsActuator(this IServiceCollection services) public static void AddMetricsObservers(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureOptionsWithChangeTokenSource(); services.TryAddEnumerable(ServiceDescriptor.Singleton()); diff --git a/src/Management/src/Endpoint/Metrics/MetricCollectionHostedService.cs b/src/Management/src/Endpoint/Metrics/MetricCollectionHostedService.cs index 64b925d005..43fcea7c30 100644 --- a/src/Management/src/Endpoint/Metrics/MetricCollectionHostedService.cs +++ b/src/Management/src/Endpoint/Metrics/MetricCollectionHostedService.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Hosting; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Metrics.SystemDiagnosticsMetrics; namespace Steeltoe.Management.Endpoint.Metrics; @@ -14,7 +13,7 @@ internal sealed class MetricCollectionHostedService : IHostedService public MetricCollectionHostedService(AggregationManager aggregationManager) { - ArgumentGuard.NotNull(aggregationManager); + ArgumentNullException.ThrowIfNull(aggregationManager); _aggregationManager = aggregationManager; } diff --git a/src/Management/src/Endpoint/Metrics/MetricLabelExtensions.cs b/src/Management/src/Endpoint/Metrics/MetricLabelExtensions.cs index 05747c3e26..091295f5df 100644 --- a/src/Management/src/Endpoint/Metrics/MetricLabelExtensions.cs +++ b/src/Management/src/Endpoint/Metrics/MetricLabelExtensions.cs @@ -2,15 +2,13 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Metrics; internal static class MetricLabelExtensions { public static ReadOnlySpan> AsReadonlySpan(this IDictionary keyValuePairs) { - ArgumentGuard.NotNull(keyValuePairs); + ArgumentNullException.ThrowIfNull(keyValuePairs); return new ReadOnlySpan>(keyValuePairs.ToArray()); } diff --git a/src/Management/src/Endpoint/Metrics/MetricTag.cs b/src/Management/src/Endpoint/Metrics/MetricTag.cs index 4f6c3a7644..008d38ff7e 100644 --- a/src/Management/src/Endpoint/Metrics/MetricTag.cs +++ b/src/Management/src/Endpoint/Metrics/MetricTag.cs @@ -17,8 +17,9 @@ public sealed class MetricTag public MetricTag(string tag, ISet values) { - ArgumentGuard.NotNull(tag); - ArgumentGuard.NotNull(values); + ArgumentException.ThrowIfNullOrEmpty(tag); + ArgumentNullException.ThrowIfNull(values); + ArgumentGuard.ElementsNotNull(values); Tag = tag; Values = values; diff --git a/src/Management/src/Endpoint/Metrics/MetricsEndpointHandler.cs b/src/Management/src/Endpoint/Metrics/MetricsEndpointHandler.cs index 9aa879da8c..b516c4ce96 100755 --- a/src/Management/src/Endpoint/Metrics/MetricsEndpointHandler.cs +++ b/src/Management/src/Endpoint/Metrics/MetricsEndpointHandler.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Metrics; @@ -18,9 +17,9 @@ internal sealed class MetricsEndpointHandler : IMetricsEndpointHandler public MetricsEndpointHandler(IOptionsMonitor optionsMonitor, MetricsExporter exporter, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(exporter); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(exporter); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _exporter = exporter; @@ -65,7 +64,7 @@ internal IList GetMetricSamplesByTags(MetricsCollection - tags.All(tag => sample.Tags != null && sample.Tags.Any(sampleTag => tag.Key == sampleTag.Key && tag.Value == sampleTag.Value))).ToList(); + tags.All(tag => sample.Tags != null && sample.Tags.Any(sampleTag => tag.Key == sampleTag.Key && tag.Value == sampleTag.Value))).ToArray(); } static MetricSample SumAggregator(MetricSample current, MetricSample next) @@ -80,46 +79,46 @@ static MetricSample MaxAggregator(MetricSample current, MetricSample next) try { - List rateSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Rate).ToList(); + MetricSample[] rateSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Rate).ToArray(); - if (rateSamples.Any()) + if (rateSamples.Length > 0) { MetricSample sample = rateSamples.Aggregate(SumAggregator); - sampleList.Add(new MetricSample(MetricStatistic.Rate, sample.Value / rateSamples.Count, sample.Tags)); + sampleList.Add(new MetricSample(MetricStatistic.Rate, sample.Value / rateSamples.Length, sample.Tags)); } - List valueSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Value).ToList(); + MetricSample[] valueSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Value).ToArray(); - if (valueSamples.Any()) + if (valueSamples.Length > 0) { MetricSample sample = valueSamples.Aggregate(SumAggregator); - sampleList.Add(new MetricSample(MetricStatistic.Value, sample.Value / valueSamples.Count, sample.Tags)); + sampleList.Add(new MetricSample(MetricStatistic.Value, sample.Value / valueSamples.Length, sample.Tags)); } - List totalSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Total).ToList(); + MetricSample[] totalSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Total).ToArray(); - if (totalSamples.Any()) + if (totalSamples.Length > 0) { sampleList.Add(totalSamples.Aggregate(SumAggregator)); } - List totalTimeSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.TotalTime).ToList(); + MetricSample[] totalTimeSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.TotalTime).ToArray(); - if (totalTimeSamples.Any()) + if (totalTimeSamples.Length > 0) { sampleList.Add(totalTimeSamples.Aggregate(SumAggregator)); } - List countSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Count).ToList(); + MetricSample[] countSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Count).ToArray(); - if (countSamples.Any()) + if (countSamples.Length > 0) { sampleList.Add(countSamples.Aggregate(SumAggregator)); } - List maxSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Max).ToList(); + MetricSample[] maxSamples = filtered.Where(sample => sample.Statistic == MetricStatistic.Max).ToArray(); - if (maxSamples.Any()) + if (maxSamples.Length > 0) { MetricSample sample = maxSamples.Aggregate(MaxAggregator); sampleList.Add(new MetricSample(MetricStatistic.Max, sample.Value, sample.Tags)); diff --git a/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs b/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs index 8e5e9e2303..f26aaf03e0 100644 --- a/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Metrics/MetricsEndpointMiddleware.cs @@ -92,10 +92,7 @@ internal IList> ParseTags(IQueryCollection query) { if (tag != null) { - string[] segments = tag.Split(new[] - { - ':' - }, 2); + string[] segments = tag.Split([':'], 2); if (segments.Length == 2) { diff --git a/src/Management/src/Endpoint/Metrics/MetricsExporter.cs b/src/Management/src/Endpoint/Metrics/MetricsExporter.cs index 58181147ce..617d2df666 100644 --- a/src/Management/src/Endpoint/Metrics/MetricsExporter.cs +++ b/src/Management/src/Endpoint/Metrics/MetricsExporter.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics.Metrics; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Metrics.SystemDiagnosticsMetrics; namespace Steeltoe.Management.Endpoint.Metrics; @@ -32,14 +31,14 @@ internal sealed class MetricsExporter /// public MetricsExporter(MetricsExporterOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _cacheDurationMilliseconds = options.CacheDurationMilliseconds; } public void SetCollect(Action collect) { - ArgumentGuard.NotNull(collect); + ArgumentNullException.ThrowIfNull(collect); _collect = collect; } @@ -69,8 +68,8 @@ public void SetCollect(Action collect) internal void AddMetrics(Instrument instrument, LabeledAggregationStatistics stats) { - ArgumentGuard.NotNull(instrument); - ArgumentGuard.NotNull(stats); + ArgumentNullException.ThrowIfNull(instrument); + ArgumentNullException.ThrowIfNull(stats); UpdateAvailableTags(_availableTags, instrument.Name, stats.Labels); diff --git a/src/Management/src/Endpoint/Metrics/MetricsRequest.cs b/src/Management/src/Endpoint/Metrics/MetricsRequest.cs index e29f1795cb..48af2ad4fb 100644 --- a/src/Management/src/Endpoint/Metrics/MetricsRequest.cs +++ b/src/Management/src/Endpoint/Metrics/MetricsRequest.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Metrics; public sealed class MetricsRequest @@ -14,8 +12,8 @@ public sealed class MetricsRequest public MetricsRequest(string metricName, IList> tags) { - ArgumentGuard.NotNull(metricName); - ArgumentGuard.NotNull(tags); + ArgumentException.ThrowIfNullOrEmpty(metricName); + ArgumentNullException.ThrowIfNull(tags); MetricName = metricName; Tags = tags; diff --git a/src/Management/src/Endpoint/Metrics/MetricsResponse.cs b/src/Management/src/Endpoint/Metrics/MetricsResponse.cs index b8706fedb4..84281faf65 100644 --- a/src/Management/src/Endpoint/Metrics/MetricsResponse.cs +++ b/src/Management/src/Endpoint/Metrics/MetricsResponse.cs @@ -27,16 +27,19 @@ public sealed class MetricsResponse public MetricsResponse(ISet names) { - ArgumentGuard.NotNull(names); + ArgumentNullException.ThrowIfNull(names); + ArgumentGuard.ElementsNotNullOrEmpty(names); Names = names; } public MetricsResponse(string name, IList measurements, IList availableTags) { - ArgumentGuard.NotNull(name); - ArgumentGuard.NotNull(measurements); - ArgumentGuard.NotNull(availableTags); + ArgumentException.ThrowIfNullOrEmpty(name); + ArgumentNullException.ThrowIfNull(measurements); + ArgumentGuard.ElementsNotNull(measurements); + ArgumentNullException.ThrowIfNull(availableTags); + ArgumentGuard.ElementsNotNull(availableTags); Name = name; Measurements = measurements; diff --git a/src/Management/src/Endpoint/Metrics/Observer/AspNetCoreHostingObserver.cs b/src/Management/src/Endpoint/Metrics/Observer/AspNetCoreHostingObserver.cs index f97eb19a8a..048bfa2423 100644 --- a/src/Management/src/Endpoint/Metrics/Observer/AspNetCoreHostingObserver.cs +++ b/src/Management/src/Endpoint/Metrics/Observer/AspNetCoreHostingObserver.cs @@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; namespace Steeltoe.Management.Endpoint.Metrics.Observer; @@ -32,7 +31,7 @@ internal sealed class AspNetCoreHostingObserver : MetricsObserver public AspNetCoreHostingObserver(IOptionsMonitor optionsMonitor, ILoggerFactory loggerFactory) : base(DefaultObserverName, DiagnosticName, loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); string? ingressIgnorePattern = optionsMonitor.CurrentValue.IngressIgnorePattern; @@ -79,9 +78,6 @@ public override void ProcessEvent(string eventName, object? value) private void HandleStopEvent(Activity current, HttpContext context) { - ArgumentGuard.NotNull(current); - ArgumentGuard.NotNull(context); - if (ShouldIgnoreRequest(context.Request.Path)) { _logger.LogDebug("HandleStopEvent: Ignoring path: {Path}", context.Request.Path); @@ -98,7 +94,7 @@ private void HandleStopEvent(Activity current, HttpContext context) internal IDictionary GetLabelSets(HttpContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); string uri = context.Request.Path.ToString(); string statusCode = context.Response.StatusCode.ToString(CultureInfo.InvariantCulture); diff --git a/src/Management/src/Endpoint/Metrics/Observer/ClrRuntimeObserver.cs b/src/Management/src/Endpoint/Metrics/Observer/ClrRuntimeObserver.cs index b643c9e3d6..03e0d7f341 100644 --- a/src/Management/src/Endpoint/Metrics/Observer/ClrRuntimeObserver.cs +++ b/src/Management/src/Endpoint/Metrics/Observer/ClrRuntimeObserver.cs @@ -5,7 +5,6 @@ using System.Diagnostics; using System.Diagnostics.Metrics; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; namespace Steeltoe.Management.Endpoint.Metrics.Observer; @@ -35,7 +34,7 @@ internal sealed class ClrRuntimeObserver : IRuntimeDiagnosticSource public ClrRuntimeObserver(IOptionsMonitor options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _options = options; } diff --git a/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs b/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs index 270bb8ca8f..99ad65b340 100644 --- a/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs +++ b/src/Management/src/Endpoint/Metrics/Observer/EventCounterListener.cs @@ -8,7 +8,6 @@ using System.Globalization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; namespace Steeltoe.Management.Endpoint.Metrics.Observer; @@ -33,8 +32,8 @@ internal sealed class EventCounterListener : EventListener public EventCounterListener(IOptionsMonitor optionsMonitor, ILogger logger) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _optionsMonitor = optionsMonitor; _logger = logger; @@ -61,7 +60,7 @@ public EventCounterListener(IOptionsMonitor optionsMonit /// protected override void OnEventWritten(EventWrittenEventArgs eventData) { - ArgumentGuard.NotNull(eventData); + ArgumentNullException.ThrowIfNull(eventData); if (!_isInitialized) { @@ -89,7 +88,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) protected override void OnEventSourceCreated(EventSource eventSource) { - ArgumentGuard.NotNull(eventSource); + ArgumentNullException.ThrowIfNull(eventSource); if (EventSourceName.Equals(eventSource.Name, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Management/src/Endpoint/Metrics/Observer/HttpClientCoreObserver.cs b/src/Management/src/Endpoint/Metrics/Observer/HttpClientCoreObserver.cs index 8deb7e6ed1..63bafde6d8 100644 --- a/src/Management/src/Endpoint/Metrics/Observer/HttpClientCoreObserver.cs +++ b/src/Management/src/Endpoint/Metrics/Observer/HttpClientCoreObserver.cs @@ -31,7 +31,7 @@ internal sealed class HttpClientCoreObserver : MetricsObserver public HttpClientCoreObserver(IOptionsMonitor optionsMonitor, ILoggerFactory loggerFactory) : base(DefaultObserverName, DiagnosticName, loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); string? egressIgnorePattern = optionsMonitor.CurrentValue.EgressIgnorePattern; diff --git a/src/Management/src/Endpoint/Metrics/Observer/HttpClientDesktopObserver.cs b/src/Management/src/Endpoint/Metrics/Observer/HttpClientDesktopObserver.cs index 6c4bd4e8a9..9543d122f8 100644 --- a/src/Management/src/Endpoint/Metrics/Observer/HttpClientDesktopObserver.cs +++ b/src/Management/src/Endpoint/Metrics/Observer/HttpClientDesktopObserver.cs @@ -32,7 +32,7 @@ internal sealed class HttpClientDesktopObserver : MetricsObserver public HttpClientDesktopObserver(IOptionsMonitor optionsMonitor, ILoggerFactory loggerFactory) : base(DefaultObserverName, DiagnosticName, loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); string? egressIgnorePattern = optionsMonitor.CurrentValue.EgressIgnorePattern; diff --git a/src/Management/src/Endpoint/Metrics/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Metrics/ServiceCollectionExtensions.cs index f36f30afe9..662c3783bc 100644 --- a/src/Management/src/Endpoint/Metrics/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Metrics/ServiceCollectionExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Metrics.SystemDiagnosticsMetrics; using Steeltoe.Management.Endpoint.Middleware; @@ -28,7 +27,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddMetricsActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); @@ -61,7 +60,7 @@ public static IServiceCollection AddMetricsActuatorServices(this IServiceCollect public static IServiceCollection AddSteeltoeCollector(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); return services.AddSingleton(provider => { diff --git a/src/Management/src/Endpoint/Middleware/EndpointMiddleware.cs b/src/Management/src/Endpoint/Middleware/EndpointMiddleware.cs index ffa1962054..581dd40338 100644 --- a/src/Management/src/Endpoint/Middleware/EndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Middleware/EndpointMiddleware.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.ContentNegotiation; using Steeltoe.Management.Endpoint.Options; @@ -25,9 +24,9 @@ public abstract class EndpointMiddleware : IEndpointMiddlewa protected EndpointMiddleware(IEndpointHandler endpointHandler, IOptionsMonitor managementOptionsMonitor, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(endpointHandler); - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(endpointHandler); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(loggerFactory); EndpointHandler = endpointHandler; ManagementOptionsMonitor = managementOptionsMonitor; @@ -36,8 +35,6 @@ protected EndpointMiddleware(IEndpointHandler endpointHandle public virtual bool ShouldInvoke(PathString requestPath) { - ArgumentGuard.NotNull(requestPath); - ManagementOptions managementOptions = ManagementOptionsMonitor.CurrentValue; bool isEnabled = EndpointOptions.IsEnabled(managementOptions); bool isExposed = EndpointOptions.IsExposed(managementOptions); @@ -55,7 +52,7 @@ public virtual bool ShouldInvoke(PathString requestPath) public async Task InvokeAsync(HttpContext context, RequestDelegate? next) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); if (ShouldInvoke(context.Request.Path)) { @@ -73,7 +70,7 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate? next) protected virtual async Task WriteResponseAsync(TResult result, HttpContext context, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); context.HandleContentNegotiation(_logger); diff --git a/src/Management/src/Endpoint/Options/ConfigureEndpointOptions.cs b/src/Management/src/Endpoint/Options/ConfigureEndpointOptions.cs index 768f829f33..f754b489f9 100644 --- a/src/Management/src/Endpoint/Options/ConfigureEndpointOptions.cs +++ b/src/Management/src/Endpoint/Options/ConfigureEndpointOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Options; @@ -19,9 +18,9 @@ internal abstract class ConfigureEndpointOptions : IConfigureOptionsWithKey(); - options.Exclude = GetListFromConfigurationCsvString(secondSection, "exclude") ?? new List(); + options.Include = GetListFromConfigurationCsvString(secondSection, "include") ?? []; + options.Exclude = GetListFromConfigurationCsvString(secondSection, "exclude") ?? []; } if (options.Include.Count == 0 && options.Exclude.Count == 0) diff --git a/src/Management/src/Endpoint/PublicAPI.Unshipped.txt b/src/Management/src/Endpoint/PublicAPI.Unshipped.txt index 41daaf1826..b86aa707c0 100755 --- a/src/Management/src/Endpoint/PublicAPI.Unshipped.txt +++ b/src/Management/src/Endpoint/PublicAPI.Unshipped.txt @@ -201,7 +201,7 @@ Steeltoe.Management.Endpoint.Health.Availability.AvailabilityEventArgs Steeltoe.Management.Endpoint.Health.Availability.AvailabilityEventArgs.AvailabilityEventArgs(Steeltoe.Management.Endpoint.Health.Availability.AvailabilityState! availabilityState) -> void Steeltoe.Management.Endpoint.Health.Availability.AvailabilityEventArgs.NewState.get -> Steeltoe.Management.Endpoint.Health.Availability.AvailabilityState! Steeltoe.Management.Endpoint.Health.Availability.AvailabilityHealthContributor -Steeltoe.Management.Endpoint.Health.Availability.AvailabilityHealthContributor.AvailabilityHealthContributor(System.Collections.Generic.Dictionary! stateMappings, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void +Steeltoe.Management.Endpoint.Health.Availability.AvailabilityHealthContributor.AvailabilityHealthContributor(System.Collections.Generic.IDictionary! stateMappings, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void Steeltoe.Management.Endpoint.Health.Availability.AvailabilityHealthContributor.CheckHealthAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! Steeltoe.Management.Endpoint.Health.Availability.AvailabilityState Steeltoe.Management.Endpoint.Health.Availability.AvailabilityState.AvailabilityState(string! value) -> void diff --git a/src/Management/src/Endpoint/Refresh/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Refresh/EndpointServiceCollectionExtensions.cs index f8d96454fb..18417b04fd 100644 --- a/src/Management/src/Endpoint/Refresh/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Refresh/EndpointServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Refresh; @@ -17,7 +16,7 @@ public static class EndpointServiceCollectionExtensions /// public static void AddRefreshActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddRefreshActuatorServices(); diff --git a/src/Management/src/Endpoint/Refresh/RefreshEndpointHandler.cs b/src/Management/src/Endpoint/Refresh/RefreshEndpointHandler.cs index a51efb3c49..56d5e464e6 100755 --- a/src/Management/src/Endpoint/Refresh/RefreshEndpointHandler.cs +++ b/src/Management/src/Endpoint/Refresh/RefreshEndpointHandler.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Refresh; @@ -19,9 +18,9 @@ internal sealed class RefreshEndpointHandler : IRefreshEndpointHandler public RefreshEndpointHandler(IOptionsMonitor optionsMonitor, IConfiguration configuration, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _configuration = configuration; diff --git a/src/Management/src/Endpoint/Refresh/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Refresh/ServiceCollectionExtensions.cs index e800ffce6c..1b789aeeda 100644 --- a/src/Management/src/Endpoint/Refresh/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Refresh/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.Refresh; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddRefreshActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); diff --git a/src/Management/src/Endpoint/RouteMappings/AspNetCoreRouteDetails.cs b/src/Management/src/Endpoint/RouteMappings/AspNetCoreRouteDetails.cs index 89ce816b39..957f7a3f46 100755 --- a/src/Management/src/Endpoint/RouteMappings/AspNetCoreRouteDetails.cs +++ b/src/Management/src/Endpoint/RouteMappings/AspNetCoreRouteDetails.cs @@ -18,12 +18,17 @@ public sealed class AspNetCoreRouteDetails public AspNetCoreRouteDetails(string routeTemplate, IList httpMethods, IList consumes, IList produces, IList headers, IList @params) { - ArgumentGuard.NotNull(routeTemplate); - ArgumentGuard.NotNull(httpMethods); - ArgumentGuard.NotNull(consumes); - ArgumentGuard.NotNull(produces); - ArgumentGuard.NotNull(headers); - ArgumentGuard.NotNull(@params); + ArgumentException.ThrowIfNullOrEmpty(routeTemplate); + ArgumentNullException.ThrowIfNull(httpMethods); + ArgumentGuard.ElementsNotNullOrWhiteSpace(httpMethods); + ArgumentNullException.ThrowIfNull(consumes); + ArgumentGuard.ElementsNotNullOrWhiteSpace(consumes); + ArgumentNullException.ThrowIfNull(produces); + ArgumentGuard.ElementsNotNullOrWhiteSpace(produces); + ArgumentNullException.ThrowIfNull(headers); + ArgumentGuard.ElementsNotNullOrWhiteSpace(headers); + ArgumentNullException.ThrowIfNull(@params); + ArgumentGuard.ElementsNotNullOrWhiteSpace(@params); RouteTemplate = routeTemplate; HttpMethods = httpMethods; diff --git a/src/Management/src/Endpoint/RouteMappings/ContextMappings.cs b/src/Management/src/Endpoint/RouteMappings/ContextMappings.cs index 977060b09c..f40f6e836f 100755 --- a/src/Management/src/Endpoint/RouteMappings/ContextMappings.cs +++ b/src/Management/src/Endpoint/RouteMappings/ContextMappings.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -17,7 +16,7 @@ public sealed class ContextMappings public ContextMappings(IDictionary> mappingDictionary, string? parentId) { - ArgumentGuard.NotNull(mappingDictionary); + ArgumentNullException.ThrowIfNull(mappingDictionary); // At this point, .NET will only ever have one context, and it must be named "dispatcherServlets" // For .NET, the mappingDictionary contains keys that represent the type name of the controller and then a diff --git a/src/Management/src/Endpoint/RouteMappings/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/RouteMappings/EndpointServiceCollectionExtensions.cs index 772da77d5b..b6c60c9a81 100755 --- a/src/Management/src/Endpoint/RouteMappings/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/RouteMappings/EndpointServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -18,7 +17,7 @@ public static class EndpointServiceCollectionExtensions /// public static void AddMappingsActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddMappingsActuatorServices(); diff --git a/src/Management/src/Endpoint/RouteMappings/MediaTypeDescriptor.cs b/src/Management/src/Endpoint/RouteMappings/MediaTypeDescriptor.cs index a85ce6c4f0..58758f9859 100644 --- a/src/Management/src/Endpoint/RouteMappings/MediaTypeDescriptor.cs +++ b/src/Management/src/Endpoint/RouteMappings/MediaTypeDescriptor.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -17,7 +16,7 @@ public sealed class MediaTypeDescriptor public MediaTypeDescriptor(string mediaType, bool negated) { - ArgumentGuard.NotNull(mediaType); + ArgumentException.ThrowIfNullOrWhiteSpace(mediaType); MediaType = mediaType; Negated = negated; diff --git a/src/Management/src/Endpoint/RouteMappings/RequestMappingConditions.cs b/src/Management/src/Endpoint/RouteMappings/RequestMappingConditions.cs index 0c271bd93a..dc50e77fd8 100644 --- a/src/Management/src/Endpoint/RouteMappings/RequestMappingConditions.cs +++ b/src/Management/src/Endpoint/RouteMappings/RequestMappingConditions.cs @@ -30,12 +30,18 @@ public sealed class RequestMappingConditions public RequestMappingConditions(IList patterns, IList methods, IList consumes, IList produces, IList headers, IList @params) { - ArgumentGuard.NotNull(patterns); - ArgumentGuard.NotNull(methods); - ArgumentGuard.NotNull(consumes); - ArgumentGuard.NotNull(produces); - ArgumentGuard.NotNull(headers); - ArgumentGuard.NotNull(@params); + ArgumentNullException.ThrowIfNull(patterns); + ArgumentGuard.ElementsNotNullOrWhiteSpace(patterns); + ArgumentNullException.ThrowIfNull(methods); + ArgumentGuard.ElementsNotNullOrWhiteSpace(methods); + ArgumentNullException.ThrowIfNull(consumes); + ArgumentGuard.ElementsNotNull(consumes); + ArgumentNullException.ThrowIfNull(produces); + ArgumentGuard.ElementsNotNull(produces); + ArgumentNullException.ThrowIfNull(headers); + ArgumentGuard.ElementsNotNullOrWhiteSpace(headers); + ArgumentNullException.ThrowIfNull(@params); + ArgumentGuard.ElementsNotNullOrWhiteSpace(@params); Patterns = patterns; Methods = methods; diff --git a/src/Management/src/Endpoint/RouteMappings/RouteBuilderExtensions.cs b/src/Management/src/Endpoint/RouteMappings/RouteBuilderExtensions.cs index 90e1f7fb0b..1d055654e2 100644 --- a/src/Management/src/Endpoint/RouteMappings/RouteBuilderExtensions.cs +++ b/src/Management/src/Endpoint/RouteMappings/RouteBuilderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -21,7 +20,7 @@ public static class RouteBuilderExtensions /// public static IRouteBuilder AddRoutesToMappingsActuator(this IRouteBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); var routerMappings = builder.ServiceProvider.GetRequiredService(); diff --git a/src/Management/src/Endpoint/RouteMappings/RouteMappingDescription.cs b/src/Management/src/Endpoint/RouteMappings/RouteMappingDescription.cs index 6d23bf871e..5f7426144b 100755 --- a/src/Management/src/Endpoint/RouteMappings/RouteMappingDescription.cs +++ b/src/Management/src/Endpoint/RouteMappings/RouteMappingDescription.cs @@ -5,7 +5,6 @@ using System.Reflection; using System.Text; using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -24,8 +23,8 @@ public sealed class RouteMappingDescription public RouteMappingDescription(string routeHandler, AspNetCoreRouteDetails routeDetails) { - ArgumentGuard.NotNull(routeHandler); - ArgumentGuard.NotNull(routeDetails); + ArgumentException.ThrowIfNullOrWhiteSpace(routeHandler); + ArgumentNullException.ThrowIfNull(routeDetails); Handler = routeHandler; Predicate = CreatePredicateString(routeDetails); @@ -33,8 +32,8 @@ public RouteMappingDescription(string routeHandler, AspNetCoreRouteDetails route public RouteMappingDescription(MethodInfo routeHandlerMethod, AspNetCoreRouteDetails routeDetails) { - ArgumentGuard.NotNull(routeHandlerMethod); - ArgumentGuard.NotNull(routeDetails); + ArgumentNullException.ThrowIfNull(routeHandlerMethod); + ArgumentNullException.ThrowIfNull(routeDetails); Handler = routeHandlerMethod.ToString()!; Predicate = CreatePredicateString(routeDetails); @@ -92,7 +91,7 @@ private RouteMappingDetails CreateMappingDetails(AspNetCoreRouteDetails routeDet // Does not apply for .NET var @params = new List(); - var conditions = new RequestMappingConditions(patterns, routeDetails.HttpMethods.ToList(), consumes, produces, headers, @params); + var conditions = new RequestMappingConditions(patterns, routeDetails.HttpMethods, consumes, produces, headers, @params); return new RouteMappingDetails(conditions); } diff --git a/src/Management/src/Endpoint/RouteMappings/RouteMappingDetails.cs b/src/Management/src/Endpoint/RouteMappings/RouteMappingDetails.cs index 354f6bf31e..4ff80b8558 100644 --- a/src/Management/src/Endpoint/RouteMappings/RouteMappingDetails.cs +++ b/src/Management/src/Endpoint/RouteMappings/RouteMappingDetails.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -14,7 +13,7 @@ public sealed class RouteMappingDetails public RouteMappingDetails(RequestMappingConditions requestMappingConditions) { - ArgumentGuard.NotNull(requestMappingConditions); + ArgumentNullException.ThrowIfNull(requestMappingConditions); RequestMappingConditions = requestMappingConditions; } diff --git a/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs b/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs index 5f2967df92..1d8b11a23f 100755 --- a/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs +++ b/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs @@ -20,7 +20,7 @@ internal sealed class RouteMappingsEndpointHandler : IRouteMappingsEndpointHandl { private readonly IOptionsMonitor _optionsMonitor; private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; - private readonly IList _apiDescriptionProviders; + private readonly ICollection _apiDescriptionProviders; private readonly RouterMappings _routerMappings; private readonly ILogger _logger; @@ -30,15 +30,18 @@ public RouteMappingsEndpointHandler(IOptionsMonitor apiDescriptionProviders, RouterMappings routerMappings, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(actionDescriptorCollectionProvider); - ArgumentGuard.NotNull(apiDescriptionProviders); - ArgumentGuard.NotNull(routerMappings); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(actionDescriptorCollectionProvider); + ArgumentNullException.ThrowIfNull(apiDescriptionProviders); + ArgumentNullException.ThrowIfNull(routerMappings); + ArgumentNullException.ThrowIfNull(loggerFactory); + + IApiDescriptionProvider[] apiDescriptionProviderArray = apiDescriptionProviders.ToArray(); + ArgumentGuard.ElementsNotNull(apiDescriptionProviderArray); _optionsMonitor = optionsMonitor; _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; - _apiDescriptionProviders = apiDescriptionProviders.ToList(); + _apiDescriptionProviders = apiDescriptionProviderArray; _routerMappings = routerMappings; _logger = loggerFactory.CreateLogger(); } @@ -155,11 +158,10 @@ private AspNetCoreRouteDetails GetRouteDetails(ActionDescriptor actionDescriptor routeTemplate = $"/{controllerDescriptor.ControllerName}/{controllerDescriptor.ActionName}"; } - List httpMethods = actionDescriptor.ActionConstraints?.OfType().SingleOrDefault()?.HttpMethods.ToList() ?? - new List - { - RouteMappingDescription.AllHttpMethods - }; + string[] httpMethods = actionDescriptor.ActionConstraints?.OfType().SingleOrDefault()?.HttpMethods.ToArray() ?? + [ + RouteMappingDescription.AllHttpMethods + ]; var consumes = new List(); diff --git a/src/Management/src/Endpoint/RouteMappings/RouteMappingsResponse.cs b/src/Management/src/Endpoint/RouteMappings/RouteMappingsResponse.cs index d5c1a5281f..df33d39ee1 100755 --- a/src/Management/src/Endpoint/RouteMappings/RouteMappingsResponse.cs +++ b/src/Management/src/Endpoint/RouteMappings/RouteMappingsResponse.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -14,7 +13,7 @@ public sealed class RouteMappingsResponse public RouteMappingsResponse(ContextMappings contextMappings) { - ArgumentGuard.NotNull(contextMappings); + ArgumentNullException.ThrowIfNull(contextMappings); // At this point, .NET will only ever have one application => "application" ContextMappings = new Dictionary diff --git a/src/Management/src/Endpoint/RouteMappings/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/RouteMappings/ServiceCollectionExtensions.cs index f7d23c4b79..166874e195 100755 --- a/src/Management/src/Endpoint/RouteMappings/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/RouteMappings/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.RouteMappings; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddMappingsActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.TryAddSingleton(); diff --git a/src/Management/src/Endpoint/Services/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Services/EndpointServiceCollectionExtensions.cs index ba5f2efe68..ab96886122 100644 --- a/src/Management/src/Endpoint/Services/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Services/EndpointServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Services; @@ -17,7 +16,7 @@ public static class EndpointServiceCollectionExtensions /// public static IServiceCollection AddServicesActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddServicesActuatorServices(); diff --git a/src/Management/src/Endpoint/Services/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Services/ServiceCollectionExtensions.cs index e5174312ce..ccc3cded8b 100644 --- a/src/Management/src/Endpoint/Services/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Services/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.Services; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddServicesActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.AddSingleton(services); diff --git a/src/Management/src/Endpoint/Services/ServiceRegistration.cs b/src/Management/src/Endpoint/Services/ServiceRegistration.cs index 782e67bf72..46d200798b 100644 --- a/src/Management/src/Endpoint/Services/ServiceRegistration.cs +++ b/src/Management/src/Endpoint/Services/ServiceRegistration.cs @@ -6,7 +6,6 @@ using System.Reflection; using System.Text.Json.Serialization; using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Services; @@ -29,7 +28,7 @@ public sealed class ServiceRegistration public ServiceRegistration(ServiceDescriptor descriptor) { - ArgumentGuard.NotNull(descriptor); + ArgumentNullException.ThrowIfNull(descriptor); Name = descriptor.ServiceType.FullName!; Scope = descriptor.Lifetime.ToString(); diff --git a/src/Management/src/Endpoint/Services/ServicesEndpointHandler.cs b/src/Management/src/Endpoint/Services/ServicesEndpointHandler.cs index 9c21e6d7c3..5091faeeb4 100644 --- a/src/Management/src/Endpoint/Services/ServicesEndpointHandler.cs +++ b/src/Management/src/Endpoint/Services/ServicesEndpointHandler.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Services; @@ -17,16 +16,16 @@ internal sealed class ServicesEndpointHandler : IServicesEndpointHandler public ServicesEndpointHandler(IOptionsMonitor optionsMonitor, IServiceCollection services) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(services); _optionsMonitor = optionsMonitor; _lazyServiceRegistrations = new Lazy>(() => ConvertToRegistrations(services), LazyThreadSafetyMode.PublicationOnly); } - private static List ConvertToRegistrations(IServiceCollection services) + private static IList ConvertToRegistrations(IServiceCollection services) { - return services.Select(descriptor => new ServiceRegistration(descriptor)).ToList(); + return services.Select(descriptor => new ServiceRegistration(descriptor)).ToArray(); } public Task> InvokeAsync(object? argument, CancellationToken cancellationToken) diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/Application.cs b/src/Management/src/Endpoint/SpringBootAdminClient/Application.cs index 223d5cfb25..9cad8b6689 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/Application.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/Application.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.SpringBootAdminClient; @@ -26,11 +25,11 @@ internal sealed class Application public Application(string name, Uri managementUrl, Uri healthUrl, Uri serviceUrl, IDictionary metadata) { - ArgumentGuard.NotNull(name); - ArgumentGuard.NotNull(managementUrl); - ArgumentGuard.NotNull(healthUrl); - ArgumentGuard.NotNull(serviceUrl); - ArgumentGuard.NotNull(metadata); + ArgumentException.ThrowIfNullOrWhiteSpace(name); + ArgumentNullException.ThrowIfNull(managementUrl); + ArgumentNullException.ThrowIfNull(healthUrl); + ArgumentNullException.ThrowIfNull(serviceUrl); + ArgumentNullException.ThrowIfNull(metadata); Name = name; ManagementUrl = managementUrl; diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs b/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs index fb77ab4837..f2bdab7d80 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs @@ -22,8 +22,8 @@ internal sealed class ConfigureSpringBootAdminClientOptions : IConfigureOptionsW public ConfigureSpringBootAdminClientOptions(IConfiguration configuration, IApplicationInstanceInfo applicationInstanceInfo) { - ArgumentGuard.NotNull(configuration); - ArgumentGuard.NotNull(applicationInstanceInfo); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(applicationInstanceInfo); _configuration = configuration; _applicationInstanceInfo = applicationInstanceInfo; diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs index ab0c82b024..340411281b 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Extensions; using Steeltoe.Common.Http.HttpClientPooling; using Steeltoe.Management.Endpoint.Health; @@ -26,7 +25,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddSpringBootAdminClient(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.RegisterDefaultApplicationInstanceInfo(); diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs b/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs index 1a2213704a..24ee849ac0 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/SpringBootAdminClientHostedService.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Extensions; using Steeltoe.Common.Http; using Steeltoe.Management.Endpoint.Health; @@ -30,11 +29,11 @@ public SpringBootAdminClientHostedService(IOptionsMonitor managementOptionsMonitor, IOptionsMonitor healthOptionsMonitor, IHttpClientFactory httpClientFactory, ILogger logger) { - ArgumentGuard.NotNull(clientOptionsMonitor); - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(healthOptionsMonitor); - ArgumentGuard.NotNull(httpClientFactory); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(clientOptionsMonitor); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(healthOptionsMonitor); + ArgumentNullException.ThrowIfNull(httpClientFactory); + ArgumentNullException.ThrowIfNull(logger); _clientOptionsMonitor = clientOptionsMonitor; _managementOptionsMonitor = managementOptionsMonitor; diff --git a/src/Management/src/Endpoint/ThreadDump/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/ThreadDump/EndpointServiceCollectionExtensions.cs index 291ed9e729..71ed5bc321 100644 --- a/src/Management/src/Endpoint/ThreadDump/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/ThreadDump/EndpointServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.ThreadDump; @@ -17,14 +16,14 @@ public static class EndpointServiceCollectionExtensions /// public static void AddThreadDumpActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddThreadDumpActuator(MediaTypeVersion.V2); } public static void AddThreadDumpActuator(this IServiceCollection services, MediaTypeVersion version) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddThreadDumpActuatorServices(version); diff --git a/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs b/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs index 59ae5484b1..42e4a6d7dc 100644 --- a/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs +++ b/src/Management/src/Endpoint/ThreadDump/EventPipeThreadDumper.cs @@ -13,7 +13,6 @@ using Microsoft.Diagnostics.Tracing.Stacks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Extensions; namespace Steeltoe.Management.Endpoint.ThreadDump; @@ -42,8 +41,8 @@ public sealed class EventPipeThreadDumper public EventPipeThreadDumper(IOptionsMonitor optionsMonitor, ILogger logger) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _optionsMonitor = optionsMonitor; _logger = logger; diff --git a/src/Management/src/Endpoint/ThreadDump/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/ThreadDump/ServiceCollectionExtensions.cs index dae7f9b55d..a75b9e4eb7 100644 --- a/src/Management/src/Endpoint/ThreadDump/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/ThreadDump/ServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; using Steeltoe.Management.Endpoint.Options; @@ -30,7 +29,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddThreadDumpActuatorServices(this IServiceCollection services, MediaTypeVersion version) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); if (version == MediaTypeVersion.V1) { diff --git a/src/Management/src/Endpoint/ThreadDump/ThreadDumpEndpointHandler.cs b/src/Management/src/Endpoint/ThreadDump/ThreadDumpEndpointHandler.cs index 9272fd3b4b..2c7c4eda3a 100755 --- a/src/Management/src/Endpoint/ThreadDump/ThreadDumpEndpointHandler.cs +++ b/src/Management/src/Endpoint/ThreadDump/ThreadDumpEndpointHandler.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.ThreadDump; @@ -19,9 +18,9 @@ internal sealed class ThreadDumpEndpointHandler : IThreadDumpEndpointHandler public ThreadDumpEndpointHandler(IOptionsMonitor optionsMonitor, EventPipeThreadDumper threadDumper, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(threadDumper); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(threadDumper); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _threadDumper = threadDumper; diff --git a/src/Management/src/Endpoint/ThreadDump/ThreadDumpV2Converter.cs b/src/Management/src/Endpoint/ThreadDump/ThreadDumpV2Converter.cs index ebffe3ce11..db4af59150 100644 --- a/src/Management/src/Endpoint/ThreadDump/ThreadDumpV2Converter.cs +++ b/src/Management/src/Endpoint/ThreadDump/ThreadDumpV2Converter.cs @@ -4,7 +4,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.ThreadDump; @@ -17,7 +16,7 @@ public override IList Read(ref Utf8JsonReader reader, Type typeToCon public override void Write(Utf8JsonWriter writer, IList value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); + ArgumentNullException.ThrowIfNull(writer); writer.WriteStartObject(); writer.WritePropertyName("threads"); diff --git a/src/Management/src/Endpoint/Trace/ConfigureTraceEndpointOptions.cs b/src/Management/src/Endpoint/Trace/ConfigureTraceEndpointOptions.cs index 8bb0362482..e44059ad94 100644 --- a/src/Management/src/Endpoint/Trace/ConfigureTraceEndpointOptions.cs +++ b/src/Management/src/Endpoint/Trace/ConfigureTraceEndpointOptions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Options; namespace Steeltoe.Management.Endpoint.Trace; @@ -19,14 +18,14 @@ internal sealed class ConfigureTraceEndpointOptions : ConfigureEndpointOptions public static void AddTraceActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddTraceActuator(MediaTypeVersion.V2); } @@ -36,7 +35,7 @@ public static void AddTraceActuator(this IServiceCollection services) /// public static void AddTraceActuator(this IServiceCollection services, MediaTypeVersion version) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); services.AddHostedService(); diff --git a/src/Management/src/Endpoint/Trace/HttpTrace.cs b/src/Management/src/Endpoint/Trace/HttpTrace.cs index 475c362321..d8fce31026 100644 --- a/src/Management/src/Endpoint/Trace/HttpTrace.cs +++ b/src/Management/src/Endpoint/Trace/HttpTrace.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Trace; public sealed class HttpTrace @@ -17,8 +15,8 @@ public sealed class HttpTrace public HttpTrace(Request request, Response response, long timestamp, Principal? principal, Session? session, double timeTaken) { - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(response); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(response); Request = request; Response = response; diff --git a/src/Management/src/Endpoint/Trace/HttpTraceDiagnosticObserver.cs b/src/Management/src/Endpoint/Trace/HttpTraceDiagnosticObserver.cs index 09121eccc5..e28c42836b 100644 --- a/src/Management/src/Endpoint/Trace/HttpTraceDiagnosticObserver.cs +++ b/src/Management/src/Endpoint/Trace/HttpTraceDiagnosticObserver.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Trace; @@ -32,8 +31,8 @@ public override HttpTraceResult GetTraces() protected override void RecordHttpTrace(Activity current, HttpContext context) { - ArgumentGuard.NotNull(current); - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(current); + ArgumentNullException.ThrowIfNull(context); HttpTrace trace = MakeTraceV2(context, current.Duration); _queue.Enqueue(trace); diff --git a/src/Management/src/Endpoint/Trace/HttpTraceEndpointHandler.cs b/src/Management/src/Endpoint/Trace/HttpTraceEndpointHandler.cs index 7a86f3fdfe..b77ea4cab7 100755 --- a/src/Management/src/Endpoint/Trace/HttpTraceEndpointHandler.cs +++ b/src/Management/src/Endpoint/Trace/HttpTraceEndpointHandler.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Trace; @@ -23,9 +22,9 @@ internal sealed class HttpTraceEndpointHandler : IHttpTraceEndpointHandler public HttpTraceEndpointHandler(IOptionsMonitor optionsMonitor, IHttpTraceRepository traceRepository, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); - ArgumentGuard.NotNull(traceRepository); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(traceRepository); + ArgumentNullException.ThrowIfNull(loggerFactory); _optionsMonitor = optionsMonitor; _traceRepository = traceRepository; diff --git a/src/Management/src/Endpoint/Trace/HttpTraceResultConverter.cs b/src/Management/src/Endpoint/Trace/HttpTraceResultConverter.cs index 4beb61289f..db4c13db19 100644 --- a/src/Management/src/Endpoint/Trace/HttpTraceResultConverter.cs +++ b/src/Management/src/Endpoint/Trace/HttpTraceResultConverter.cs @@ -4,7 +4,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Trace; @@ -17,7 +16,7 @@ public override HttpTraceResult Read(ref Utf8JsonReader reader, Type typeToConve public override void Write(Utf8JsonWriter writer, HttpTraceResult value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); + ArgumentNullException.ThrowIfNull(writer); if (value is HttpTraceResultV2 traceResultV2) { diff --git a/src/Management/src/Endpoint/Trace/HttpTraceResultV1.cs b/src/Management/src/Endpoint/Trace/HttpTraceResultV1.cs index ec541cf0c8..4b3ac5a8c8 100644 --- a/src/Management/src/Endpoint/Trace/HttpTraceResultV1.cs +++ b/src/Management/src/Endpoint/Trace/HttpTraceResultV1.cs @@ -12,7 +12,8 @@ public sealed class HttpTraceResultV1 : HttpTraceResult public HttpTraceResultV1(IList traces) { - ArgumentGuard.NotNull(traces); + ArgumentNullException.ThrowIfNull(traces); + ArgumentGuard.ElementsNotNull(traces); Traces = traces; CurrentVersion = MediaTypeVersion.V1; diff --git a/src/Management/src/Endpoint/Trace/HttpTraceResultV2.cs b/src/Management/src/Endpoint/Trace/HttpTraceResultV2.cs index c3cc454813..2b4fc37c47 100644 --- a/src/Management/src/Endpoint/Trace/HttpTraceResultV2.cs +++ b/src/Management/src/Endpoint/Trace/HttpTraceResultV2.cs @@ -14,7 +14,8 @@ public sealed class HttpTraceResultV2 : HttpTraceResult public HttpTraceResultV2(IList traces) { - ArgumentGuard.NotNull(traces); + ArgumentNullException.ThrowIfNull(traces); + ArgumentGuard.ElementsNotNull(traces); Traces = traces; CurrentVersion = MediaTypeVersion.V2; diff --git a/src/Management/src/Endpoint/Trace/Principal.cs b/src/Management/src/Endpoint/Trace/Principal.cs index 7ba31ae4a8..7898162166 100644 --- a/src/Management/src/Endpoint/Trace/Principal.cs +++ b/src/Management/src/Endpoint/Trace/Principal.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Trace; public sealed class Principal @@ -12,7 +10,7 @@ public sealed class Principal public Principal(string name) { - ArgumentGuard.NotNull(name); + ArgumentException.ThrowIfNullOrEmpty(name); Name = name; } diff --git a/src/Management/src/Endpoint/Trace/Request.cs b/src/Management/src/Endpoint/Trace/Request.cs index eaaaa188f3..8ed3b7342a 100644 --- a/src/Management/src/Endpoint/Trace/Request.cs +++ b/src/Management/src/Endpoint/Trace/Request.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Trace; public sealed class Request @@ -15,9 +13,9 @@ public sealed class Request public Request(string method, string uri, IDictionary> headers, string? remoteAddress) { - ArgumentGuard.NotNull(method); - ArgumentGuard.NotNull(uri); - ArgumentGuard.NotNull(headers); + ArgumentException.ThrowIfNullOrWhiteSpace(method); + ArgumentException.ThrowIfNullOrWhiteSpace(uri); + ArgumentNullException.ThrowIfNull(headers); Method = method; Uri = uri; diff --git a/src/Management/src/Endpoint/Trace/Response.cs b/src/Management/src/Endpoint/Trace/Response.cs index 2045a5faae..c2bde75004 100644 --- a/src/Management/src/Endpoint/Trace/Response.cs +++ b/src/Management/src/Endpoint/Trace/Response.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Trace; public sealed class Response @@ -13,7 +11,7 @@ public sealed class Response public Response(int status, IDictionary> headers) { - ArgumentGuard.NotNull(headers); + ArgumentNullException.ThrowIfNull(headers); Status = status; Headers = headers; diff --git a/src/Management/src/Endpoint/Trace/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Trace/ServiceCollectionExtensions.cs index e48630d0a1..8095c6b3ed 100644 --- a/src/Management/src/Endpoint/Trace/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Trace/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.Trace; @@ -28,7 +27,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddTraceActuatorServices(this IServiceCollection services, MediaTypeVersion version) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); services.AddSingleton(); diff --git a/src/Management/src/Endpoint/Trace/Session.cs b/src/Management/src/Endpoint/Trace/Session.cs index 2c5c9bb95e..0e188071e9 100644 --- a/src/Management/src/Endpoint/Trace/Session.cs +++ b/src/Management/src/Endpoint/Trace/Session.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Trace; public sealed class Session @@ -12,7 +10,7 @@ public sealed class Session public Session(string id) { - ArgumentGuard.NotNull(id); + ArgumentException.ThrowIfNullOrWhiteSpace(id); Id = id; } diff --git a/src/Management/src/Endpoint/Trace/TraceDiagnosticObserver.cs b/src/Management/src/Endpoint/Trace/TraceDiagnosticObserver.cs index e409624c55..4304925c88 100644 --- a/src/Management/src/Endpoint/Trace/TraceDiagnosticObserver.cs +++ b/src/Management/src/Endpoint/Trace/TraceDiagnosticObserver.cs @@ -10,7 +10,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; namespace Steeltoe.Management.Endpoint.Trace; @@ -29,7 +28,7 @@ internal class TraceDiagnosticObserver : DiagnosticObserver, IHttpTraceRepositor public TraceDiagnosticObserver(IOptionsMonitor optionsMonitor, ILoggerFactory loggerFactory) : base(DefaultObserverName, DiagnosticName, loggerFactory) { - ArgumentGuard.NotNull(optionsMonitor); + ArgumentNullException.ThrowIfNull(optionsMonitor); _optionsMonitor = optionsMonitor; _logger = loggerFactory.CreateLogger(); @@ -69,8 +68,8 @@ public override void ProcessEvent(string eventName, object? value) protected virtual void RecordHttpTrace(Activity current, HttpContext context) { - ArgumentGuard.NotNull(current); - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(current); + ArgumentNullException.ThrowIfNull(context); TraceResult trace = MakeTrace(context, current.Duration); Queue.Enqueue(trace); @@ -83,7 +82,7 @@ protected virtual void RecordHttpTrace(Activity current, HttpContext context) internal TraceResult MakeTrace(HttpContext context, TimeSpan duration) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); HttpRequest request = context.Request; HttpResponse response = context.Response; @@ -161,7 +160,7 @@ internal long GetJavaTime(long ticks) internal string? GetSessionId(HttpContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); var sessionFeature = context.Features.Get(); @@ -177,7 +176,7 @@ internal string GetTimeTaken(TimeSpan duration) internal Dictionary> GetRequestParameters(HttpRequest request) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); var parameters = new Dictionary>(); IQueryCollection query = request.Query; @@ -202,35 +201,35 @@ internal string GetTimeTaken(TimeSpan duration) internal string GetRequestUri(HttpRequest request) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); return $"{request.Scheme}://{request.Host.Value}{request.Path.Value}"; } internal string? GetPathInfo(HttpRequest request) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); return request.Path.Value; } internal string? GetUserPrincipal(HttpContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); return context.User.Identity?.Name; } internal string? GetRemoteAddress(HttpContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); return context.Connection.RemoteIpAddress?.ToString(); } internal Dictionary GetHeaders(int status, IHeaderDictionary headers) { - ArgumentGuard.NotNull(headers); + ArgumentNullException.ThrowIfNull(headers); Dictionary result = GetHeaders(headers); result.Add("status", status.ToString(CultureInfo.InvariantCulture)); diff --git a/src/Management/src/Endpoint/Trace/TraceResult.cs b/src/Management/src/Endpoint/Trace/TraceResult.cs index c76cc243b7..c0949e9984 100644 --- a/src/Management/src/Endpoint/Trace/TraceResult.cs +++ b/src/Management/src/Endpoint/Trace/TraceResult.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.Json.Serialization; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Trace; @@ -17,7 +16,7 @@ public sealed class TraceResult public TraceResult(long timestamp, IDictionary info) { - ArgumentGuard.NotNull(info); + ArgumentNullException.ThrowIfNull(info); TimeStamp = timestamp; Info = info; diff --git a/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs b/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs index 2b1efab870..232f3fe898 100755 --- a/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/ActuatorEndpointHandler.cs @@ -24,20 +24,23 @@ internal sealed class ActuatorEndpointHandler : IActuatorEndpointHandler public ActuatorEndpointHandler(IOptionsMonitor managementOptionsMonitor, IOptionsMonitor endpointOptionsMonitor, IEnumerable endpointOptionsCollection, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsCollection); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsCollection); + ArgumentNullException.ThrowIfNull(loggerFactory); + + EndpointOptions[] endpointOptionsArray = endpointOptionsCollection.ToArray(); + ArgumentGuard.ElementsNotNull(endpointOptionsArray); _managementOptionsMonitor = managementOptionsMonitor; _endpointOptionsMonitor = endpointOptionsMonitor; - _endpointOptionsCollection = endpointOptionsCollection.ToList(); + _endpointOptionsCollection = endpointOptionsArray; _hypermediaServiceLogger = loggerFactory.CreateLogger(); } public Task InvokeAsync(string baseUrl, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(baseUrl); + ArgumentException.ThrowIfNullOrWhiteSpace(baseUrl); var service = new HypermediaService(_managementOptionsMonitor, _endpointOptionsMonitor, _endpointOptionsCollection, _hypermediaServiceLogger); Links result = service.Invoke(baseUrl); diff --git a/src/Management/src/Endpoint/Web/Hypermedia/ActuatorHypermediaEndpointMiddleware.cs b/src/Management/src/Endpoint/Web/Hypermedia/ActuatorHypermediaEndpointMiddleware.cs index 97c9f4c0c5..86abda4aed 100644 --- a/src/Management/src/Endpoint/Web/Hypermedia/ActuatorHypermediaEndpointMiddleware.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/ActuatorHypermediaEndpointMiddleware.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; using Steeltoe.Management.Endpoint.Options; @@ -25,7 +24,7 @@ public ActuatorHypermediaEndpointMiddleware(IActuatorEndpointHandler endpointHan protected override async Task InvokeEndpointHandlerAsync(HttpContext context, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); _logger.LogDebug("InvokeAsync({Method}, {Path})", context.Request.Method, context.Request.Path.Value); string requestUri = GetRequestUri(context.Request); diff --git a/src/Management/src/Endpoint/Web/Hypermedia/EndpointServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Web/Hypermedia/EndpointServiceCollectionExtensions.cs index 611af9cab4..013299f846 100644 --- a/src/Management/src/Endpoint/Web/Hypermedia/EndpointServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/EndpointServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; namespace Steeltoe.Management.Endpoint.Web.Hypermedia; @@ -11,7 +10,7 @@ public static class EndpointServiceCollectionExtensions { public static void AddHypermediaActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddCommonActuatorServices(); services.AddHypermediaActuatorServices(); diff --git a/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs b/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs index 43522b1082..ad07b930e9 100644 --- a/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/HypermediaService.cs @@ -21,10 +21,11 @@ public HypermediaService(IOptionsMonitor managementOptionsMon IOptionsMonitor hypermediaEndpointOptionsMonitor, ICollection endpointOptionsCollection, ILogger logger) { - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(hypermediaEndpointOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsCollection); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(hypermediaEndpointOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsCollection); + ArgumentGuard.ElementsNotNull(endpointOptionsCollection); + ArgumentNullException.ThrowIfNull(logger); _managementOptionsMonitor = managementOptionsMonitor; _endpointOptions = hypermediaEndpointOptionsMonitor.CurrentValue; @@ -36,10 +37,11 @@ public HypermediaService(IOptionsMonitor managementOptionsMon IOptionsMonitor cloudFoundryEndpointOptionsMonitor, ICollection endpointOptionsCollection, ILogger logger) { - ArgumentGuard.NotNull(managementOptionsMonitor); - ArgumentGuard.NotNull(cloudFoundryEndpointOptionsMonitor); - ArgumentGuard.NotNull(endpointOptionsCollection); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(managementOptionsMonitor); + ArgumentNullException.ThrowIfNull(cloudFoundryEndpointOptionsMonitor); + ArgumentNullException.ThrowIfNull(endpointOptionsCollection); + ArgumentGuard.ElementsNotNull(endpointOptionsCollection); + ArgumentNullException.ThrowIfNull(logger); _managementOptionsMonitor = managementOptionsMonitor; _endpointOptions = cloudFoundryEndpointOptionsMonitor.CurrentValue; @@ -49,7 +51,7 @@ public HypermediaService(IOptionsMonitor managementOptionsMon public Links Invoke(string baseUrl) { - ArgumentGuard.NotNull(baseUrl); + ArgumentException.ThrowIfNullOrWhiteSpace(baseUrl); var links = new Links(); diff --git a/src/Management/src/Endpoint/Web/Hypermedia/Link.cs b/src/Management/src/Endpoint/Web/Hypermedia/Link.cs index 89d28dd2e4..7eb12f9c09 100644 --- a/src/Management/src/Endpoint/Web/Hypermedia/Link.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/Link.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Steeltoe.Common; - namespace Steeltoe.Management.Endpoint.Web.Hypermedia; public sealed class Link @@ -14,7 +12,7 @@ public sealed class Link public Link(string href) { - ArgumentGuard.NotNull(href); + ArgumentException.ThrowIfNullOrEmpty(href); Href = href; Templated = href.Contains('{'); diff --git a/src/Management/src/Endpoint/Web/Hypermedia/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/Web/Hypermedia/ServiceCollectionExtensions.cs index ea2ff2af9f..6511e9004f 100644 --- a/src/Management/src/Endpoint/Web/Hypermedia/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/Web/Hypermedia/ServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.Middleware; namespace Steeltoe.Management.Endpoint.Web.Hypermedia; @@ -25,7 +24,7 @@ public static class ServiceCollectionExtensions /// public static IServiceCollection AddHypermediaActuatorServices(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); diff --git a/src/Management/src/Prometheus/PrometheusExtensions.cs b/src/Management/src/Prometheus/PrometheusExtensions.cs index 7d5873f0c1..a760eb875f 100644 --- a/src/Management/src/Prometheus/PrometheusExtensions.cs +++ b/src/Management/src/Prometheus/PrometheusExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using OpenTelemetry.Metrics; -using Steeltoe.Common; using Steeltoe.Management.Endpoint; using Steeltoe.Management.Endpoint.Metrics; using Steeltoe.Management.Endpoint.Options; @@ -26,7 +25,7 @@ public static class PrometheusExtensions /// public static IServiceCollection AddPrometheusActuator(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.ConfigureEndpointOptions(); @@ -41,7 +40,7 @@ public static IServiceCollection AddPrometheusActuator(this IServiceCollection s public static IApplicationBuilder MapPrometheusActuator(this IApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); ManagementOptions? managementOptions = builder.ApplicationServices.GetService>()?.CurrentValue; diff --git a/src/Management/src/Tasks/DelegatingTask.cs b/src/Management/src/Tasks/DelegatingTask.cs index 0d47bf7e0d..f2fb52e6f9 100644 --- a/src/Management/src/Tasks/DelegatingTask.cs +++ b/src/Management/src/Tasks/DelegatingTask.cs @@ -12,7 +12,7 @@ internal sealed class DelegatingTask : IApplicationTask public DelegatingTask(Func asyncAction) { - ArgumentGuard.NotNull(asyncAction); + ArgumentNullException.ThrowIfNull(asyncAction); _asyncAction = asyncAction; } diff --git a/src/Management/src/Tasks/TaskHostExtensions.cs b/src/Management/src/Tasks/TaskHostExtensions.cs index 0e05ba0936..5c29830f56 100644 --- a/src/Management/src/Tasks/TaskHostExtensions.cs +++ b/src/Management/src/Tasks/TaskHostExtensions.cs @@ -31,7 +31,7 @@ public static class TaskHostExtensions /// public static async Task RunWithTasksAsync(this IWebHost host, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(host); + ArgumentNullException.ThrowIfNull(host); if (await FindAndRunTaskAsync(host.Services, cancellationToken)) { @@ -61,7 +61,7 @@ public static async Task RunWithTasksAsync(this IWebHost host, CancellationToken /// public static async Task RunWithTasksAsync(this IHost host, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(host); + ArgumentNullException.ThrowIfNull(host); if (await FindAndRunTaskAsync(host.Services, cancellationToken)) { diff --git a/src/Management/src/Tasks/TaskServiceCollectionExtensions.cs b/src/Management/src/Tasks/TaskServiceCollectionExtensions.cs index eb47daa948..14db519afc 100644 --- a/src/Management/src/Tasks/TaskServiceCollectionExtensions.cs +++ b/src/Management/src/Tasks/TaskServiceCollectionExtensions.cs @@ -48,8 +48,8 @@ public static void AddTask(this IServiceCollection services, string taskName) /// public static void AddTask(this IServiceCollection services, string taskName, ServiceLifetime lifetime) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNullOrEmpty(taskName); + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrWhiteSpace(taskName); services.TryAdd(new ServiceDescriptor(typeof(IApplicationTask), taskName, typeof(T), lifetime)); } @@ -68,9 +68,9 @@ public static void AddTask(this IServiceCollection services, string taskName, /// public static void AddTask(this IServiceCollection services, string taskName, IApplicationTask task) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNullOrEmpty(taskName); - ArgumentGuard.NotNull(task); + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrWhiteSpace(taskName); + ArgumentNullException.ThrowIfNull(task); services.TryAddKeyedSingleton(taskName, task); } @@ -89,9 +89,9 @@ public static void AddTask(this IServiceCollection services, string taskName, IA /// public static void AddTask(this IServiceCollection services, string taskName, Func asyncAction) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(taskName); - ArgumentGuard.NotNull(asyncAction); + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrWhiteSpace(taskName); + ArgumentNullException.ThrowIfNull(asyncAction); services.TryAddKeyedScoped(taskName, (serviceProvider, _) => new DelegatingTask(cancellationToken => asyncAction(serviceProvider, cancellationToken))); @@ -111,9 +111,9 @@ public static void AddTask(this IServiceCollection services, string taskName, Fu /// public static void AddTask(this IServiceCollection services, string taskName, Func factory) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNullOrEmpty(taskName); - ArgumentGuard.NotNull(factory); + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrWhiteSpace(taskName); + ArgumentNullException.ThrowIfNull(factory); services.TryAddKeyedScoped(taskName, (serviceProvider, _) => factory(serviceProvider, taskName)); } diff --git a/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs b/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs index 65d70b22ae..1668be214f 100644 --- a/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs +++ b/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs @@ -55,7 +55,7 @@ public static IServiceCollection AddDistributedTracing(this IServiceCollection s /// public static IServiceCollection AddDistributedTracing(this IServiceCollection services, Action? action) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddOptions(); services.RegisterDefaultApplicationInstanceInfo(); diff --git a/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs b/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs index b10724329c..38f8a3f709 100644 --- a/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs +++ b/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection; using OpenTelemetry.Instrumentation.AspNetCore; using OpenTelemetry.Trace; -using Steeltoe.Common; namespace Steeltoe.Management.Tracing; @@ -40,7 +39,7 @@ public static IServiceCollection AddDistributedTracingAspNetCore(this IServiceCo /// public static IServiceCollection AddDistributedTracingAspNetCore(this IServiceCollection services, Action? action) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); action += builder => builder.AddAspNetCoreInstrumentation(); diff --git a/src/Management/src/Tracing/TracingLogProcessor.cs b/src/Management/src/Tracing/TracingLogProcessor.cs index 6786162af6..6c09b5a359 100644 --- a/src/Management/src/Tracing/TracingLogProcessor.cs +++ b/src/Management/src/Tracing/TracingLogProcessor.cs @@ -4,7 +4,6 @@ using System.Text; using OpenTelemetry.Trace; -using Steeltoe.Common; using Steeltoe.Logging; namespace Steeltoe.Management.Tracing; @@ -15,14 +14,14 @@ public sealed class TracingLogProcessor : IDynamicMessageProcessor public TracingLogProcessor(TracingOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _options = options; } public string Process(string message) { - ArgumentGuard.NotNull(message); + ArgumentNullException.ThrowIfNull(message); TelemetrySpan? currentSpan = GetCurrentSpan(); diff --git a/src/Management/src/Tracing/TracingOptions.cs b/src/Management/src/Tracing/TracingOptions.cs index 2b40f84cbc..bf0d09bf96 100644 --- a/src/Management/src/Tracing/TracingOptions.cs +++ b/src/Management/src/Tracing/TracingOptions.cs @@ -76,7 +76,7 @@ public sealed class TracingOptions public TracingOptions(IApplicationInstanceInfo? appInfo, IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); IConfigurationSection section = configuration.GetSection(ConfigurationPrefix); section.Bind(this); diff --git a/src/Management/src/Wavefront/Exporters/ConfigureWavefrontExporterOptions.cs b/src/Management/src/Wavefront/Exporters/ConfigureWavefrontExporterOptions.cs index b65b9ddaaa..8941657632 100644 --- a/src/Management/src/Wavefront/Exporters/ConfigureWavefrontExporterOptions.cs +++ b/src/Management/src/Wavefront/Exporters/ConfigureWavefrontExporterOptions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Common.Net; using Steeltoe.Management.Endpoint.Options; @@ -22,14 +21,14 @@ internal sealed class ConfigureWavefrontExporterOptions : IConfigureOptionsWithK public ConfigureWavefrontExporterOptions(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); _configuration = configuration; } public void Configure(WavefrontExporterOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _configuration.GetSection(WavefrontMetricsPrefix).Bind(options); diff --git a/src/Management/src/Wavefront/Exporters/WavefrontMetricsExporter.cs b/src/Management/src/Wavefront/Exporters/WavefrontMetricsExporter.cs index a0b9b09163..e830f9ddbc 100644 --- a/src/Management/src/Wavefront/Exporters/WavefrontMetricsExporter.cs +++ b/src/Management/src/Wavefront/Exporters/WavefrontMetricsExporter.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Metrics; -using Steeltoe.Common; using Wavefront.SDK.CSharp.DirectIngestion; using Wavefront.SDK.CSharp.Entities.Metrics; @@ -22,8 +21,8 @@ public sealed class WavefrontMetricsExporter : BaseExporter public WavefrontMetricsExporter(WavefrontExporterOptions options, ILogger logger) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(logger); Options = options; _logger = logger; diff --git a/src/Management/src/Wavefront/Exporters/WavefrontTraceExporter.cs b/src/Management/src/Wavefront/Exporters/WavefrontTraceExporter.cs index 9dc1b6dd2b..bf05b06dd5 100644 --- a/src/Management/src/Wavefront/Exporters/WavefrontTraceExporter.cs +++ b/src/Management/src/Wavefront/Exporters/WavefrontTraceExporter.cs @@ -6,7 +6,6 @@ using System.Globalization; using Microsoft.Extensions.Logging; using OpenTelemetry; -using Steeltoe.Common; using Wavefront.SDK.CSharp.Common; using Wavefront.SDK.CSharp.DirectIngestion; @@ -25,8 +24,8 @@ public sealed class WavefrontTraceExporter : BaseExporter public WavefrontTraceExporter(WavefrontExporterOptions options, ILogger logger) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(logger); _options = options; diff --git a/src/Management/src/Wavefront/Exporters/WavefrontTraceExtensions.cs b/src/Management/src/Wavefront/Exporters/WavefrontTraceExtensions.cs index 698550a2af..f040bce375 100644 --- a/src/Management/src/Wavefront/Exporters/WavefrontTraceExtensions.cs +++ b/src/Management/src/Wavefront/Exporters/WavefrontTraceExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Trace; -using Steeltoe.Common; namespace Steeltoe.Management.Wavefront.Exporters; @@ -14,9 +13,9 @@ public static class WavefrontTraceExtensions public static TracerProviderBuilder AddWavefrontTraceExporter(this TracerProviderBuilder builder, WavefrontExporterOptions options, ILogger logger) { - ArgumentGuard.NotNull(builder); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(logger); var exporter = new WavefrontTraceExporter(options, logger); diff --git a/src/Management/src/Wavefront/WavefrontExtensions.cs b/src/Management/src/Wavefront/WavefrontExtensions.cs index 39d9626b96..dbf518236d 100644 --- a/src/Management/src/Wavefront/WavefrontExtensions.cs +++ b/src/Management/src/Wavefront/WavefrontExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenTelemetry.Metrics; -using Steeltoe.Common; using Steeltoe.Management.Diagnostics; using Steeltoe.Management.Endpoint; using Steeltoe.Management.Endpoint.Diagnostics; @@ -29,7 +28,7 @@ public static class WavefrontExtensions /// public static IServiceCollection AddWavefrontMetrics(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.TryAddSingleton(); services.AddHostedService(); @@ -48,7 +47,7 @@ public static IServiceCollection AddWavefrontMetrics(this IServiceCollection ser public static MeterProviderBuilder AddWavefrontExporter(this MeterProviderBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); return builder.AddReader(serviceProvider => { diff --git a/src/Management/test/Endpoint.Test/Info/Contributor/GitInfoContributorTest.cs b/src/Management/test/Endpoint.Test/Info/Contributor/GitInfoContributorTest.cs index 685689ff50..7121c432d9 100755 --- a/src/Management/test/Endpoint.Test/Info/Contributor/GitInfoContributorTest.cs +++ b/src/Management/test/Endpoint.Test/Info/Contributor/GitInfoContributorTest.cs @@ -15,9 +15,9 @@ public sealed class GitInfoContributorTest : BaseTest [Fact] public async Task ReadGitPropertiesMissingPropertiesFile() { - var contributor = new GitInfoContributor(NullLogger.Instance); + var contributor = new GitInfoContributor("foobar", NullLogger.Instance); - IConfiguration? configuration = await contributor.ReadGitPropertiesAsync("foobar", CancellationToken.None); + IConfiguration? configuration = await contributor.ReadGitPropertiesAsync(CancellationToken.None); Assert.Null(configuration); } @@ -25,10 +25,10 @@ public async Task ReadGitPropertiesMissingPropertiesFile() [Fact] public async Task ReadEmptyGitPropertiesFile() { - var contributor = new GitInfoContributor(NullLogger.Instance); string path = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}empty.git.properties"; + var contributor = new GitInfoContributor(path, NullLogger.Instance); - IConfiguration? configuration = await contributor.ReadGitPropertiesAsync(path, CancellationToken.None); + IConfiguration? configuration = await contributor.ReadGitPropertiesAsync(CancellationToken.None); Assert.Null(configuration); } @@ -36,10 +36,10 @@ public async Task ReadEmptyGitPropertiesFile() [Fact] public async Task ReadMalformedGitPropertiesFile() { - var contributor = new GitInfoContributor(NullLogger.Instance); string path = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}garbage.git.properties"; + var contributor = new GitInfoContributor(path, NullLogger.Instance); - IConfiguration? configuration = await contributor.ReadGitPropertiesAsync(path, CancellationToken.None); + IConfiguration? configuration = await contributor.ReadGitPropertiesAsync(CancellationToken.None); Assert.NotNull(configuration); Assert.Null(configuration["git"]); @@ -48,10 +48,10 @@ public async Task ReadMalformedGitPropertiesFile() [Fact] public async Task ReadGoodPropertiesFile() { - var contributor = new GitInfoContributor(NullLogger.Instance); string path = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}git.properties"; + var contributor = new GitInfoContributor(path, NullLogger.Instance); - IConfiguration? configuration = await contributor.ReadGitPropertiesAsync(path, CancellationToken.None); + IConfiguration? configuration = await contributor.ReadGitPropertiesAsync(CancellationToken.None); Assert.NotNull(configuration); Assert.Equal("true", configuration["git:dirty"]); diff --git a/src/Management/test/Endpoint.Test/Infrastructure/TestContext.cs b/src/Management/test/Endpoint.Test/Infrastructure/TestContext.cs index c8f95d6067..583cfd38b1 100644 --- a/src/Management/test/Endpoint.Test/Infrastructure/TestContext.cs +++ b/src/Management/test/Endpoint.Test/Infrastructure/TestContext.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Steeltoe.Common; using Steeltoe.Common.TestResources; using Xunit.Abstractions; @@ -72,7 +71,7 @@ public IConfigurationRoot Configuration public TestContext(ITestOutputHelper output) { - ArgumentGuard.NotNull(output); + ArgumentNullException.ThrowIfNull(output); _loggerProvider = new XunitLoggerProvider(output); } diff --git a/src/Management/test/Endpoint.Test/RouteMappings/Startup.cs b/src/Management/test/Endpoint.Test/RouteMappings/Startup.cs index 55a660846a..48bac46ae0 100644 --- a/src/Management/test/Endpoint.Test/RouteMappings/Startup.cs +++ b/src/Management/test/Endpoint.Test/RouteMappings/Startup.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Steeltoe.Common; using Steeltoe.Management.Endpoint.CloudFoundry; using Steeltoe.Management.Endpoint.RouteMappings; @@ -19,7 +18,7 @@ public sealed class Startup public Startup(IConfiguration configuration) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); _configuration = configuration; } diff --git a/src/Security/src/Authentication.JwtBearer/JwtBearerAuthenticationBuilderExtensions.cs b/src/Security/src/Authentication.JwtBearer/JwtBearerAuthenticationBuilderExtensions.cs index 88beeccf4b..81cef930da 100644 --- a/src/Security/src/Authentication.JwtBearer/JwtBearerAuthenticationBuilderExtensions.cs +++ b/src/Security/src/Authentication.JwtBearer/JwtBearerAuthenticationBuilderExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Security.Authentication.JwtBearer; @@ -20,7 +19,7 @@ public static class JwtBearerAuthenticationBuilderExtensions /// public static AuthenticationBuilder ConfigureJwtBearerForCloudFoundry(this AuthenticationBuilder authenticationBuilder) { - ArgumentGuard.NotNull(authenticationBuilder); + ArgumentNullException.ThrowIfNull(authenticationBuilder); authenticationBuilder.Services.AddSingleton, PostConfigureJwtBearerOptions>(); return authenticationBuilder; diff --git a/src/Security/src/Authentication.JwtBearer/PostConfigureJwtBearerOptions.cs b/src/Security/src/Authentication.JwtBearer/PostConfigureJwtBearerOptions.cs index ad8cba32a8..d89a77d15e 100644 --- a/src/Security/src/Authentication.JwtBearer/PostConfigureJwtBearerOptions.cs +++ b/src/Security/src/Authentication.JwtBearer/PostConfigureJwtBearerOptions.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Security.Authentication.JwtBearer; @@ -16,14 +15,14 @@ internal sealed class PostConfigureJwtBearerOptions : IPostConfigureOptions($"{BearerConfigurationKeyPrefix}:ClientId"); diff --git a/src/Security/src/Authentication.JwtBearer/TokenKeyResolver.cs b/src/Security/src/Authentication.JwtBearer/TokenKeyResolver.cs index 2207992308..08b393ba4b 100644 --- a/src/Security/src/Authentication.JwtBearer/TokenKeyResolver.cs +++ b/src/Security/src/Authentication.JwtBearer/TokenKeyResolver.cs @@ -5,7 +5,6 @@ using System.Collections.Concurrent; using System.Net.Http.Headers; using Microsoft.IdentityModel.Tokens; -using Steeltoe.Common; namespace Steeltoe.Security.Authentication.JwtBearer; @@ -19,8 +18,8 @@ internal sealed class TokenKeyResolver public TokenKeyResolver(string authority, HttpClient httpClient) { - ArgumentGuard.NotNull(authority); - ArgumentGuard.NotNull(httpClient); + ArgumentException.ThrowIfNullOrWhiteSpace(authority); + ArgumentNullException.ThrowIfNull(httpClient); if (!authority.EndsWith('/')) { diff --git a/src/Security/src/Authentication.OpenIdConnect/OpenIdConnectAuthenticationBuilderExtensions.cs b/src/Security/src/Authentication.OpenIdConnect/OpenIdConnectAuthenticationBuilderExtensions.cs index 9772d7159f..9d7fc2f4f7 100644 --- a/src/Security/src/Authentication.OpenIdConnect/OpenIdConnectAuthenticationBuilderExtensions.cs +++ b/src/Security/src/Authentication.OpenIdConnect/OpenIdConnectAuthenticationBuilderExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Steeltoe.Common; namespace Steeltoe.Security.Authentication.OpenIdConnect; @@ -20,7 +19,7 @@ public static class OpenIdConnectAuthenticationBuilderExtensions /// public static AuthenticationBuilder ConfigureOpenIdConnectForCloudFoundry(this AuthenticationBuilder authenticationBuilder) { - ArgumentGuard.NotNull(authenticationBuilder); + ArgumentNullException.ThrowIfNull(authenticationBuilder); authenticationBuilder.Services.AddSingleton, PostConfigureOpenIdConnectOptions>(); return authenticationBuilder; diff --git a/src/Security/src/Authentication.OpenIdConnect/PostConfigureOpenIdConnectOptions.cs b/src/Security/src/Authentication.OpenIdConnect/PostConfigureOpenIdConnectOptions.cs index 47525a7425..06a205df88 100644 --- a/src/Security/src/Authentication.OpenIdConnect/PostConfigureOpenIdConnectOptions.cs +++ b/src/Security/src/Authentication.OpenIdConnect/PostConfigureOpenIdConnectOptions.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols.OpenIdConnect; -using Steeltoe.Common; namespace Steeltoe.Security.Authentication.OpenIdConnect; @@ -40,7 +39,7 @@ private static Task MapScopesToClaimsAsync(TokenValidatedContext context) public void PostConfigure(string? name, OpenIdConnectOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); options.Events.OnTokenValidated = MapScopesToClaimsAsync; diff --git a/src/Security/src/Authentication.OpenIdConnect/TokenKeyResolver.cs b/src/Security/src/Authentication.OpenIdConnect/TokenKeyResolver.cs index 18c24373b9..7239caa93a 100644 --- a/src/Security/src/Authentication.OpenIdConnect/TokenKeyResolver.cs +++ b/src/Security/src/Authentication.OpenIdConnect/TokenKeyResolver.cs @@ -5,7 +5,6 @@ using System.Collections.Concurrent; using System.Net.Http.Headers; using Microsoft.IdentityModel.Tokens; -using Steeltoe.Common; namespace Steeltoe.Security.Authentication.OpenIdConnect; @@ -19,8 +18,8 @@ internal sealed class TokenKeyResolver public TokenKeyResolver(string authority, HttpClient httpClient) { - ArgumentGuard.NotNull(authority); - ArgumentGuard.NotNull(httpClient); + ArgumentException.ThrowIfNullOrWhiteSpace(authority); + ArgumentNullException.ThrowIfNull(httpClient); if (!authority.EndsWith('/')) { diff --git a/src/Security/src/Authorization.Certificate/CertificateApplicationBuilderExtensions.cs b/src/Security/src/Authorization.Certificate/CertificateApplicationBuilderExtensions.cs index 175b5822db..67c92bfff2 100644 --- a/src/Security/src/Authorization.Certificate/CertificateApplicationBuilderExtensions.cs +++ b/src/Security/src/Authorization.Certificate/CertificateApplicationBuilderExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.HttpOverrides; -using Steeltoe.Common; namespace Steeltoe.Security.Authorization.Certificate; @@ -33,8 +32,8 @@ public static IApplicationBuilder UseCertificateAuthorization(this IApplicationB /// public static IApplicationBuilder UseCertificateAuthorization(this IApplicationBuilder applicationBuilder, ForwardedHeadersOptions options) { - ArgumentGuard.NotNull(applicationBuilder); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(applicationBuilder); + ArgumentNullException.ThrowIfNull(options); options.ForwardedHeaders |= ForwardedHeaders.XForwardedProto; diff --git a/src/Security/src/Authorization.Certificate/CertificateAuthorizationBuilderExtensions.cs b/src/Security/src/Authorization.Certificate/CertificateAuthorizationBuilderExtensions.cs index 7a675a0fa2..b488d47d35 100644 --- a/src/Security/src/Authorization.Certificate/CertificateAuthorizationBuilderExtensions.cs +++ b/src/Security/src/Authorization.Certificate/CertificateAuthorizationBuilderExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Certificates; namespace Steeltoe.Security.Authorization.Certificate; @@ -28,7 +27,7 @@ public static class CertificateAuthorizationBuilderExtensions /// public static AuthorizationBuilder AddOrgAndSpacePolicies(this AuthorizationBuilder authorizationBuilder) { - ArgumentGuard.NotNull(authorizationBuilder); + ArgumentNullException.ThrowIfNull(authorizationBuilder); authorizationBuilder.Services.ConfigureCertificateOptions(CertificateConfigurationExtensions.AppInstanceIdentityCertificateName); diff --git a/src/Security/src/Authorization.Certificate/CertificateAuthorizationHandler.cs b/src/Security/src/Authorization.Certificate/CertificateAuthorizationHandler.cs index ac24843160..96dbeb1173 100644 --- a/src/Security/src/Authorization.Certificate/CertificateAuthorizationHandler.cs +++ b/src/Security/src/Authorization.Certificate/CertificateAuthorizationHandler.cs @@ -6,7 +6,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Certificates; using Steeltoe.Common.Configuration; @@ -19,8 +18,8 @@ internal sealed class CertificateAuthorizationHandler : IAuthorizationHandler public CertificateAuthorizationHandler(IOptionsMonitor certificateOptionsMonitor, ILogger logger) { - ArgumentGuard.NotNull(certificateOptionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(certificateOptionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _logger = logger; certificateOptionsMonitor.OnChange(OnCertificateRefresh); @@ -29,7 +28,7 @@ public CertificateAuthorizationHandler(IOptionsMonitor certi public Task HandleAsync(AuthorizationHandlerContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); HandleCertificateAuthorizationRequirement(context, ApplicationClaimTypes.OrganizationId, _applicationInstanceCertificate?.OrganizationId); diff --git a/src/Security/src/Authorization.Certificate/CertificateAuthorizationPolicyBuilderExtensions.cs b/src/Security/src/Authorization.Certificate/CertificateAuthorizationPolicyBuilderExtensions.cs index 0014fd88a3..739106f8f9 100644 --- a/src/Security/src/Authorization.Certificate/CertificateAuthorizationPolicyBuilderExtensions.cs +++ b/src/Security/src/Authorization.Certificate/CertificateAuthorizationPolicyBuilderExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using Microsoft.AspNetCore.Authorization; -using Steeltoe.Common; namespace Steeltoe.Security.Authorization.Certificate; @@ -17,7 +16,7 @@ public static class CertificateAuthorizationPolicyBuilderExtensions /// public static AuthorizationPolicyBuilder RequireSameOrg(this AuthorizationPolicyBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Requirements.Add(new SameOrgRequirement()); return builder; @@ -31,7 +30,7 @@ public static AuthorizationPolicyBuilder RequireSameOrg(this AuthorizationPolicy /// public static AuthorizationPolicyBuilder RequireSameSpace(this AuthorizationPolicyBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Requirements.Add(new SameSpaceRequirement()); return builder; diff --git a/src/Security/src/Authorization.Certificate/CertificateHttpClientBuilderExtensions.cs b/src/Security/src/Authorization.Certificate/CertificateHttpClientBuilderExtensions.cs index 6a6bdb54aa..6170fcb710 100644 --- a/src/Security/src/Authorization.Certificate/CertificateHttpClientBuilderExtensions.cs +++ b/src/Security/src/Authorization.Certificate/CertificateHttpClientBuilderExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Certificates; using Steeltoe.Common.Configuration; @@ -37,8 +36,8 @@ public static IHttpClientBuilder AddAppInstanceIdentityCertificate(this IHttpCli /// public static IHttpClientBuilder AddClientCertificate(this IHttpClientBuilder httpClientBuilder, string certificateName) { - ArgumentGuard.NotNull(httpClientBuilder); - ArgumentGuard.NotNull(certificateName); + ArgumentNullException.ThrowIfNull(httpClientBuilder); + ArgumentNullException.ThrowIfNull(certificateName); httpClientBuilder.Services.ConfigureCertificateOptions(certificateName); diff --git a/src/Security/src/Authorization.Certificate/PostConfigureCertificateAuthenticationOptions.cs b/src/Security/src/Authorization.Certificate/PostConfigureCertificateAuthenticationOptions.cs index 837fbd8f90..086c879948 100644 --- a/src/Security/src/Authorization.Certificate/PostConfigureCertificateAuthenticationOptions.cs +++ b/src/Security/src/Authorization.Certificate/PostConfigureCertificateAuthenticationOptions.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Authentication.Certificate; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Certificates; using Steeltoe.Common.Configuration; @@ -21,8 +20,8 @@ internal sealed class PostConfigureCertificateAuthenticationOptions : IPostConfi public PostConfigureCertificateAuthenticationOptions(IOptionsMonitor certificateOptionsMonitor, ILogger logger) { - ArgumentGuard.NotNull(certificateOptionsMonitor); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(certificateOptionsMonitor); + ArgumentNullException.ThrowIfNull(logger); _certificateOptionsMonitor = certificateOptionsMonitor; _logger = logger; @@ -30,7 +29,7 @@ public PostConfigureCertificateAuthenticationOptions(IOptionsMonitor connectorFactory) { - ArgumentGuard.NotNull(connectorFactory); + ArgumentNullException.ThrowIfNull(connectorFactory); Connector connector = connectorFactory.Get(); IConnectionMultiplexer connectionMultiplexer = connector.GetConnection(); diff --git a/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs b/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs index 7c9e0ffe74..f4eeb79b22 100644 --- a/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs +++ b/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs @@ -9,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Connectors; using Steeltoe.Connectors.Redis; @@ -28,7 +27,7 @@ public static class RedisDataProtectionBuilderExtensions /// public static IDataProtectionBuilder PersistKeysToRedis(this IDataProtectionBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); builder.Services.TryAddSingleton(provider => { diff --git a/src/Steeltoe.All.sln.DotSettings b/src/Steeltoe.All.sln.DotSettings index 9e59c02144..7851075c3b 100644 --- a/src/Steeltoe.All.sln.DotSettings +++ b/src/Steeltoe.All.sln.DotSettings @@ -1,18 +1,7 @@  - // Use the following placeholders: -// $EXPR$ -- source expression -// $NAME$ -- source name (string literal or 'nameof' expression) -// $MESSAGE$ -- string literal in the form of "$NAME$ != null" -Steeltoe.Common.ArgumentGuard.NotNull($EXPR$); - 199 - 5000 - 99 - 100 - 200 - 1000 - 500 + 5000 + 2000 3000 - 50 False ExplicitlyExcluded ExplicitlyExcluded @@ -26,8 +15,7 @@ Steeltoe.Common.ArgumentGuard.NotNull($EXPR$); 2A975FB7-401B-41BB-96A4-1DF0036888A9 557AFE26-B89D-497D-92B6-8268D04396E5/d:HeapDump/d:DotNetHeapDump 557AFE26-B89D-497D-92B6-8268D04396E5/d:Metrics/d:SystemDiagnosticsMetrics - 5CC834D7-C501-4FEC-9244-E829584192FB/f:ConfigurationSchemaAttributes.cs - 5CC834D7-C501-4FEC-9244-E829584192FB/f:ConfigurationSchemaAttribute.cs + 61812938-5132-4AB6-B48D-2DF4189B3E37/f:ConfigurationSchemaAttributes.cs 7207D047-2F02-4946-9A3D-16928E62F37B/d:SystemDiagnosticsMetrics C4C38F83-8410-443C-9599-ACFB5FA7CD2D C4C38F83-8410-443C-9599-ACFB5FA7CD2D/f:ConfigurationSchemaAttributes.cs/l:..?..?..?Common?src?Abstractions?ConfigurationSchemaAttributes.cs @@ -630,7 +618,7 @@ See the LICENSE file in the project root for more information. True True True - Replace argument null check using throw expression with Guard clause + Replace argument null check using throw expression with ArgumentNullException.ThrowIfNull True True False @@ -650,12 +638,12 @@ See the LICENSE file in the project root for more information. CSHARP False Replace argument null check with Guard clause - Steeltoe.Common.ArgumentGuard.NotNull($argument$); + System.ArgumentNullException.ThrowIfNull($argument$); $left$ = $right$; $left$ = $right$ ?? throw new ArgumentNullException(nameof($argument$)); WARNING True - Replace argument == null check with Guard clause + Replace argument == null check with ArgumentNullException.ThrowIfNull True True False @@ -665,11 +653,11 @@ $left$ = $right$; CSHARP False Replace argument null check with Guard clause - Steeltoe.Common.ArgumentGuard.NotNull($argument$); + System.ArgumentNullException.ThrowIfNull($argument$); if ($argument$ == null) throw new ArgumentNullException(nameof($argument$)); WARNING True - Replace argument is null check with Guard clause + Replace argument is null check with ArgumentNullException.ThrowIfNull True True False @@ -678,7 +666,7 @@ $left$ = $right$; True CSHARP False - Steeltoe.Common.ArgumentGuard.NotNull($argument$); + System.ArgumentNullException.ThrowIfNull($argument$); if ($argument$ is null) throw new ArgumentNullException(nameof($argument$)); WARNING True From 18208c92b9076aa5e4902bc4adf0285e0e3efba4 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Mon, 5 Aug 2024 17:52:38 +0200 Subject: [PATCH 05/30] Enable more NRT in Common --- .../src/Hosting/HostBuilderContextWrapper.cs | 2 - src/Common/src/Hosting/HostBuilderWrapper.cs | 2 - .../Hosting/Steeltoe.Common.Hosting.csproj | 1 + .../src/Http/ConfigurationExtensions.cs | 2 - src/Common/src/Http/HttpClientExtensions.cs | 2 - ...tCertificateHttpClientHandlerConfigurer.cs | 4 +- .../HttpClientHandlerFactory.cs | 2 - .../IHttpClientHandlerConfigurer.cs | 2 - ...CertificatesHttpClientHandlerConfigurer.cs | 2 - .../Serialization/BoolStringJsonConverter.cs | 2 +- .../Serialization/LongStringJsonConverter.cs | 4 +- .../src/Http/Steeltoe.Common.Http.csproj | 1 + .../src/Logging/BootstrapLoggerFactory.cs | 2 + .../src/Logging/IBootstrapLoggerFactory.cs | 4 +- .../Logging/Steeltoe.Common.Logging.csproj | 1 + .../UpgradableBootstrapLoggerFactory.cs | 43 +++++++++--------- src/Common/src/Net/IMultipleProviderRouter.cs | 31 ++----------- src/Common/src/Net/MultipleProviderRouter.cs | 9 +--- src/Common/src/Net/NativeMethods.cs | 7 +-- src/Common/src/Net/Steeltoe.Common.Net.csproj | 1 + src/Common/src/Net/WindowsNetworkFileShare.cs | 44 +++++++----------- .../ApplicationInstanceInfoTest.cs | 23 +++++----- .../ConfigurationValuesHelperTest.cs | 2 - .../PropertyPlaceholderHelperTest.cs | 2 - .../Common.Test/Steeltoe.Common.Test.csproj | 1 + .../Steeltoe.Common.Hosting.Test.csproj | 1 + .../test/Hosting.Test/TestServerStartup.cs | 30 ------------- .../Http.Test/ConfigurationExtensionsTest.cs | 6 +-- .../Steeltoe.Common.Http.Test.csproj | 1 + .../BootstrapperLoggerFactoryTests.cs | 8 ++-- .../Steeltoe.Common.Logging.Test.csproj | 1 + .../Net.Test/FakeMultipleProviderRouter.cs | 45 ++++++++----------- .../Net.Test/Steeltoe.Common.Net.Test.csproj | 1 + .../Net.Test/WindowsNetworkFileShareTest.cs | 24 +++++----- 34 files changed, 112 insertions(+), 201 deletions(-) delete mode 100644 src/Common/test/Hosting.Test/TestServerStartup.cs diff --git a/src/Common/src/Hosting/HostBuilderContextWrapper.cs b/src/Common/src/Hosting/HostBuilderContextWrapper.cs index 177d1e1725..f177ee0f73 100644 --- a/src/Common/src/Hosting/HostBuilderContextWrapper.cs +++ b/src/Common/src/Hosting/HostBuilderContextWrapper.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; diff --git a/src/Common/src/Hosting/HostBuilderWrapper.cs b/src/Common/src/Hosting/HostBuilderWrapper.cs index e8a382ee79..6fc5ab5c83 100644 --- a/src/Common/src/Hosting/HostBuilderWrapper.cs +++ b/src/Common/src/Hosting/HostBuilderWrapper.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; diff --git a/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj b/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj index b8a439c232..d2ff0d2f40 100644 --- a/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj +++ b/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj @@ -4,6 +4,7 @@ Steeltoe library for common hosting-related utilities NET Core;Cloud Hosting; true + enable diff --git a/src/Common/src/Http/ConfigurationExtensions.cs b/src/Common/src/Http/ConfigurationExtensions.cs index fd23153019..db4447bb30 100644 --- a/src/Common/src/Http/ConfigurationExtensions.cs +++ b/src/Common/src/Http/ConfigurationExtensions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.Extensions.Configuration; namespace Steeltoe.Common.Http; diff --git a/src/Common/src/Http/HttpClientExtensions.cs b/src/Common/src/Http/HttpClientExtensions.cs index cd96f09dd5..fc9cf811ba 100644 --- a/src/Common/src/Http/HttpClientExtensions.cs +++ b/src/Common/src/Http/HttpClientExtensions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; diff --git a/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs b/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs index 1b0cb19797..92c57486cf 100644 --- a/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs +++ b/src/Common/src/Http/HttpClientPooling/ClientCertificateHttpClientHandlerConfigurer.cs @@ -14,7 +14,7 @@ namespace Steeltoe.Common.Http.HttpClientPooling; public sealed class ClientCertificateHttpClientHandlerConfigurer : IHttpClientHandlerConfigurer { private readonly IOptionsMonitor _optionsMonitor; - private string _clientCertificateName; + private string? _clientCertificateName; public ClientCertificateHttpClientHandlerConfigurer(IOptionsMonitor optionsMonitor) { @@ -32,7 +32,7 @@ public void Configure(HttpClientHandler handler) { ArgumentNullException.ThrowIfNull(handler); - X509Certificate2 certificate = _optionsMonitor.Get(_clientCertificateName).Certificate; + X509Certificate2? certificate = _optionsMonitor.Get(_clientCertificateName).Certificate; if (certificate != null) { diff --git a/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs b/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs index ce377d5fd0..1c921bd88f 100644 --- a/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs +++ b/src/Common/src/Http/HttpClientPooling/HttpClientHandlerFactory.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.Http.HttpClientPooling; /// diff --git a/src/Common/src/Http/HttpClientPooling/IHttpClientHandlerConfigurer.cs b/src/Common/src/Http/HttpClientPooling/IHttpClientHandlerConfigurer.cs index 7d13f0d605..c6f9328cdc 100644 --- a/src/Common/src/Http/HttpClientPooling/IHttpClientHandlerConfigurer.cs +++ b/src/Common/src/Http/HttpClientPooling/IHttpClientHandlerConfigurer.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.Http.HttpClientPooling; /// diff --git a/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs b/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs index af1a99d9e8..d2e8ef2dcc 100644 --- a/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs +++ b/src/Common/src/Http/HttpClientPooling/ValidateCertificatesHttpClientHandlerConfigurer.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.Extensions.Options; namespace Steeltoe.Common.Http.HttpClientPooling; diff --git a/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs b/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs index 58c7d092d2..2710afb50f 100644 --- a/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs +++ b/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs @@ -12,7 +12,7 @@ public sealed class BoolStringJsonConverter : JsonConverter { public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return reader.TokenType == JsonTokenType.False || reader.TokenType == JsonTokenType.True ? reader.GetBoolean() : bool.Parse(reader.GetString()); + return reader.TokenType is JsonTokenType.False or JsonTokenType.True ? reader.GetBoolean() : bool.Parse(reader.GetString()!); } public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) diff --git a/src/Common/src/Http/Serialization/LongStringJsonConverter.cs b/src/Common/src/Http/Serialization/LongStringJsonConverter.cs index b8d6e2062c..5423a3b5c2 100644 --- a/src/Common/src/Http/Serialization/LongStringJsonConverter.cs +++ b/src/Common/src/Http/Serialization/LongStringJsonConverter.cs @@ -8,11 +8,11 @@ namespace Steeltoe.Common.Http.Serialization; -public class LongStringJsonConverter : JsonConverter +public sealed class LongStringJsonConverter : JsonConverter { public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return reader.TokenType == JsonTokenType.Number ? reader.GetInt64() : long.Parse(reader.GetString(), CultureInfo.InvariantCulture); + return reader.TokenType == JsonTokenType.Number ? reader.GetInt64() : long.Parse(reader.GetString()!, CultureInfo.InvariantCulture); } public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options) diff --git a/src/Common/src/Http/Steeltoe.Common.Http.csproj b/src/Common/src/Http/Steeltoe.Common.Http.csproj index bc238e8810..c658be020e 100644 --- a/src/Common/src/Http/Steeltoe.Common.Http.csproj +++ b/src/Common/src/Http/Steeltoe.Common.Http.csproj @@ -4,6 +4,7 @@ Steeltoe common library for HTTP http; discovery; loadbalancing true + enable diff --git a/src/Common/src/Logging/BootstrapLoggerFactory.cs b/src/Common/src/Logging/BootstrapLoggerFactory.cs index a259eebd95..831a52fc4e 100644 --- a/src/Common/src/Logging/BootstrapLoggerFactory.cs +++ b/src/Common/src/Logging/BootstrapLoggerFactory.cs @@ -20,6 +20,8 @@ public static class BootstrapLoggerFactory public static IBootstrapLoggerFactory GetInstance(object contextKey) { + ArgumentNullException.ThrowIfNull(contextKey); + return InstanceMap.GetOrAdd(contextKey, _ => new UpgradableBootstrapLoggerFactory()); } } diff --git a/src/Common/src/Logging/IBootstrapLoggerFactory.cs b/src/Common/src/Logging/IBootstrapLoggerFactory.cs index 10e38f17e2..358bb0c4a7 100644 --- a/src/Common/src/Logging/IBootstrapLoggerFactory.cs +++ b/src/Common/src/Logging/IBootstrapLoggerFactory.cs @@ -9,7 +9,7 @@ namespace Steeltoe.Common.Logging; public interface IBootstrapLoggerFactory : ILoggerFactory { - void Update(IConfiguration value); + void Update(IConfiguration configuration); - void Update(ILoggerFactory value); + void Update(ILoggerFactory loggerFactory); } diff --git a/src/Common/src/Logging/Steeltoe.Common.Logging.csproj b/src/Common/src/Logging/Steeltoe.Common.Logging.csproj index 27472071a5..51950c3d72 100644 --- a/src/Common/src/Logging/Steeltoe.Common.Logging.csproj +++ b/src/Common/src/Logging/Steeltoe.Common.Logging.csproj @@ -4,6 +4,7 @@ Steeltoe library for common logging-related utilities logging true + enable diff --git a/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs b/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs index 8c2d36699f..2afb3a179a 100644 --- a/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs +++ b/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs @@ -14,15 +14,12 @@ namespace Steeltoe.Common.Logging; /// internal sealed class UpgradableBootstrapLoggerFactory : IBootstrapLoggerFactory { - private readonly Dictionary _loggers = new(); - + private readonly Dictionary _loggersByCategoryName = new(); private readonly object _lock = new(); - private readonly Action _bootstrapLoggingBuilder; private ILoggerFactory _factoryInstance; - - private ILoggerFactory _factory; + private ILoggerFactory? _factory; public UpgradableBootstrapLoggerFactory() : this(DefaultConfigure) @@ -35,7 +32,7 @@ public UpgradableBootstrapLoggerFactory(Action _factoryInstance = LoggerFactory.Create(builder => { - IConfigurationRoot configurationRoot = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + IConfigurationRoot configurationRoot = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { { "Logging:LogLevel:Default", "Information" }, { "Logging:LogLevel:Microsoft", "Warning" }, @@ -49,25 +46,27 @@ public UpgradableBootstrapLoggerFactory(Action /// /// Updates existing loggers to use configuration from the supplied configuration. /// - public void Update(IConfiguration value) + public void Update(IConfiguration configuration) { - ArgumentNullException.ThrowIfNull(value); + ArgumentNullException.ThrowIfNull(configuration); if (_factory != null) { return; } - ILoggerFactory newLogger = LoggerFactory.Create(builder => _bootstrapLoggingBuilder(builder, value)); + ILoggerFactory newLogger = LoggerFactory.Create(builder => _bootstrapLoggingBuilder(builder, configuration)); Update(newLogger); } /// /// Updates existing loggers to use final LoggerFactory as constructed by IoC container. /// - public void Update(ILoggerFactory value) + public void Update(ILoggerFactory loggerFactory) { - if (value == null || value == _factoryInstance) + ArgumentNullException.ThrowIfNull(loggerFactory); + + if (loggerFactory == _factoryInstance) { return; } @@ -75,15 +74,15 @@ public void Update(ILoggerFactory value) lock (_lock) { _factoryInstance.Dispose(); - _factoryInstance = value; + _factoryInstance = loggerFactory; - foreach (BootstrapLoggerInst logger in _loggers.Values) + foreach (BootstrapLoggerInstance logger in _loggersByCategoryName.Values) { logger.Logger = _factoryInstance.CreateLogger(logger.Name); } } - _factory = value; + _factory = loggerFactory; } public void Dispose() @@ -106,11 +105,11 @@ public ILogger CreateLogger(string categoryName) { lock (_lock) { - if (!_loggers.TryGetValue(categoryName, out BootstrapLoggerInst logger)) + if (!_loggersByCategoryName.TryGetValue(categoryName, out BootstrapLoggerInstance? logger)) { ILogger innerLogger = _factoryInstance.CreateLogger(categoryName); - logger = new BootstrapLoggerInst(innerLogger, categoryName); - _loggers.Add(categoryName, logger); + logger = new BootstrapLoggerInstance(innerLogger, categoryName); + _loggersByCategoryName.Add(categoryName, logger); } return logger; @@ -122,19 +121,19 @@ private static void DefaultConfigure(ILoggingBuilder builder, IConfiguration con builder.AddConsole().AddConfiguration(configuration.GetSection("Logging")); } - internal sealed class BootstrapLoggerInst : ILogger + private sealed class BootstrapLoggerInstance : ILogger { public volatile ILogger Logger; - public string Name { get; } - public BootstrapLoggerInst(ILogger logger, string name) + public BootstrapLoggerInstance(ILogger logger, string name) { Name = name; Logger = logger; } - public IDisposable BeginScope(TState state) + public IDisposable? BeginScope(TState state) + where TState : notnull { return Logger.BeginScope(state); } @@ -144,7 +143,7 @@ public bool IsEnabled(LogLevel logLevel) return Logger.IsEnabled(logLevel); } - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { Logger.Log(logLevel, eventId, state, exception, formatter); } diff --git a/src/Common/src/Net/IMultipleProviderRouter.cs b/src/Common/src/Net/IMultipleProviderRouter.cs index 600f36a7f5..39cf5b4f21 100644 --- a/src/Common/src/Net/IMultipleProviderRouter.cs +++ b/src/Common/src/Net/IMultipleProviderRouter.cs @@ -6,6 +6,7 @@ using static Steeltoe.Common.Net.WindowsNetworkFileShare; #pragma warning disable S3874 // "out" and "ref" parameters should not be used +#pragma warning disable S107 // Methods should not have too many parameters namespace Steeltoe.Common.Net; @@ -14,31 +15,6 @@ namespace Steeltoe.Common.Net; /// public interface IMultipleProviderRouter { - /// - /// Makes a connection to a network resource and can redirect a local device to the network resource. - /// - /// P/Invoke call to mpr.dll. - /// - /// - /// Network resource to interact with. - /// - /// - /// Password for making the network connection. - /// - /// - /// Username for making the network connection. - /// - /// - /// A set of connection options. - /// - /// - /// - /// An integer representing the result. - /// - /// - int AddConnection(NetResource netResource, string password, string username, int flags); - -#pragma warning disable S107 // Methods should not have too many parameters /// /// Makes a connection to a network resource. Can redirect a local device to a network resource. /// @@ -74,9 +50,8 @@ public interface IMultipleProviderRouter /// An integer representing the result. /// /// - int UseConnection(IntPtr hwndOwner, NetResource netResource, string password, string username, int flags, string lpAccessName, string lpBufferSize, - string lpResult); -#pragma warning restore S107 // Methods should not have too many parameters + int UseConnection(IntPtr hwndOwner, NetResource netResource, string? password, string? username, int flags, string? lpAccessName, string? lpBufferSize, + string? lpResult); /// /// Cancels an existing network connection, removes remembered network connections that are not currently connected. diff --git a/src/Common/src/Net/MultipleProviderRouter.cs b/src/Common/src/Net/MultipleProviderRouter.cs index c1aa3fb119..9b2d247cef 100644 --- a/src/Common/src/Net/MultipleProviderRouter.cs +++ b/src/Common/src/Net/MultipleProviderRouter.cs @@ -17,13 +17,8 @@ public MultipleProviderRouter() } } - public int AddConnection(NetResource netResource, string password, string username, int flags) - { - return NativeMethods.WNetAddConnection2(netResource, password, username, flags); - } - - public int UseConnection(IntPtr hwndOwner, NetResource netResource, string password, string username, int flags, string lpAccessName, string lpBufferSize, - string lpResult) + public int UseConnection(IntPtr hwndOwner, NetResource netResource, string? password, string? username, int flags, string? lpAccessName, + string? lpBufferSize, string? lpResult) { return NativeMethods.WNetUseConnection(hwndOwner, netResource, password, username, flags, lpAccessName, lpBufferSize, lpResult); } diff --git a/src/Common/src/Net/NativeMethods.cs b/src/Common/src/Net/NativeMethods.cs index a4a3b3d0de..6fcc383706 100644 --- a/src/Common/src/Net/NativeMethods.cs +++ b/src/Common/src/Net/NativeMethods.cs @@ -11,15 +11,12 @@ namespace Steeltoe.Common.Net; internal static class NativeMethods { [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags); + internal static extern int WNetUseConnection(IntPtr hwndOwner, NetResource netResource, string? password, string? username, int flags, string? lpAccessName, + string? lpBufferSize, string? lpResult); [DllImport("mpr.dll", CharSet = CharSet.Unicode)] internal static extern int WNetCancelConnection2(string name, int flags, bool force); - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetUseConnection(IntPtr hwndOwner, NetResource netResource, string password, string username, int flags, string lpAccessName, - string lpBufferSize, string lpResult); - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] internal static extern int WNetGetLastError(out int error, out StringBuilder errorBuf, int errorBufSize, out StringBuilder nameBuf, int nameBufSize); } diff --git a/src/Common/src/Net/Steeltoe.Common.Net.csproj b/src/Common/src/Net/Steeltoe.Common.Net.csproj index d0b2ca36d4..de82f6394d 100644 --- a/src/Common/src/Net/Steeltoe.Common.Net.csproj +++ b/src/Common/src/Net/Steeltoe.Common.Net.csproj @@ -4,6 +4,7 @@ Steeltoe common library for network interaction Windows-file-sharing; network-file-system true + enable diff --git a/src/Common/src/Net/WindowsNetworkFileShare.cs b/src/Common/src/Net/WindowsNetworkFileShare.cs index edd2528e4a..7980c523ab 100644 --- a/src/Common/src/Net/WindowsNetworkFileShare.cs +++ b/src/Common/src/Net/WindowsNetworkFileShare.cs @@ -13,7 +13,7 @@ namespace Steeltoe.Common.Net; /// /// For interacting with SMB network file shares on Windows. /// -public class WindowsNetworkFileShare : IDisposable +public sealed class WindowsNetworkFileShare : IDisposable { // private const int NO_ERROR = 0 private const int ErrorAccessDenied = 5; @@ -83,11 +83,13 @@ public class WindowsNetworkFileShare : IDisposable /// /// A class that handles calls to mpr.dll or performs same operations. /// - public WindowsNetworkFileShare(string networkName, NetworkCredential credentials, IMultipleProviderRouter multipleProviderRouter = null) + public WindowsNetworkFileShare(string networkName, NetworkCredential credentials, IMultipleProviderRouter? multipleProviderRouter = null) { - _multipleProviderRouter = multipleProviderRouter ?? new MultipleProviderRouter(); + ArgumentNullException.ThrowIfNull(networkName); + ArgumentNullException.ThrowIfNull(credentials); _networkName = networkName; + _multipleProviderRouter = multipleProviderRouter ?? new MultipleProviderRouter(); var netResource = new NetResource { @@ -138,11 +140,15 @@ public int GetLastError(out int error, out StringBuilder errorBuf, int errorBufS return _multipleProviderRouter.GetLastError(out error, out errorBuf, errorBufSize, out nameBuf, nameBufSize); } - /// + /// + /// Disconnects the file share. + /// public void Dispose() { - Dispose(true); - GC.SuppressFinalize(this); + // With the current design, it's not possible to disconnect the network share from the finalizer, + // because the _multipleProviderRouter instance may have already been garbage-collected. + + _multipleProviderRouter.CancelConnection(_networkName, 0, true); } /// @@ -164,22 +170,6 @@ internal static string GetErrorForNumber(int errNum) return ErrorList.First(e => e.Num == errNum).Message; } - /// - /// Disposes the object, cancels connection with file share. - /// - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - /// - protected virtual void Dispose(bool disposing) - { - // With the current design, it's not possible to disconnect the network share from the finalizer, - // because the _mpr instance may have already been garbage-collected. - if (disposing) - { - _multipleProviderRouter.CancelConnection(_networkName, 0, true); - } - } - /// /// Scope of the file share. /// @@ -233,15 +223,15 @@ private record struct ErrorClass(int Num, string Message) /// . /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public class NetResource + public sealed class NetResource { public ResourceScope Scope; public ResourceType ResourceType; public ResourceDisplayType DisplayType; public int Usage; - public string LocalName; - public string RemoteName; - public string Comment; - public string Provider; + public string? LocalName; + public string? RemoteName; + public string? Comment; + public string? Provider; } } diff --git a/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs b/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs index 5f22997535..9aa9c9bd08 100644 --- a/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs +++ b/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs @@ -18,7 +18,7 @@ public void ConstructorSetsDefaults() var options = new ApplicationInstanceInfo(configurationRoot, true); Assert.Null(options.ApplicationId); - Assert.Equal(Assembly.GetEntryAssembly().GetName().Name, options.ApplicationName); + Assert.Equal(Assembly.GetEntryAssembly()!.GetName().Name, options.ApplicationName); Assert.Null(options.ApplicationVersion); Assert.Null(options.InstanceId); Assert.Equal(-1, options.InstanceIndex); @@ -36,22 +36,23 @@ public void ConstructorSetsDefaults() [Fact] public void ConstructorReadsApplicationConfiguration() { - const string configJson = @" + const string configJson = """ { - ""Application"" : { - ""Name"": ""my-app"", - ""ApplicationId"": ""fa05c1a9-0fc1-4fbd-bae1-139850dec7a3"", - ""Uris"": [ - ""my-app.10.244.0.34.xip.io"", - ""my-app2.10.244.0.34.xip.io"" + "Application" : { + "Name": "my-app", + "ApplicationId": "fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", + "Uris": [ + "my-app.10.244.0.34.xip.io", + "my-app2.10.244.0.34.xip.io" ], - ""Version"": ""fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca"" + "Version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca" } - }"; + } + """; using var sandbox = new Sandbox(); string path = sandbox.CreateFile("appsettings.json", configJson); - string directory = Path.GetDirectoryName(path); + string directory = Path.GetDirectoryName(path)!; string fileName = Path.GetFileName(path); var builder = new ConfigurationBuilder(); builder.SetBasePath(directory); diff --git a/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs b/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs index f1ecb85e52..8e24324a19 100644 --- a/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs +++ b/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.Extensions.Configuration; using Steeltoe.Common.Configuration; diff --git a/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs b/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs index 334f35cea6..58f2955258 100644 --- a/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs +++ b/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Steeltoe.Common.Configuration; diff --git a/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj b/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj index a466bce300..774ca0666a 100644 --- a/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj +++ b/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj @@ -1,6 +1,7 @@ net8.0 + enable diff --git a/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj b/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj index fa458da51f..f8a54d2c77 100644 --- a/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj +++ b/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj @@ -1,6 +1,7 @@ net8.0 + enable diff --git a/src/Common/test/Hosting.Test/TestServerStartup.cs b/src/Common/test/Hosting.Test/TestServerStartup.cs deleted file mode 100644 index 1a8da3df0f..0000000000 --- a/src/Common/test/Hosting.Test/TestServerStartup.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. - -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting.Server.Features; -using Microsoft.Extensions.DependencyInjection; - -namespace Steeltoe.Common.Hosting.Test; - -public sealed class TestServerStartup -{ - public List ExpectedAddresses { get; private set; } - - public TestServerStartup() - { - ExpectedAddresses = new List(); - } - - public void ConfigureServices(IServiceCollection services) - { - } - - public void Configure(IApplicationBuilder app) - { - List addresses = ExpectedAddresses; - Assert.Equal(addresses, app.ServerFeatures.Get()?.Addresses); - ExpectedAddresses = null; - } -} diff --git a/src/Common/test/Http.Test/ConfigurationExtensionsTest.cs b/src/Common/test/Http.Test/ConfigurationExtensionsTest.cs index 39664b2b1f..6b75d3c591 100644 --- a/src/Common/test/Http.Test/ConfigurationExtensionsTest.cs +++ b/src/Common/test/Http.Test/ConfigurationExtensionsTest.cs @@ -31,7 +31,7 @@ public void Detects_addresses_from_UseUrls() [Fact] public void Detects_URLS_in_configuration() { - var appSettings = new Dictionary + var appSettings = new Dictionary { ["urls"] = "http://localhost:8888;https://127.0.0.1:9999" }; @@ -51,7 +51,7 @@ public void Detects_URLS_in_configuration() [Fact] public void Detects_PORTS_in_configuration() { - var appSettings = new Dictionary + var appSettings = new Dictionary { ["http_ports"] = "5555", ["https_ports"] = "6666" @@ -72,7 +72,7 @@ public void Detects_PORTS_in_configuration() [Fact] public void Ignores_PORTS_when_URLS_present_in_configuration() { - var appSettings = new Dictionary + var appSettings = new Dictionary { ["urls"] = "http://[::1]:8888;https://192.168.1.1:9999", ["http_ports"] = "5555", diff --git a/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj b/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj index 725845961e..79194e8ab9 100644 --- a/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj +++ b/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj @@ -1,6 +1,7 @@ net8.0 + enable diff --git a/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTests.cs b/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTests.cs index d07dcb9a69..7b4be9bedc 100644 --- a/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTests.cs +++ b/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTests.cs @@ -41,10 +41,10 @@ public void UpgradableBootLogger() mockLogger.Verify(x => x.Log(LogLevel.Information, It.IsAny(), It.Is((o, t) => string.Equals("Test", o.ToString(), StringComparison.OrdinalIgnoreCase)), It.IsAny(), - It.Is>((v, t) => true))); + It.Is>((v, t) => true))); // test change to log levels after updated with configuration - IConfigurationRoot configurationRoot = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + IConfigurationRoot configurationRoot = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { { "Logging:LogLevel:Default", nameof(LogLevel.Warning) } }).Build(); @@ -55,7 +55,7 @@ public void UpgradableBootLogger() mockLogger.Verify( x => x.Log(LogLevel.Information, It.IsAny(), It.Is((o, t) => string.Equals("Test2", o.ToString(), StringComparison.OrdinalIgnoreCase)), It.IsAny(), - It.Is>((v, t) => true)), Times.Never); + It.Is>((v, t) => true)), Times.Never); // upgrade bootstrapper with new log factory, and confirm that it delegates to loggers spawned from it var newLogProvider = new Mock(); @@ -69,6 +69,6 @@ public void UpgradableBootLogger() newMockLogger.Verify( x => x.Log(LogLevel.Information, It.IsAny(), It.Is((o, t) => string.Equals("Test3", o.ToString(), StringComparison.OrdinalIgnoreCase)), It.IsAny(), - It.Is>((v, t) => true)), Times.Never); + It.Is>((v, t) => true)), Times.Never); } } diff --git a/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj b/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj index fbfe9daa8a..900c80c1fb 100644 --- a/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj +++ b/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj @@ -1,6 +1,7 @@ net8.0 + enable diff --git a/src/Common/test/Net.Test/FakeMultipleProviderRouter.cs b/src/Common/test/Net.Test/FakeMultipleProviderRouter.cs index 6d8225cbdb..34bb7ea7cc 100644 --- a/src/Common/test/Net.Test/FakeMultipleProviderRouter.cs +++ b/src/Common/test/Net.Test/FakeMultipleProviderRouter.cs @@ -6,41 +6,22 @@ namespace Steeltoe.Common.Net.Test; -internal sealed class FakeMultipleProviderRouter : IMultipleProviderRouter +internal sealed class FakeMultipleProviderRouter(bool shouldConnect = true) : IMultipleProviderRouter { - internal string Username { get; private set; } - internal string Password { get; private set; } - internal string NetworkPath { get; private set; } - internal bool ShouldConnect { get; } + private readonly bool _shouldConnect = shouldConnect; - public FakeMultipleProviderRouter(bool shouldConnect = true) - { - ShouldConnect = shouldConnect; - } - - public int AddConnection(WindowsNetworkFileShare.NetResource netResource, string password, string username, int flags) - { - throw new NotImplementedException(); - } - - public int CancelConnection(string name, int flags, bool force) - { - return -1; - } - - public int GetLastError(out int error, out StringBuilder errorBuf, int errorBufSize, out StringBuilder nameBuf, int nameBufSize) - { - throw new NotImplementedException(); - } + internal string? Username { get; private set; } + internal string? Password { get; private set; } + internal string? NetworkPath { get; private set; } - public int UseConnection(IntPtr hwndOwner, WindowsNetworkFileShare.NetResource netResource, string password, string username, int flags, - string lpAccessName, string lpBufferSize, string lpResult) + public int UseConnection(IntPtr hwndOwner, WindowsNetworkFileShare.NetResource netResource, string? password, string? username, int flags, + string? lpAccessName, string? lpBufferSize, string? lpResult) { NetworkPath = netResource.RemoteName; Username = username; Password = password; - if (ShouldConnect) + if (_shouldConnect) { return 0; } @@ -48,4 +29,14 @@ public int UseConnection(IntPtr hwndOwner, WindowsNetworkFileShare.NetResource n // throw "bad device" error return 1200; } + + public int CancelConnection(string name, int flags, bool force) + { + return -1; + } + + public int GetLastError(out int error, out StringBuilder errorBuf, int errorBufSize, out StringBuilder nameBuf, int nameBufSize) + { + throw new NotImplementedException(); + } } diff --git a/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj b/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj index 723bcb6e1f..c321980aca 100644 --- a/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj +++ b/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj @@ -1,6 +1,7 @@ net8.0 + enable diff --git a/src/Common/test/Net.Test/WindowsNetworkFileShareTest.cs b/src/Common/test/Net.Test/WindowsNetworkFileShareTest.cs index cf2e16a1c1..0024cba8e9 100644 --- a/src/Common/test/Net.Test/WindowsNetworkFileShareTest.cs +++ b/src/Common/test/Net.Test/WindowsNetworkFileShareTest.cs @@ -25,34 +25,34 @@ public void GetErrorForUnknownNumber_ReturnsUnKnownError() [Fact] public void WindowsNetworkFileShare_Constructor_SetsValuesOn_ConnectSuccess() { - var fakeMpr = new FakeMultipleProviderRouter(); + var router = new FakeMultipleProviderRouter(); - _ = new WindowsNetworkFileShare(@"\\server\path", new NetworkCredential("user", "password"), fakeMpr); + _ = new WindowsNetworkFileShare(@"\\server\path", new NetworkCredential("user", "password"), router); - Assert.Equal("user", fakeMpr.Username); - Assert.Equal("password", fakeMpr.Password); - Assert.Equal(@"\\server\path", fakeMpr.NetworkPath); + Assert.Equal("user", router.Username); + Assert.Equal("password", router.Password); + Assert.Equal(@"\\server\path", router.NetworkPath); } [Fact] public void WindowsNetworkFileShare_Constructor_ConcatenatesUserAndDomain() { - var fakeMpr = new FakeMultipleProviderRouter(); + var router = new FakeMultipleProviderRouter(); - _ = new WindowsNetworkFileShare(@"\\server\path", new NetworkCredential("user", "password", "domain"), fakeMpr); + _ = new WindowsNetworkFileShare(@"\\server\path", new NetworkCredential("user", "password", "domain"), router); - Assert.Equal(@"domain\user", fakeMpr.Username); - Assert.Equal("password", fakeMpr.Password); - Assert.Equal(@"\\server\path", fakeMpr.NetworkPath); + Assert.Equal(@"domain\user", router.Username); + Assert.Equal("password", router.Password); + Assert.Equal(@"\\server\path", router.NetworkPath); } [Fact] public void WindowsNetworkFileShare_Constructor_ThrowsOn_ConnectFail() { - var fakeMpr = new FakeMultipleProviderRouter(false); + var router = new FakeMultipleProviderRouter(false); var exception = Assert.Throws(() => - new WindowsNetworkFileShare("doesn't-matter", new NetworkCredential("user", "password"), fakeMpr)); + new WindowsNetworkFileShare("doesn't-matter", new NetworkCredential("user", "password"), router)); Assert.Equal("Error connecting to remote share - Code: 1200, Error: Bad Device", exception.Message); } From 2ce20950df29957c4141d7e69db5a3bb3e909448 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Wed, 7 Aug 2024 09:08:30 +0200 Subject: [PATCH 06/30] IApplicationInstanceInfo: Remove unused code --- .../src/Common/ApplicationInstanceInfo.cs | 19 ++--------- .../Extensions/ServiceCollectionExtensions.cs | 5 ++- .../Extensions/ServiceProviderExtensions.cs | 33 ------------------- src/Common/src/Common/SteeltoeComponent.cs | 6 +--- .../CloudFoundryApplicationOptions.cs | 1 + ...CloudFoundryServiceCollectionExtensions.cs | 18 +++------- .../CloudFoundryHostBuilderExtensionsTest.cs | 3 +- 7 files changed, 14 insertions(+), 71 deletions(-) delete mode 100644 src/Common/src/Common/Extensions/ServiceProviderExtensions.cs diff --git a/src/Common/src/Common/ApplicationInstanceInfo.cs b/src/Common/src/Common/ApplicationInstanceInfo.cs index 02f083bd0d..1e80f5db6a 100644 --- a/src/Common/src/Common/ApplicationInstanceInfo.cs +++ b/src/Common/src/Common/ApplicationInstanceInfo.cs @@ -12,31 +12,24 @@ public class ApplicationInstanceInfo : IApplicationInstanceInfo { public const string ApplicationRoot = "application"; public const string SpringApplicationRoot = "spring:application"; - public const string ServicesRoot = "services"; public const string EurekaRoot = "eureka"; - public const string ConfigServerRoot = "spring:cloud:config"; public const string ConsulRoot = "consul"; - public const string KubernetesRoot = "spring:cloud:kubernetes"; public const string ManagementRoot = "management"; protected IConfiguration Configuration { get; set; } protected virtual string PlatformRoot => string.Empty; - public string DefaultAppName => Assembly.GetEntryAssembly().GetName().Name; + public string DefaultAppName => Assembly.GetEntryAssembly()!.GetName().Name; public string AppNameKey => $"{SpringApplicationRoot}:name"; public string AppInstanceIdKey => $"{SpringApplicationRoot}:instance_id"; - public string ConfigServerNameKey => $"{ConfigServerRoot}:name"; - public string ConsulInstanceNameKey => $"{ConsulRoot}:serviceName"; public string EurekaInstanceNameKey => $"{EurekaRoot}:instance:appName"; - public string KubernetesNameKey => $"{KubernetesRoot}:name"; - public string ManagementNameKey => $"{ManagementRoot}:name"; public string PlatformNameKey => BuildConfigString(PlatformRoot, $"{ApplicationRoot}:name"); @@ -65,10 +58,6 @@ public virtual string ApplicationId public virtual string ApplicationVersion { get; set; } - public virtual string EnvironmentName { get; set; } = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")) - ? "Production" - : Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); - public virtual int InstanceIndex { get; set; } = -1; public int Port { get; set; } = -1; @@ -140,15 +129,11 @@ public string GetApplicationNameInContext(SteeltoeComponent component, string ad { return component switch { - SteeltoeComponent.Configuration => ConfigurationValuesHelper.GetPreferredSetting(Configuration, DefaultAppName, additionalSearchPath, - ConfigServerNameKey, PlatformNameKey, AppNameKey), SteeltoeComponent.Discovery => ConfigurationValuesHelper.GetPreferredSetting(Configuration, DefaultAppName, additionalSearchPath, EurekaInstanceNameKey, ConsulInstanceNameKey, PlatformNameKey, AppNameKey), - SteeltoeComponent.Kubernetes => ConfigurationValuesHelper.GetPreferredSetting(Configuration, DefaultAppName, additionalSearchPath, - KubernetesNameKey, PlatformNameKey, AppNameKey), SteeltoeComponent.Management => ConfigurationValuesHelper.GetPreferredSetting(Configuration, DefaultAppName, additionalSearchPath, ManagementNameKey, PlatformNameKey, AppNameKey), - _ => ConfigurationValuesHelper.GetPreferredSetting(Configuration, DefaultAppName, additionalSearchPath, PlatformNameKey, AppNameKey) + _ => throw new NotSupportedException($"Unknown component '{component}'.") }; } } diff --git a/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs index 8214c4213d..e95110e424 100644 --- a/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs +++ b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs @@ -21,6 +21,9 @@ internal static class ServiceCollectionExtensions public static void RegisterDefaultApplicationInstanceInfo(this IServiceCollection services) { services.TryAddSingleton(serviceProvider => - new ApplicationInstanceInfo(serviceProvider.GetRequiredService(), true)); + { + var configuration = serviceProvider.GetRequiredService(); + return new ApplicationInstanceInfo(configuration, true); + }); } } diff --git a/src/Common/src/Common/Extensions/ServiceProviderExtensions.cs b/src/Common/src/Common/Extensions/ServiceProviderExtensions.cs deleted file mode 100644 index c5aba0f5f7..0000000000 --- a/src/Common/src/Common/Extensions/ServiceProviderExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; - -namespace Steeltoe.Common.Extensions; - -internal static class ServiceProviderExtensions -{ - /// - /// If an instance of is found, it is returned. Otherwise, a default instance is returned. - /// - /// - /// Provider of services. - /// - /// - /// An instance of . - /// - public static IApplicationInstanceInfo GetApplicationInstanceInfo(this IServiceProvider sp) - { - var appInfo = sp.GetService(); - - if (appInfo == null) - { - var configuration = sp.GetRequiredService(); - appInfo = new ApplicationInstanceInfo(configuration, string.Empty); - } - - return appInfo; - } -} diff --git a/src/Common/src/Common/SteeltoeComponent.cs b/src/Common/src/Common/SteeltoeComponent.cs index 5458c3c21b..c5bd4dd166 100644 --- a/src/Common/src/Common/SteeltoeComponent.cs +++ b/src/Common/src/Common/SteeltoeComponent.cs @@ -7,9 +7,5 @@ namespace Steeltoe.Common; public enum SteeltoeComponent { Discovery, - Configuration, - Connectors, - Kubernetes, - Management, - Security + Management } diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs index 0c93696e3b..e957f2ec3e 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs @@ -7,6 +7,7 @@ namespace Steeltoe.Configuration.CloudFoundry; +// See https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html#VCAP-APPLICATION public sealed class CloudFoundryApplicationOptions : ApplicationInstanceInfo { internal const string PlatformConfigurationRoot = "vcap"; diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs index fe8d653bc6..7140be0b12 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry; @@ -121,20 +122,11 @@ public static IServiceCollection RegisterCloudFoundryApplicationInstanceInfo(thi { ArgumentNullException.ThrowIfNull(services); - ServiceDescriptor? appInfoDescriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IApplicationInstanceInfo)); - - if (appInfoDescriptor?.ImplementationType?.IsAssignableFrom(typeof(CloudFoundryApplicationOptions)) != true) + services.Replace(ServiceDescriptor.Singleton(serviceProvider => { - if (appInfoDescriptor != null) - { - services.Remove(appInfoDescriptor); - } - - services.AddSingleton(typeof(CloudFoundryApplicationOptions), - serviceProvider => new CloudFoundryApplicationOptions(serviceProvider.GetRequiredService())); - - services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService()); - } + var configuration = serviceProvider.GetRequiredService(); + return new CloudFoundryApplicationOptions(configuration); + })); return services; } diff --git a/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs b/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs index 0c90709f53..36253e640d 100644 --- a/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs +++ b/src/Configuration/test/CloudFoundry.Test/CloudFoundryHostBuilderExtensionsTest.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Steeltoe.Common; -using Steeltoe.Common.Extensions; using Steeltoe.Common.TestResources; namespace Steeltoe.Configuration.CloudFoundry.Test; @@ -22,7 +21,7 @@ public void HostAddCloudFoundryConfiguration_Adds() hostbuilder.AddCloudFoundryConfiguration(); IHost host = hostbuilder.Build(); - IApplicationInstanceInfo instanceInfo = host.Services.GetApplicationInstanceInfo(); + var instanceInfo = host.Services.GetRequiredService(); Assert.IsAssignableFrom(instanceInfo); var configurationRoot = (IConfigurationRoot)host.Services.GetRequiredService(); Assert.Contains(configurationRoot.Providers, provider => provider is CloudFoundryConfigurationProvider); From 429e6cabb431f1849fe6c65403b108f6b06214be Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Thu, 8 Aug 2024 11:24:49 +0200 Subject: [PATCH 07/30] Remove ConfigureReloadableOptions (same as OptionsBuilder.BindConfiguration) --- .../ConfigurationOptionsBinder.cs | 57 ------------------- ...onfigurationServiceCollectionExtensions.cs | 3 +- .../ConsulServiceCollectionExtensions.cs | 12 ++-- .../EurekaServiceCollectionExtensions.cs | 10 ++-- ...PostConfigureConsulDiscoveryOptionsTest.cs | 7 +-- .../PostConfigureEurekaInstanceOptionsTest.cs | 3 +- 6 files changed, 18 insertions(+), 74 deletions(-) delete mode 100644 src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs diff --git a/src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs b/src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs deleted file mode 100644 index 7869ad4e6c..0000000000 --- a/src/Common/src/Common/Configuration/ConfigurationOptionsBinder.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. - -#nullable enable - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Options; - -namespace Steeltoe.Common.Configuration; - -internal static class ConfigurationOptionsBinder -{ - /// - /// Binds against a configuration key and registers for change detection, so that - /// always returns the latest value. This method exists so that callers don't need to pass - /// to set this up. - /// - /// - /// The type of options to bind against configuration. - /// - /// - /// The to add services to. - /// - /// - /// The configuration key to bind from. - /// - /// - /// An optional action for additional configuration of . - /// - public static void ConfigureReloadableOptions(this IServiceCollection services, string configurationKey, - Action? configureAction = null) - where TOptions : class - { - ArgumentNullException.ThrowIfNull(services); - ArgumentException.ThrowIfNullOrEmpty(configurationKey); - - OptionsBuilder builder = services.AddOptions(); - - builder.Configure((options, serviceProvider) => - { - var configuration = serviceProvider.GetRequiredService(); - IConfigurationSection section = configuration.GetSection(configurationKey); - section.Bind(options); - - configureAction?.Invoke(options, serviceProvider); - }); - - services.AddSingleton>(serviceProvider => - { - var configuration = serviceProvider.GetRequiredService(); - IConfigurationSection section = configuration.GetSection(configurationKey); - return new ConfigurationChangeTokenSource(section); - }); - } -} diff --git a/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs b/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs index 28decc1503..6f73d7505a 100644 --- a/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs +++ b/src/Discovery/src/Configuration/ConfigurationServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; namespace Steeltoe.Discovery.Configuration; @@ -47,7 +46,7 @@ public static IServiceCollection AddConfigurationDiscoveryClient(this IServiceCo { ArgumentNullException.ThrowIfNull(services); - services.ConfigureReloadableOptions(ConfigurationDiscoveryOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(ConfigurationDiscoveryOptions.ConfigurationPrefix); services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IDiscoveryClient), typeof(ConfigurationDiscoveryClient))); services.AddHostedService(); diff --git a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs index e3d7148721..4849921b9f 100644 --- a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs +++ b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Steeltoe.Common; -using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -44,17 +43,22 @@ private static void ConfigureConsulServices(IServiceCollection services) ConfigureConsulOptions(services); ConfigureConsulDiscoveryOptions(services); + + services.AddOptions().BindConfiguration(InetOptions.ConfigurationPrefix); } private static void ConfigureConsulOptions(IServiceCollection services) { - services.ConfigureReloadableOptions(ConsulOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(ConsulOptions.ConfigurationPrefix); services.AddSingleton, ValidateConsulOptions>(); } private static void ConfigureConsulDiscoveryOptions(IServiceCollection services) { - services.ConfigureReloadableOptions(ConsulDiscoveryOptions.ConfigurationPrefix, (options, serviceProvider) => + OptionsBuilder optionsBuilder = services.AddOptions(); + optionsBuilder.BindConfiguration(ConsulDiscoveryOptions.ConfigurationPrefix); + + optionsBuilder.Configure((options, serviceProvider) => { var configuration = serviceProvider.GetRequiredService(); @@ -66,8 +70,6 @@ private static void ConfigureConsulDiscoveryOptions(IServiceCollection services) } }); - services.ConfigureReloadableOptions(InetOptions.ConfigurationPrefix); - services.AddSingleton, PostConfigureConsulDiscoveryOptions>(); } diff --git a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs index ac3fd0ca9b..08eaa40c66 100644 --- a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs +++ b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Steeltoe.Common.Certificates; -using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -51,7 +50,10 @@ private static void ConfigureEurekaServices(IServiceCollection services) private static void ConfigureEurekaClientOptions(IServiceCollection services) { - services.ConfigureReloadableOptions(EurekaClientOptions.ConfigurationPrefix, (options, serviceProvider) => + OptionsBuilder optionsBuilder = services.AddOptions(); + optionsBuilder.BindConfiguration(EurekaClientOptions.ConfigurationPrefix); + + optionsBuilder.Configure((options, serviceProvider) => { var configuration = serviceProvider.GetRequiredService(); @@ -68,8 +70,8 @@ private static void ConfigureEurekaClientOptions(IServiceCollection services) private static void ConfigureEurekaInstanceOptions(IServiceCollection services) { - services.ConfigureReloadableOptions(EurekaInstanceOptions.ConfigurationPrefix); - services.ConfigureReloadableOptions(InetOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(EurekaInstanceOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(InetOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureEurekaInstanceOptions>(); DynamicPortAssignmentHostedService.Wire(services); diff --git a/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs b/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs index cafb980c8c..042973179d 100644 --- a/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs +++ b/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; -using Steeltoe.Common.Configuration; using Steeltoe.Common.Net; using Steeltoe.Common.TestResources; using Steeltoe.Discovery.Consul.Configuration; @@ -58,7 +57,7 @@ public void DoesNotUseNetworkInterfacesByDefault() var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddSingleton(inetUtilsMock.Object); - services.ConfigureReloadableOptions(ConsulDiscoveryOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(ConsulDiscoveryOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureConsulDiscoveryOptions>(); using ServiceProvider serviceProvider = services.BuildServiceProvider(true); @@ -85,7 +84,7 @@ public void CanUseNetworkInterfaces() var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddSingleton(inetUtilsMock.Object); - services.ConfigureReloadableOptions(ConsulDiscoveryOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(ConsulDiscoveryOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureConsulDiscoveryOptions>(); using ServiceProvider serviceProvider = services.BuildServiceProvider(true); @@ -113,7 +112,7 @@ public void CanUseNetworkInterfacesWithoutReverseDnsOnIP() services.AddSingleton(configuration); services.AddLogging(); services.AddSingleton(); - services.ConfigureReloadableOptions(ConsulDiscoveryOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(ConsulDiscoveryOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureConsulDiscoveryOptions>(); using ServiceProvider serviceProvider = services.BuildServiceProvider(true); diff --git a/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs b/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs index c8c6811cae..ad00a999ae 100644 --- a/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs +++ b/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs @@ -11,7 +11,6 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; -using Steeltoe.Common.Configuration; using Steeltoe.Common.Extensions; using Steeltoe.Common.Net; using Steeltoe.Common.TestResources; @@ -358,7 +357,7 @@ private static ServiceProvider BuildTestServiceProvider(Dictionary(); services.RegisterDefaultApplicationInstanceInfo(); - services.ConfigureReloadableOptions(EurekaInstanceOptions.ConfigurationPrefix); + services.AddOptions().BindConfiguration(EurekaInstanceOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureEurekaInstanceOptions>(); return services.BuildServiceProvider(true); From eea51a0d5c6fbc8ed3c6aa608af93287612b43b9 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Thu, 8 Aug 2024 12:14:12 +0200 Subject: [PATCH 08/30] Fixes and test coverage for registering option configurers --- .../ConfigureCertificateOptionsTest.cs | 7 +- .../DynamicPortAssignmentHostedService.cs | 4 +- .../ActuatorServiceCollectionExtensions.cs | 13 +-- .../ServiceCollectionExtensions.cs | 4 +- .../Endpoint.Test/ConfigureOptionsTest.cs | 87 +++++++++++++++++++ .../ConfigureKeyManagementOptions.cs | 33 +++++++ .../RedisDataProtectionBuilderExtensions.cs | 7 +- 7 files changed, 131 insertions(+), 24 deletions(-) create mode 100644 src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs create mode 100644 src/Security/src/DataProtection.Redis/ConfigureKeyManagementOptions.cs diff --git a/src/Common/test/Certificates.Test/ConfigureCertificateOptionsTest.cs b/src/Common/test/Certificates.Test/ConfigureCertificateOptionsTest.cs index 006568e5ed..5da2fb5583 100644 --- a/src/Common/test/Certificates.Test/ConfigureCertificateOptionsTest.cs +++ b/src/Common/test/Certificates.Test/ConfigureCertificateOptionsTest.cs @@ -170,10 +170,11 @@ public async Task CertificateOptionsUpdateOnFileLocationChange() var optionsMonitor = serviceProvider.GetRequiredService>(); optionsMonitor.Get(CertificateName).Certificate.Should().BeEquivalentTo(firstX509); - IEnumerable> tokenSources = serviceProvider.GetServices>(); - bool changeCalled = false; - IChangeToken changeToken = tokenSources.First().GetChangeToken(); + IOptionsChangeTokenSource[] tokenSources = serviceProvider.GetServices>().ToArray(); + tokenSources.OfType>().Should().HaveCount(2); + IChangeToken changeToken = tokenSources.OfType>().Single().GetChangeToken(); + bool changeCalled = false; _ = changeToken.RegisterChangeCallback(_ => changeCalled = true, "state"); configuration[$"{CertificateOptions.ConfigurationKeyPrefix}:{CertificateName}:CertificateFilePath"] = certificate2FilePath; configuration[$"{CertificateOptions.ConfigurationKeyPrefix}:{CertificateName}:PrivateKeyFilePath"] = privateKey2FilePath; diff --git a/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs b/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs index 8a9daecc0e..ef165cddac 100644 --- a/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs +++ b/src/Discovery/src/Eureka/DynamicPortAssignmentHostedService.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -48,7 +49,8 @@ public static void Wire(IServiceCollection services) services.AddSingleton>(serviceProvider => serviceProvider.GetRequiredService()); - services.ConfigureOptions(); + services.TryAddEnumerable( + ServiceDescriptor.Singleton, EurekaInstanceDynamicPortsPostConfigureOptions>()); } } diff --git a/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs b/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs index 85ec2ce514..59c26c31d5 100644 --- a/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/ActuatorServiceCollectionExtensions.cs @@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; @@ -56,18 +55,10 @@ internal static void ConfigureOptionsWithChangeTokenSource { - // Workaround for services.ConfigureOptions() registering multiple times, - // see https://github.com/dotnet/runtime/issues/42358. - services.AddOptions(); - services.TryAddTransient, TConfigureOptions>(); + services.TryAddEnumerable(ServiceDescriptor.Transient, TConfigureOptions>()); - services.AddSingleton>(provider => - { - var configurer = (TConfigureOptions)provider.GetRequiredService>(); - var configuration = provider.GetRequiredService(); - return new ConfigurationChangeTokenSource(configuration.GetSection(configurer.ConfigurationKey)); - }); + services.TryAddSingleton, ConfigurationChangeTokenSource>(); } public static void AddAllActuators(this IServiceCollection services, Action? buildCorsPolicy) diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs index 340411281b..c84de2a3cc 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs @@ -29,10 +29,8 @@ public static IServiceCollection AddSpringBootAdminClient(this IServiceCollectio services.RegisterDefaultApplicationInstanceInfo(); - // Workaround for services.ConfigureOptions() registering multiple times, - // see https://github.com/dotnet/runtime/issues/42358. services.AddOptions(); - services.TryAddTransient, ConfigureManagementOptions>(); + services.TryAddEnumerable(ServiceDescriptor.Transient, ConfigureManagementOptions>()); services.ConfigureEndpointOptions(); services.ConfigureOptionsWithChangeTokenSource(); diff --git a/src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs b/src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs new file mode 100644 index 0000000000..63951c6dd1 --- /dev/null +++ b/src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs @@ -0,0 +1,87 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Steeltoe.Management.Endpoint.Environment; +using Steeltoe.Management.Endpoint.Info; +using Steeltoe.Management.Endpoint.Options; + +namespace Steeltoe.Management.Endpoint.Test; + +public sealed class ConfigureOptionsTest +{ + [Fact] + public void Does_not_register_options_configurer_multiple_times() + { + IConfiguration configuration = new ConfigurationBuilder().Build(); + + var services = new ServiceCollection(); + services.AddSingleton(configuration); + + services.AddInfoActuator(); + services.AddEnvironmentActuator(); + + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + IConfigureOptions[] configurers = serviceProvider.GetServices>().ToArray(); + configurers.Should().HaveCount(1); + + IOptionsChangeTokenSource[] tokenSources = serviceProvider.GetServices>().ToArray(); + tokenSources.Should().HaveCount(1); + } + + [Fact] + public void Can_register_additional_options_configurer_upfront() + { + IConfiguration configuration = new ConfigurationBuilder().Build(); + + var services = new ServiceCollection(); + services.AddSingleton(configuration); + + services.AddTransient, CustomManagementOptionsConfigurer>(); + services.AddInfoActuator(); + + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + IConfigureOptions[] configurers = serviceProvider.GetServices>().ToArray(); + configurers.Should().HaveCount(2); + configurers.OfType().Should().HaveCount(1); + configurers.OfType().Should().HaveCount(1); + + var optionsMonitor = serviceProvider.GetRequiredService>(); + optionsMonitor.CurrentValue.Port.Should().Be("9999"); + } + + [Fact] + public void Can_register_additional_options_configurer_afterwards() + { + IConfiguration configuration = new ConfigurationBuilder().Build(); + + var services = new ServiceCollection(); + services.AddSingleton(configuration); + + services.AddInfoActuator(); + services.AddTransient, CustomManagementOptionsConfigurer>(); + + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + IConfigureOptions[] configurers = serviceProvider.GetServices>().ToArray(); + configurers.Should().HaveCount(2); + configurers.OfType().Should().HaveCount(1); + configurers.OfType().Should().HaveCount(1); + + var optionsMonitor = serviceProvider.GetRequiredService>(); + optionsMonitor.CurrentValue.Port.Should().Be("9999"); + } + + private sealed class CustomManagementOptionsConfigurer : IConfigureOptions + { + public void Configure(ManagementOptions options) + { + options.Port = "9999"; + } + } +} diff --git a/src/Security/src/DataProtection.Redis/ConfigureKeyManagementOptions.cs b/src/Security/src/DataProtection.Redis/ConfigureKeyManagementOptions.cs new file mode 100644 index 0000000000..5a9a9a6c1f --- /dev/null +++ b/src/Security/src/DataProtection.Redis/ConfigureKeyManagementOptions.cs @@ -0,0 +1,33 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using Microsoft.AspNetCore.DataProtection.KeyManagement; +using Microsoft.AspNetCore.DataProtection.Repositories; +using Microsoft.Extensions.Options; + +namespace Steeltoe.Security.DataProtection.Redis; + +internal sealed class ConfigureKeyManagementOptions : IConfigureNamedOptions +{ + private readonly IXmlRepository _xmlRepository; + + public ConfigureKeyManagementOptions(IXmlRepository xmlRepository) + { + ArgumentNullException.ThrowIfNull(xmlRepository); + + _xmlRepository = xmlRepository; + } + + public void Configure(KeyManagementOptions options) + { + Configure(Options.DefaultName, options); + } + + public void Configure(string? name, KeyManagementOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + options.XmlRepository = _xmlRepository; + } +} diff --git a/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs b/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs index f4eeb79b22..5cf1d6095e 100644 --- a/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs +++ b/src/Security/src/DataProtection.Redis/RedisDataProtectionBuilderExtensions.cs @@ -37,12 +37,7 @@ public static IDataProtectionBuilder PersistKeysToRedis(this IDataProtectionBuil }); builder.Services.TryAddSingleton(); - - builder.Services.AddSingleton>(provider => - { - return new ConfigureNamedOptions(Options.DefaultName, - options => options.XmlRepository = provider.GetRequiredService()); - }); + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, ConfigureKeyManagementOptions>()); return builder; } From 5ead4bf5b9b44903c11dd8639b6dda8afc450c64 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Fri, 9 Aug 2024 13:38:33 +0200 Subject: [PATCH 09/30] Refactor IApplicationInstanceInfo The following configuration keys are no longer being read, as they were never meant to be: - application:name - application:uris - consul:serviceName - management:name - spring:application:instance_id Renames: - IServiceCollection.RegisterDefaultApplicationInstanceInfo -> AddApplicationInstanceInfo - IServiceCollection.RegisterCloudFoundryApplicationInstanceInfo -> AddCloudFoundryOptions (unified with other extension methods) --- .../HostBuilderExtensionsTest.cs | 9 +- .../CertificateConfigurationExtensions.cs | 3 +- .../src/Certificates/CertificateSettings.cs | 4 +- .../src/Certificates/ConfigurationSchema.json | 4 +- .../Certificates/LocalCertificateWriter.cs | 2 +- .../src/Common/ApplicationInstanceInfo.cs | 141 +----------- .../SpringApplicationSettings.cs | 20 ++ .../ConfigureApplicationInstanceInfo.cs | 30 +++ .../Extensions/ServiceCollectionExtensions.cs | 18 +- .../src/Common/IApplicationInstanceInfo.cs | 80 ++----- .../src/Common/Properties/AssemblyInfo.cs | 1 + src/Common/src/Common/SteeltoeComponent.cs | 11 - src/Common/src/Http/HttpClientExtensions.cs | 2 +- .../Serialization/BoolStringJsonConverter.cs | 7 +- .../Serialization/LongStringJsonConverter.cs | 7 +- .../ApplicationInstanceInfoTest.cs | 74 ++++--- .../{Limits.cs => ApplicationLimits.cs} | 12 +- .../CloudFoundryApplicationOptions.cs | 202 ++++++++++-------- ...CloudFoundryServiceCollectionExtensions.cs | 112 +--------- .../CloudFoundryServicesOptions.cs | 2 +- .../HostBuilderWrapperExtensions.cs | 2 +- .../src/CloudFoundry/PublicAPI.Unshipped.txt | 80 +++---- .../src/ConfigServer/ConfigurationSchema.json | 12 +- .../ConfigServer/Properties/AssemblyInfo.cs | 2 + .../CloudFoundryApplicationOptionsTest.cs | 165 +++++++------- ...dFoundryServiceCollectionExtensionsTest.cs | 10 +- .../ConfigServerClientOptionsTest.cs | 13 +- ...igServerServiceCollectionExtensionsTest.cs | 17 +- .../HostedSpringBootConfigurationTests.cs | 4 +- .../MongoDb/MongoDbHealthContributor.cs | 3 +- .../Redis/RedisHealthContributor.cs | 3 +- .../src/Consul/ConfigurationSchema.json | 6 +- .../ConsulServiceCollectionExtensions.cs | 6 +- .../PostConfigureConsulDiscoveryOptions.cs | 66 +++++- .../src/Consul/Properties/AssemblyInfo.cs | 3 +- .../src/Consul/Registry/ConsulRegistration.cs | 82 +------ .../src/Eureka/ConfigurationSchema.json | 17 +- .../EurekaServiceCollectionExtensions.cs | 2 +- .../PostConfigureEurekaInstanceOptions.cs | 7 +- .../src/Eureka/Properties/AssemblyInfo.cs | 7 +- .../src/Eureka/SpringDiscoverySettings.cs | 23 ++ ...PostConfigureConsulDiscoveryOptionsTest.cs | 16 ++ .../Registry/ConsulRegistrationTest.cs | 145 ++++--------- .../Registry/ConsulServiceRegistrarTest.cs | 23 +- .../Registry/ConsulServiceRegistryTest.cs | 37 ++-- .../Registry/TestRegistrationFactory.cs | 50 +++++ .../PostConfigureEurekaInstanceOptionsTest.cs | 11 +- .../Eureka.Test/Transport/EurekaClientTest.cs | 18 +- .../DiscoveryHostBuilderExtensionsTest.cs | 11 +- ...veryWebApplicationBuilderExtensionsTest.cs | 4 +- .../DiscoveryWebHostBuilderExtensionsTest.cs | 11 +- .../src/Endpoint/ConfigurationSchema.json | 6 +- .../src/Endpoint/Properties/AssemblyInfo.cs | 3 +- .../RouteMappingsEndpointHandler.cs | 10 +- .../ConfigureSpringBootAdminClientOptions.cs | 5 +- .../ServiceCollectionExtensions.cs | 2 +- .../src/Tasks/ConfigurationSchema.json | 6 +- .../src/Tasks/Properties/AssemblyInfo.cs | 3 +- src/Management/src/Tasks/TaskSettings.cs | 20 ++ .../src/Tracing/ConfigurationSchema.json | 10 +- .../src/Tracing/ConfigureTracingOptions.cs | 36 ++++ .../src/Tracing/Properties/AssemblyInfo.cs | 3 +- .../src/Tracing/PublicAPI.Unshipped.txt | 5 +- .../TracingBaseServiceCollectionExtensions.cs | 69 +++--- .../TracingCoreServiceCollectionExtensions.cs | 18 +- .../src/Tracing/TracingLogProcessor.cs | 15 +- src/Management/src/Tracing/TracingOptions.cs | 33 +-- src/Management/test/Endpoint.Test/BaseTest.cs | 4 +- .../Endpoint.Test/ConfigureOptionsTest.cs | 6 +- .../EndpointServiceCollectionTest.cs | 8 +- ...EndpointServiceCollectionExtensionsTest.cs | 28 +-- .../Metrics/MetricsEndpointTest.cs | 16 +- .../Refresh/EndpointServiceCollectionTest.cs | 8 +- .../Services/EndpointServiceCollectionTest.cs | 8 +- .../ServiceCollectionExtensionsTest.cs | 2 +- .../SpringBootAdminClientOptionsTest.cs | 17 +- .../EndpointServiceCollectionTest.cs | 6 +- .../Trace/EndpointServiceCollectionTest.cs | 35 +-- .../Trace/TraceEndpointOptionsTest.cs | 78 +++++-- src/Management/test/Tracing.Test/TestBase.cs | 9 +- ...cingBaseServiceCollectionExtensionsTest.cs | 25 ++- ...cingCoreServiceCollectionExtensionsTest.cs | 9 +- .../Tracing.Test/TracingLogProcessorTest.cs | 48 +++-- .../test/Tracing.Test/TracingOptionsTest.cs | 113 +++++----- .../ConfigurationSchema.json | 2 +- 85 files changed, 1129 insertions(+), 1134 deletions(-) create mode 100644 src/Common/src/Common/Configuration/SpringApplicationSettings.cs create mode 100644 src/Common/src/Common/ConfigureApplicationInstanceInfo.cs delete mode 100644 src/Common/src/Common/SteeltoeComponent.cs rename src/Configuration/src/CloudFoundry/{Limits.cs => ApplicationLimits.cs} (55%) create mode 100644 src/Discovery/src/Eureka/SpringDiscoverySettings.cs create mode 100644 src/Discovery/test/Consul.Test/Registry/TestRegistrationFactory.cs create mode 100644 src/Management/src/Tasks/TaskSettings.cs create mode 100644 src/Management/src/Tracing/ConfigureTracingOptions.cs diff --git a/src/Bootstrap/test/AutoConfiguration.Test/HostBuilderExtensionsTest.cs b/src/Bootstrap/test/AutoConfiguration.Test/HostBuilderExtensionsTest.cs index 610035f6c5..5b9d6625a1 100644 --- a/src/Bootstrap/test/AutoConfiguration.Test/HostBuilderExtensionsTest.cs +++ b/src/Bootstrap/test/AutoConfiguration.Test/HostBuilderExtensionsTest.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; using MongoDB.Driver; using MySqlConnector; using Npgsql; @@ -355,8 +356,12 @@ private static void AssertTracingIsAutowired(HostWrapper hostWrapper) { var tracerProvider = hostWrapper.Services.GetRequiredService(); - hostWrapper.Services.GetService().Should().NotBeNull(); - hostWrapper.Services.GetService().Should().NotBeNull(); + IHostedService[] hostedServices = hostWrapper.Services.GetServices().ToArray(); + hostedServices.Should().ContainSingle(hostedService => hostedService.GetType().Name == "TelemetryHostedService"); + + var optionsMonitor = hostWrapper.Services.GetRequiredService>(); + optionsMonitor.CurrentValue.Name.Should().NotBeNull(); + hostWrapper.Services.GetService().Should().NotBeNull(); FieldInfo? instrumentationsField = tracerProvider.GetType().GetField("instrumentations", BindingFlags.NonPublic | BindingFlags.Instance); diff --git a/src/Common/src/Certificates/CertificateConfigurationExtensions.cs b/src/Common/src/Certificates/CertificateConfigurationExtensions.cs index 1b49c3bbf7..4cc9d7467d 100644 --- a/src/Common/src/Certificates/CertificateConfigurationExtensions.cs +++ b/src/Common/src/Certificates/CertificateConfigurationExtensions.cs @@ -97,7 +97,8 @@ public static IConfigurationBuilder AddAppInstanceIdentityCertificate(this IConf writer.Write(organizationId.Value, spaceId.Value); Environment.SetEnvironmentVariable("CF_SYSTEM_CERT_PATH", - Path.Combine(Directory.GetParent(LocalCertificateWriter.AppBasePath)!.ToString(), LocalCertificateWriter.CertificateDirectoryName)); + Path.Combine(Directory.GetParent(LocalCertificateWriter.AppBasePath)?.FullName ?? string.Empty, + LocalCertificateWriter.CertificateDirectoryName)); Environment.SetEnvironmentVariable("CF_INSTANCE_CERT", Path.Combine(LocalCertificateWriter.AppBasePath, LocalCertificateWriter.CertificateDirectoryName, diff --git a/src/Common/src/Certificates/CertificateSettings.cs b/src/Common/src/Certificates/CertificateSettings.cs index 74f7c3eaa8..fcbee8e2f3 100644 --- a/src/Common/src/Certificates/CertificateSettings.cs +++ b/src/Common/src/Certificates/CertificateSettings.cs @@ -7,10 +7,12 @@ namespace Steeltoe.Common.Certificates; /// -/// Indicates where to load a from. +/// Configuration settings for certificate access. Indicates where to load a from. /// internal sealed class CertificateSettings { + // This type only exists to enable JSON schema documentation via ConfigurationSchemaAttribute. + /// /// Gets or sets the local path to a certificate file on disk. Use if the private key is stored in another file. /// diff --git a/src/Common/src/Certificates/ConfigurationSchema.json b/src/Common/src/Certificates/ConfigurationSchema.json index 88cba16cf3..0ac68091c0 100644 --- a/src/Common/src/Certificates/ConfigurationSchema.json +++ b/src/Common/src/Certificates/ConfigurationSchema.json @@ -28,7 +28,7 @@ "description": "Gets or sets the local path to a private key file on disk (optional)." } }, - "description": "Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from.", + "description": "Configuration settings for certificate access. Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from.", "additionalProperties": { "type": "object", "properties": { @@ -41,7 +41,7 @@ "description": "Gets or sets the local path to a private key file on disk (optional)." } }, - "description": "Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." + "description": "Configuration settings for certificate access. Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." } } } diff --git a/src/Common/src/Certificates/LocalCertificateWriter.cs b/src/Common/src/Certificates/LocalCertificateWriter.cs index af3991178f..8d2c39fa0d 100644 --- a/src/Common/src/Certificates/LocalCertificateWriter.cs +++ b/src/Common/src/Certificates/LocalCertificateWriter.cs @@ -16,7 +16,7 @@ internal sealed class LocalCertificateWriter internal static readonly string AppBasePath = AppContext.BaseDirectory[..AppContext.BaseDirectory.LastIndexOf($"{Path.DirectorySeparatorChar}bin", StringComparison.Ordinal)]; - private static readonly string ParentPath = Directory.GetParent(AppBasePath)!.ToString(); + private static readonly string ParentPath = Directory.GetParent(AppBasePath)?.ToString() ?? string.Empty; internal static readonly string RootCaPfxPath = Path.Combine(ParentPath, CertificateDirectoryName, "SteeltoeCA.pfx"); diff --git a/src/Common/src/Common/ApplicationInstanceInfo.cs b/src/Common/src/Common/ApplicationInstanceInfo.cs index 1e80f5db6a..94bbec85d2 100644 --- a/src/Common/src/Common/ApplicationInstanceInfo.cs +++ b/src/Common/src/Common/ApplicationInstanceInfo.cs @@ -2,138 +2,19 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Reflection; -using Microsoft.Extensions.Configuration; -using Steeltoe.Common.Configuration; +#nullable enable namespace Steeltoe.Common; -public class ApplicationInstanceInfo : IApplicationInstanceInfo +/// +public sealed class ApplicationInstanceInfo : IApplicationInstanceInfo { - public const string ApplicationRoot = "application"; - public const string SpringApplicationRoot = "spring:application"; - public const string EurekaRoot = "eureka"; - public const string ConsulRoot = "consul"; - public const string ManagementRoot = "management"; - - protected IConfiguration Configuration { get; set; } - - protected virtual string PlatformRoot => string.Empty; - - public string DefaultAppName => Assembly.GetEntryAssembly()!.GetName().Name; - - public string AppNameKey => $"{SpringApplicationRoot}:name"; - - public string AppInstanceIdKey => $"{SpringApplicationRoot}:instance_id"; - - public string ConsulInstanceNameKey => $"{ConsulRoot}:serviceName"; - - public string EurekaInstanceNameKey => $"{EurekaRoot}:instance:appName"; - - public string ManagementNameKey => $"{ManagementRoot}:name"; - - public string PlatformNameKey => BuildConfigString(PlatformRoot, $"{ApplicationRoot}:name"); - - // ReSharper disable once InconsistentNaming - public string Instance_Id { get; set; } - - public virtual string InstanceId - { - get => Instance_Id; - set => Instance_Id = value; - } - - // ReSharper disable once InconsistentNaming - public string Application_Id { get; set; } - - public virtual string ApplicationId - { - get => Application_Id; - set => Application_Id = value; - } - - public virtual string Name { get; set; } - - public virtual string ApplicationName => Name ?? Configuration?.GetValue(AppNameKey, DefaultAppName); - - public virtual string ApplicationVersion { get; set; } - - public virtual int InstanceIndex { get; set; } = -1; - - public int Port { get; set; } = -1; - - public virtual IEnumerable Uris { get; set; } - - public string Version { get; set; } - - public virtual int DiskLimit { get; set; } = -1; - - public virtual int MemoryLimit { get; set; } = -1; - - public virtual int FileDescriptorLimit { get; set; } = -1; - - public virtual string InstanceIP { get; set; } - - public virtual string InternalIP { get; set; } - - public ApplicationInstanceInfo() - { - SecondChanceSetIdProperties(); - } - - public ApplicationInstanceInfo(IConfiguration configuration) - { - configuration.Bind(this); - - Configuration = configuration; - SecondChanceSetIdProperties(Configuration); - } - - public ApplicationInstanceInfo(IConfiguration configuration, bool noPrefix) - { - configuration.GetSection(ApplicationRoot).Bind(this); - - Configuration = configuration; - SecondChanceSetIdProperties(Configuration); - } - - public ApplicationInstanceInfo(IConfiguration configuration, string sectionPrefix) - { - string prefix = BuildConfigString(sectionPrefix, ApplicationRoot); - configuration.GetSection(prefix).Bind(this); - - Configuration = configuration; - SecondChanceSetIdProperties(Configuration); - } - - protected void SecondChanceSetIdProperties(IConfiguration configuration = null) - { - if (configuration != null) - { - Instance_Id ??= configuration.GetValue(AppInstanceIdKey); - Application_Id ??= configuration.GetValue($"{SpringApplicationRoot}:id"); - } - } - - private static string BuildConfigString(string prefix, string key) - { - if (string.IsNullOrEmpty(prefix)) - { - return key; - } - - return $"{prefix}:{key}"; - } - - public string GetApplicationNameInContext(SteeltoeComponent component, string additionalSearchPath = null) - { - return component switch - { - SteeltoeComponent.Discovery => ConfigurationValuesHelper.GetPreferredSetting(Configuration, DefaultAppName, additionalSearchPath, - EurekaInstanceNameKey, ConsulInstanceNameKey, PlatformNameKey, AppNameKey), - SteeltoeComponent.Management => ConfigurationValuesHelper.GetPreferredSetting(Configuration, DefaultAppName, additionalSearchPath, - ManagementNameKey, PlatformNameKey, AppNameKey), - _ => throw new NotSupportedException($"Unknown component '{component}'.") - }; - } + /// + public string? ApplicationName { get; set; } + + public string? ApplicationId { get; set; } + public string? InstanceId { get; set; } + public int InstanceIndex { get; set; } = -1; + public IList Uris { get; } = new List(); + public string? InternalIP { get; set; } } diff --git a/src/Common/src/Common/Configuration/SpringApplicationSettings.cs b/src/Common/src/Common/Configuration/SpringApplicationSettings.cs new file mode 100644 index 0000000000..f9b0d85321 --- /dev/null +++ b/src/Common/src/Common/Configuration/SpringApplicationSettings.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable + +namespace Steeltoe.Common.Configuration; + +/// +/// Fallback configuration settings that describe this application. +/// +internal sealed class SpringApplicationSettings +{ + // This type only exists to enable JSON schema documentation via ConfigurationSchemaAttribute. + + /// + /// Gets or sets the name of this application. + /// + public string? Name { get; set; } +} diff --git a/src/Common/src/Common/ConfigureApplicationInstanceInfo.cs b/src/Common/src/Common/ConfigureApplicationInstanceInfo.cs new file mode 100644 index 0000000000..e3c8ac6912 --- /dev/null +++ b/src/Common/src/Common/ConfigureApplicationInstanceInfo.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable + +using System.Reflection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; + +namespace Steeltoe.Common; + +internal sealed class ConfigureApplicationInstanceInfo : IConfigureOptions +{ + private readonly IConfiguration _configuration; + + public ConfigureApplicationInstanceInfo(IConfiguration configuration) + { + ArgumentNullException.ThrowIfNull(configuration); + + _configuration = configuration; + } + + public void Configure(ApplicationInstanceInfo options) + { + ArgumentNullException.ThrowIfNull(options); + + options.ApplicationName ??= _configuration.GetValue("spring:application:name") ?? Assembly.GetEntryAssembly()!.GetName().Name; + } +} diff --git a/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs index e95110e424..3a47eb0d53 100644 --- a/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs +++ b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs @@ -4,26 +4,32 @@ #nullable enable -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; namespace Steeltoe.Common.Extensions; internal static class ServiceCollectionExtensions { /// - /// Try to register a default instance of . + /// Registers for use with the options pattern. It is also registered as + /// in the IoC container for easy access. /// /// - /// Collection of configured services. + /// The to add services to. /// - public static void RegisterDefaultApplicationInstanceInfo(this IServiceCollection services) + public static void AddApplicationInstanceInfo(this IServiceCollection services) { + ArgumentNullException.ThrowIfNull(services); + + services.AddOptions(); + services.TryAddEnumerable(ServiceDescriptor.Singleton, ConfigureApplicationInstanceInfo>()); + services.TryAddSingleton(serviceProvider => { - var configuration = serviceProvider.GetRequiredService(); - return new ApplicationInstanceInfo(configuration, true); + var optionsMonitor = serviceProvider.GetRequiredService>(); + return optionsMonitor.CurrentValue; }); } } diff --git a/src/Common/src/Common/IApplicationInstanceInfo.cs b/src/Common/src/Common/IApplicationInstanceInfo.cs index e4d1452426..7e1862db22 100644 --- a/src/Common/src/Common/IApplicationInstanceInfo.cs +++ b/src/Common/src/Common/IApplicationInstanceInfo.cs @@ -2,78 +2,24 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + namespace Steeltoe.Common; +/// +/// Provides information about the currently running application instance. +/// public interface IApplicationInstanceInfo { - string InstanceId { get; } - - /// - /// Gets a GUID identifying the application. - /// - string ApplicationId { get; } - - /// - /// Gets the name of the application, as known to the hosting platform. - /// - string ApplicationName { get; } - - /// - /// Gets the URIs assigned to the app. - /// - IEnumerable Uris { get; } - - /// - /// Gets the index number of the app instance. - /// - int InstanceIndex { get; } - - /// - /// Gets the port assigned to the app instance, on which it should listen. - /// - int Port { get; } - /// - /// Gets a GUID identifying the application instance. + /// Gets the name of this application. /// - string Version { get; } + string? ApplicationName { get; } - /// - /// Gets the maximum amount of disk available for the app instance. - /// - int DiskLimit { get; } - - /// - /// Gets the maximum amount of memory available for the app instance. - /// - int MemoryLimit { get; } - - /// - /// Gets the maximum amount of file descriptors available to the app instance. - /// - int FileDescriptorLimit { get; } - - /// - /// Gets the internal IP address of the container running the app instance. - /// - string InternalIP { get; } - - /// - /// Gets the external IP address of the host running the app instance. - /// - string InstanceIP { get; } - - /// - /// Gets the name to use to represent the app instance in the context of a given Steeltoe component. - /// - /// - /// The Steeltoe component requesting the app's name. - /// - /// - /// One additional configuration key to consider, used as top priority in search. - /// - /// - /// The name of the application. - /// - string GetApplicationNameInContext(SteeltoeComponent component, string additionalSearchPath = null); + // These properties exist to avoid taking a dependency on Configuration.CloudFoundry in other Steeltoe projects. + internal string? ApplicationId { get; } + internal string? InstanceId { get; } + internal int InstanceIndex { get; } + internal IList Uris { get; } + internal string? InternalIP { get; } } diff --git a/src/Common/src/Common/Properties/AssemblyInfo.cs b/src/Common/src/Common/Properties/AssemblyInfo.cs index 4749c1afb8..16c27144ec 100644 --- a/src/Common/src/Common/Properties/AssemblyInfo.cs +++ b/src/Common/src/Common/Properties/AssemblyInfo.cs @@ -12,6 +12,7 @@ [assembly: InternalsVisibleTo("Steeltoe.Common.Hosting.Test")] [assembly: InternalsVisibleTo("Steeltoe.Common.Http")] [assembly: InternalsVisibleTo("Steeltoe.Common.Test")] +[assembly: InternalsVisibleTo("Steeltoe.Configuration.CloudFoundry")] [assembly: InternalsVisibleTo("Steeltoe.Configuration.CloudFoundry.Test")] [assembly: InternalsVisibleTo("Steeltoe.Configuration.ConfigServer")] [assembly: InternalsVisibleTo("Steeltoe.Configuration.Encryption")] diff --git a/src/Common/src/Common/SteeltoeComponent.cs b/src/Common/src/Common/SteeltoeComponent.cs deleted file mode 100644 index c5bd4dd166..0000000000 --- a/src/Common/src/Common/SteeltoeComponent.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information. - -namespace Steeltoe.Common; - -public enum SteeltoeComponent -{ - Discovery, - Management -} diff --git a/src/Common/src/Http/HttpClientExtensions.cs b/src/Common/src/Http/HttpClientExtensions.cs index fc9cf811ba..2e55e3fb38 100644 --- a/src/Common/src/Http/HttpClientExtensions.cs +++ b/src/Common/src/Http/HttpClientExtensions.cs @@ -83,6 +83,6 @@ public static void ConfigureForSteeltoe(this HttpClient httpClient, TimeSpan? ti internal sealed class AccessTokenResponse { [JsonPropertyName("access_token")] - public string AccessToken { get; set; } = null!; + public string? AccessToken { get; set; } } } diff --git a/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs b/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs index 2710afb50f..05b7c04c44 100644 --- a/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs +++ b/src/Common/src/Http/Serialization/BoolStringJsonConverter.cs @@ -12,7 +12,12 @@ public sealed class BoolStringJsonConverter : JsonConverter { public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return reader.TokenType is JsonTokenType.False or JsonTokenType.True ? reader.GetBoolean() : bool.Parse(reader.GetString()!); + return reader.TokenType switch + { + JsonTokenType.False or JsonTokenType.True => reader.GetBoolean(), + JsonTokenType.String => bool.Parse(reader.GetString()!), + _ => throw new JsonException() + }; } public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) diff --git a/src/Common/src/Http/Serialization/LongStringJsonConverter.cs b/src/Common/src/Http/Serialization/LongStringJsonConverter.cs index 5423a3b5c2..39c6cecf47 100644 --- a/src/Common/src/Http/Serialization/LongStringJsonConverter.cs +++ b/src/Common/src/Http/Serialization/LongStringJsonConverter.cs @@ -12,7 +12,12 @@ public sealed class LongStringJsonConverter : JsonConverter { public override long Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - return reader.TokenType == JsonTokenType.Number ? reader.GetInt64() : long.Parse(reader.GetString()!, CultureInfo.InvariantCulture); + return reader.TokenType switch + { + JsonTokenType.Number => reader.GetInt64(), + JsonTokenType.String => long.Parse(reader.GetString()!, CultureInfo.InvariantCulture), + _ => throw new JsonException() + }; } public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options) diff --git a/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs b/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs index 9aa9c9bd08..2f76b3baf9 100644 --- a/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs +++ b/src/Common/test/Common.Test/ApplicationInstanceInfoTest.cs @@ -4,6 +4,8 @@ using System.Reflection; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Steeltoe.Common.Extensions; using Steeltoe.Common.TestResources.IO; namespace Steeltoe.Common.Test; @@ -13,40 +15,26 @@ public sealed class ApplicationInstanceInfoTest [Fact] public void ConstructorSetsDefaults() { - var builder = new ConfigurationBuilder(); - IConfigurationRoot configurationRoot = builder.Build(); + var options = new ApplicationInstanceInfo(); - var options = new ApplicationInstanceInfo(configurationRoot, true); + Assert.Null(options.ApplicationName); Assert.Null(options.ApplicationId); - Assert.Equal(Assembly.GetEntryAssembly()!.GetName().Name, options.ApplicationName); - Assert.Null(options.ApplicationVersion); Assert.Null(options.InstanceId); Assert.Equal(-1, options.InstanceIndex); - Assert.Null(options.Uris); - Assert.Null(options.Version); - Assert.Null(options.InstanceIP); + Assert.Empty(options.Uris); Assert.Null(options.InternalIP); - Assert.Equal(-1, options.DiskLimit); - Assert.Equal(-1, options.FileDescriptorLimit); - Assert.Equal(-1, options.InstanceIndex); - Assert.Equal(-1, options.MemoryLimit); - Assert.Equal(-1, options.Port); } [Fact] - public void ConstructorReadsApplicationConfiguration() + public void ReadsApplicationConfiguration() { const string configJson = """ { - "Application" : { - "Name": "my-app", - "ApplicationId": "fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", - "Uris": [ - "my-app.10.244.0.34.xip.io", - "my-app2.10.244.0.34.xip.io" - ], - "Version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca" + "Spring": { + "Application": { + "Name": "my-app" } + } } """; @@ -57,16 +45,42 @@ public void ConstructorReadsApplicationConfiguration() var builder = new ConfigurationBuilder(); builder.SetBasePath(directory); builder.AddJsonFile(fileName); - IConfigurationRoot configurationRoot = builder.Build(); + IConfiguration configuration = builder.Build(); - var options = new ApplicationInstanceInfo(configurationRoot, true); + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddApplicationInstanceInfo(); + ServiceProvider serviceProvider = services.BuildServiceProvider(true); + + var options = serviceProvider.GetRequiredService(); - Assert.Equal("fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", options.ApplicationId); Assert.Equal("my-app", options.ApplicationName); - Assert.NotNull(options.Uris); - Assert.Equal(2, options.Uris.Count()); - Assert.Contains("my-app.10.244.0.34.xip.io", options.Uris); - Assert.Contains("my-app2.10.244.0.34.xip.io", options.Uris); - Assert.Equal("fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca", options.Version); + } + + [Fact] + public void Resolves_application_name_from_configuration() + { + var appSettings = new Dictionary(); + + IApplicationInstanceInfo info = FromConfiguration(appSettings); + info.ApplicationName.Should().Be(Assembly.GetEntryAssembly()!.GetName().Name); + + appSettings.Add("spring:application:name", "SpringAppName"); + info = FromConfiguration(appSettings); + info.ApplicationName.Should().Be("SpringAppName"); + } + + private IApplicationInstanceInfo FromConfiguration(IDictionary appSettings) + { + IConfigurationBuilder builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddApplicationInstanceInfo(); + ServiceProvider serviceProvider = services.BuildServiceProvider(true); + + return serviceProvider.GetRequiredService(); } } diff --git a/src/Configuration/src/CloudFoundry/Limits.cs b/src/Configuration/src/CloudFoundry/ApplicationLimits.cs similarity index 55% rename from src/Configuration/src/CloudFoundry/Limits.cs rename to src/Configuration/src/CloudFoundry/ApplicationLimits.cs index 8f9a47fb10..7c0206cd27 100644 --- a/src/Configuration/src/CloudFoundry/Limits.cs +++ b/src/Configuration/src/CloudFoundry/ApplicationLimits.cs @@ -2,11 +2,17 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +using Microsoft.Extensions.Configuration; + namespace Steeltoe.Configuration.CloudFoundry; -public sealed class Limits +public sealed class ApplicationLimits { public int Disk { get; set; } = -1; - public int Fds { get; set; } = -1; - public int Mem { get; set; } = -1; + + [ConfigurationKeyName("fds")] + public int FileDescriptor { get; set; } = -1; + + [ConfigurationKeyName("mem")] + public int Memory { get; set; } = -1; } diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs index e957f2ec3e..da46c0024c 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryApplicationOptions.cs @@ -7,92 +7,124 @@ namespace Steeltoe.Configuration.CloudFoundry; -// See https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html#VCAP-APPLICATION -public sealed class CloudFoundryApplicationOptions : ApplicationInstanceInfo +public sealed class CloudFoundryApplicationOptions : IApplicationInstanceInfo { - internal const string PlatformConfigurationRoot = "vcap"; - - protected override string PlatformRoot => PlatformConfigurationRoot; - - // ReSharper disable once InconsistentNaming - public string? CF_Api { get; set; } - - public override string ApplicationName => Name; - + // See https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html#VCAP-APPLICATION + + /// + /// Gets or sets the GUID identifying the app. + /// + [ConfigurationKeyName("application_id")] + public string? ApplicationId { get; set; } + + /// + /// Gets or sets the name assigned to the app when it was pushed. + /// + [ConfigurationKeyName("application_name")] + public string ApplicationName { get; set; } = "unknown"; + + /// + /// Gets the URIs assigned to the app. + /// + [ConfigurationKeyName("application_uris")] + public IList Uris { get; } = new List(); + + /// + /// Gets or sets the GUID identifying a version of the app. Each time an app is pushed or restarted, this value is updated. + /// + [ConfigurationKeyName("application_version")] + public string? ApplicationVersion { get; set; } + + /// + /// Gets or sets the location of the Cloud Controller API for the Cloud Foundry deployment where the app runs. + /// + [ConfigurationKeyName("cf_api")] + public string? Api { get; set; } + + /// + /// Gets or sets the limits to disk space, number of files, and memory permitted to the app. Memory and disk space limits are supplied when the app is + /// deployed, either on the command line or in the app manifest. The number of files allowed is operator-defined. + /// + public ApplicationLimits? Limits { get; set; } + + /// + /// Gets or sets the GUID identifying the org where the app is deployed. + /// + [ConfigurationKeyName("organization_id")] + public string? OrganizationId { get; set; } + + /// + /// Gets or sets the human-readable name of the org where the app is deployed. + /// + [ConfigurationKeyName("organization_name")] + public string? OrganizationName { get; set; } + + /// + /// Gets or sets the UID identifying the process. Only present in running application containers. + /// + [ConfigurationKeyName("process_id")] + public string? ProcessId { get; set; } + + /// + /// Gets or sets the type of process. Only present in running application containers. + /// + [ConfigurationKeyName("process_type")] + public string? ProcessType { get; set; } + + /// + /// Gets or sets the GUID identifying the space where the app is deployed. + /// + [ConfigurationKeyName("space_id")] + public string? SpaceId { get; set; } + + /// + /// Gets or sets the human-readable name of the space where the app is deployed. + /// + [ConfigurationKeyName("space_name")] + public string? SpaceName { get; set; } + + /// + /// Gets or sets the human-readable timestamp for the time the instance was started. Not provided on Diego Cells. + /// + [ConfigurationKeyName("start")] public string? Start { get; set; } - // ReSharper disable once InconsistentNaming - public IEnumerable? Application_Uris { get; set; } - - public IEnumerable? ApplicationUris => Application_Uris; - - // ReSharper disable once InconsistentNaming - public string? Application_Version { get; set; } - - public override string? ApplicationVersion => Application_Version; - - // ReSharper disable once InconsistentNaming - public int Instance_Index { get; set; } = -1; - - public override int InstanceIndex => Instance_Index; - - // ReSharper disable once InconsistentNaming - public string? Space_Id { get; set; } - - public string? SpaceId => Space_Id; - - // ReSharper disable once InconsistentNaming - public string? Space_Name { get; set; } - - public string? SpaceName => Space_Name; - - // ReSharper disable once InconsistentNaming - public string? Instance_IP { get; set; } - - public override string? InstanceIP => Instance_IP; - - // ReSharper disable once InconsistentNaming - public string? Internal_IP { get; set; } - - public override string? InternalIP => Internal_IP; - - public Limits? Limits { get; set; } - - public override int DiskLimit => Limits?.Disk ?? -1; - - public override int MemoryLimit => Limits?.Mem ?? -1; - - public override int FileDescriptorLimit => Limits?.Fds ?? -1; - - // This constructor is for use with IOptions. - public CloudFoundryApplicationOptions() - { - SecondChanceSetIdProperties(); - } - - public CloudFoundryApplicationOptions(IConfiguration configuration) - : base(configuration, PlatformConfigurationRoot) - { - SetIdPropertiesFromVcap(configuration); - } - - private void SetIdPropertiesFromVcap(IConfiguration? configuration = null) - { - if (configuration != null) - { - string? vcapInstanceId = configuration.GetValue($"{PlatformConfigurationRoot}:application:instance_id"); - - if (!string.IsNullOrEmpty(vcapInstanceId)) - { - Instance_Id = vcapInstanceId; - } - - string? vcapApplicationId = configuration.GetValue($"{PlatformConfigurationRoot}:application:id"); - - if (!string.IsNullOrEmpty(vcapApplicationId)) - { - Application_Id = vcapApplicationId; - } - } - } + /// + /// Gets or sets the UNIX epoch timestamp for the time the instance was started. Not provided on Diego Cells. + /// + [ConfigurationKeyName("started_at_timestamp")] + public long StartedAtTimestamp { get; set; } + + // The properties below don't actually exist in VCAP_APPLICATION, but are sourced from other environment variables. + + /// + /// Gets or sets the UUID of the app instance. Originates from the CF_INSTANCE_GUID environment variable. + /// + [ConfigurationKeyName("instance_id")] + public string? InstanceId { get; set; } + + /// + /// Gets or sets the zero-based index number of the app instance. Originates from the CF_INSTANCE_INDEX environment variable. + /// + [ConfigurationKeyName("instance_index")] + public int InstanceIndex { get; set; } = -1; + + /// + /// Gets or sets the external (host-side) port corresponding to the internal (container-side) port. Originates from the CF_INSTANCE_PORT environment + /// variable. + /// + [ConfigurationKeyName("port")] + public int InstancePort { get; set; } = -1; + + /// + /// Gets or sets the external IP address of the host running the app instance. Originates from the CF_INSTANCE_IP environment variable. + /// + [ConfigurationKeyName("instance_ip")] + public string? InstanceIP { get; set; } + + /// + /// Gets or sets the internal IP address of the container running the app instance. Originates from the CF_INSTANCE_INTERNAL_IP environment variable. + /// + [ConfigurationKeyName("internal_ip")] + public string? InternalIP { get; set; } } diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs index 7140be0b12..5a551fc44e 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryServiceCollectionExtensions.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; using Steeltoe.Common; namespace Steeltoe.Configuration.CloudFoundry; @@ -15,117 +15,23 @@ namespace Steeltoe.Configuration.CloudFoundry; public static class CloudFoundryServiceCollectionExtensions { /// - /// Binds configuration data into and and adds both to the - /// provided service container. You can then inject both options using the normal Options pattern. + /// Registers and for use with the options pattern. The first + /// type is also registered as in the IoC container for easy access. /// /// - /// The service container. + /// The to add services to. /// - /// - /// The application configuration. - /// - /// - /// The incoming service container. - /// - public static IServiceCollection ConfigureCloudFoundryOptions(this IServiceCollection services, IConfiguration configuration) - { - ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(configuration); - - services.AddOptions(); - - IConfigurationSection appSection = - configuration.GetSection($"{CloudFoundryApplicationOptions.PlatformConfigurationRoot}:{ApplicationInstanceInfo.ApplicationRoot}"); - - services.Configure(appSection); - - IConfigurationSection serviceSection = configuration.GetSection(CloudFoundryServicesOptions.ServicesConfigurationRoot); - services.Configure(serviceSection); - - return services; - } - - /// - /// Finds the Cloud Foundry service with the in VCAP_SERVICES and binds the configuration data from the provided - /// into . The name of each option will be the name of the Cloud Foundry - /// service binding. You can then inject all the options using the normal options pattern. - /// - /// - /// The service container. - /// - /// - /// The application configuration. - /// - /// - /// The Cloud Foundry service name to bind to the options type. - /// - /// - /// The incoming service container. - /// - public static IServiceCollection ConfigureCloudFoundryService(this IServiceCollection services, IConfiguration configuration, string serviceName) - { - ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(configuration); - ArgumentException.ThrowIfNullOrWhiteSpace(serviceName); - - services.Configure(serviceName, option => option.Bind(configuration, serviceName)); - - return services; - } - - /// - /// Finds all Cloud Foundry services with the in VCAP_SERVICES and binds the configuration data from the provided - /// into . The name of each option will be the name of the Cloud Foundry - /// service binding. You can then inject all the options using the normal options pattern. - /// - /// - /// The service container. - /// - /// - /// The application configuration. - /// - /// - /// The Cloud Foundry service label to use to bind to the options type. - /// - /// - /// The incoming service container. - /// - public static IServiceCollection ConfigureCloudFoundryServices(this IServiceCollection services, IConfiguration configuration, string serviceLabel) + public static IServiceCollection AddCloudFoundryOptions(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(configuration); - ArgumentException.ThrowIfNullOrWhiteSpace(serviceLabel); - var servicesOptions = new CloudFoundryServicesOptions(configuration); - - if (servicesOptions.Services.TryGetValue(serviceLabel, out IList? serviceList)) - { - foreach (Service service in serviceList) - { - if (!string.IsNullOrEmpty(service.Name)) - { - services.ConfigureCloudFoundryService(configuration, service.Name); - } - } - } - - return services; - } - - /// - /// Removes any existing if found. Registers a . - /// - /// - /// Collection of configured services. - /// - public static IServiceCollection RegisterCloudFoundryApplicationInstanceInfo(this IServiceCollection services) - { - ArgumentNullException.ThrowIfNull(services); + services.AddOptions().BindConfiguration("vcap"); + services.AddOptions().BindConfiguration("vcap:application"); services.Replace(ServiceDescriptor.Singleton(serviceProvider => { - var configuration = serviceProvider.GetRequiredService(); - return new CloudFoundryApplicationOptions(configuration); + var optionsMonitor = serviceProvider.GetRequiredService>(); + return optionsMonitor.CurrentValue; })); return services; diff --git a/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs b/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs index 5a5c06a212..09a4663d88 100644 --- a/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs +++ b/src/Configuration/src/CloudFoundry/CloudFoundryServicesOptions.cs @@ -8,7 +8,7 @@ namespace Steeltoe.Configuration.CloudFoundry; public sealed class CloudFoundryServicesOptions : BaseServiceOptions { - internal const string ServicesConfigurationRoot = "vcap"; + private const string ServicesConfigurationRoot = "vcap"; protected override string ConfigurationPrefix => ServicesConfigurationRoot; diff --git a/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs b/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs index f7a63d4ccf..6d0318badb 100644 --- a/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs +++ b/src/Configuration/src/CloudFoundry/HostBuilderWrapperExtensions.cs @@ -16,7 +16,7 @@ public static HostBuilderWrapper AddCloudFoundryConfiguration(this HostBuilderWr ArgumentNullException.ThrowIfNull(loggerFactory); wrapper.ConfigureAppConfiguration(builder => builder.AddCloudFoundry(null, loggerFactory)); - wrapper.ConfigureServices(services => services.RegisterCloudFoundryApplicationInstanceInfo()); + wrapper.ConfigureServices(services => services.AddCloudFoundryOptions()); if (loggerFactory is IBootstrapLoggerFactory) { diff --git a/src/Configuration/src/CloudFoundry/PublicAPI.Unshipped.txt b/src/Configuration/src/CloudFoundry/PublicAPI.Unshipped.txt index 25a67161a8..e5aa8c34ba 100644 --- a/src/Configuration/src/CloudFoundry/PublicAPI.Unshipped.txt +++ b/src/Configuration/src/CloudFoundry/PublicAPI.Unshipped.txt @@ -1,12 +1,4 @@ #nullable enable -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationName.get -> string! -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationVersion.get -> string? -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.DiskLimit.get -> int -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.FileDescriptorLimit.get -> int -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceIndex.get -> int -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceIP.get -> string? -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InternalIP.get -> string? -override Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.MemoryLimit.get -> int static Steeltoe.Configuration.CloudFoundry.CloudFoundryConfigurationBuilderExtensions.AddCloudFoundry(this Microsoft.Extensions.Configuration.IConfigurationBuilder! configurationBuilder) -> Microsoft.Extensions.Configuration.IConfigurationBuilder! static Steeltoe.Configuration.CloudFoundry.CloudFoundryConfigurationBuilderExtensions.AddCloudFoundry(this Microsoft.Extensions.Configuration.IConfigurationBuilder! configurationBuilder, Steeltoe.Configuration.CloudFoundry.ICloudFoundrySettingsReader? settingsReader) -> Microsoft.Extensions.Configuration.IConfigurationBuilder! static Steeltoe.Configuration.CloudFoundry.CloudFoundryConfigurationBuilderExtensions.AddCloudFoundry(this Microsoft.Extensions.Configuration.IConfigurationBuilder! configurationBuilder, Steeltoe.Configuration.CloudFoundry.ICloudFoundrySettingsReader? settingsReader, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> Microsoft.Extensions.Configuration.IConfigurationBuilder! @@ -16,36 +8,54 @@ static Steeltoe.Configuration.CloudFoundry.CloudFoundryHostBuilderExtensions.Add static Steeltoe.Configuration.CloudFoundry.CloudFoundryHostBuilderExtensions.AddCloudFoundryConfiguration(this Microsoft.Extensions.Hosting.IHostApplicationBuilder! builder, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> Microsoft.Extensions.Hosting.IHostApplicationBuilder! static Steeltoe.Configuration.CloudFoundry.CloudFoundryHostBuilderExtensions.AddCloudFoundryConfiguration(this Microsoft.Extensions.Hosting.IHostBuilder! builder) -> Microsoft.Extensions.Hosting.IHostBuilder! static Steeltoe.Configuration.CloudFoundry.CloudFoundryHostBuilderExtensions.AddCloudFoundryConfiguration(this Microsoft.Extensions.Hosting.IHostBuilder! builder, Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> Microsoft.Extensions.Hosting.IHostBuilder! -static Steeltoe.Configuration.CloudFoundry.CloudFoundryServiceCollectionExtensions.ConfigureCloudFoundryOptions(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, Microsoft.Extensions.Configuration.IConfiguration! configuration) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! -static Steeltoe.Configuration.CloudFoundry.CloudFoundryServiceCollectionExtensions.ConfigureCloudFoundryService(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, Microsoft.Extensions.Configuration.IConfiguration! configuration, string! serviceName) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! -static Steeltoe.Configuration.CloudFoundry.CloudFoundryServiceCollectionExtensions.ConfigureCloudFoundryServices(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, Microsoft.Extensions.Configuration.IConfiguration! configuration, string! serviceLabel) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! -static Steeltoe.Configuration.CloudFoundry.CloudFoundryServiceCollectionExtensions.RegisterCloudFoundryApplicationInstanceInfo(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Steeltoe.Configuration.CloudFoundry.CloudFoundryServiceCollectionExtensions.AddCloudFoundryOptions(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +Steeltoe.Configuration.CloudFoundry.ApplicationLimits +Steeltoe.Configuration.CloudFoundry.ApplicationLimits.ApplicationLimits() -> void +Steeltoe.Configuration.CloudFoundry.ApplicationLimits.Disk.get -> int +Steeltoe.Configuration.CloudFoundry.ApplicationLimits.Disk.set -> void +Steeltoe.Configuration.CloudFoundry.ApplicationLimits.FileDescriptor.get -> int +Steeltoe.Configuration.CloudFoundry.ApplicationLimits.FileDescriptor.set -> void +Steeltoe.Configuration.CloudFoundry.ApplicationLimits.Memory.get -> int +Steeltoe.Configuration.CloudFoundry.ApplicationLimits.Memory.set -> void Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationUris.get -> System.Collections.Generic.IEnumerable? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Application_Uris.get -> System.Collections.Generic.IEnumerable? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Application_Uris.set -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Application_Version.get -> string? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Application_Version.set -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.CF_Api.get -> string? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.CF_Api.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Api.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Api.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationId.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationId.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationName.get -> string! +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationName.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationVersion.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ApplicationVersion.set -> void Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.CloudFoundryApplicationOptions() -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.CloudFoundryApplicationOptions(Microsoft.Extensions.Configuration.IConfiguration! configuration) -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Instance_Index.get -> int -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Instance_Index.set -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Instance_IP.get -> string? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Instance_IP.set -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Internal_IP.get -> string? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Internal_IP.set -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Limits.get -> Steeltoe.Configuration.CloudFoundry.Limits? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceId.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceId.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceIndex.get -> int +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceIndex.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceIP.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstanceIP.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstancePort.get -> int +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InstancePort.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InternalIP.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.InternalIP.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Limits.get -> Steeltoe.Configuration.CloudFoundry.ApplicationLimits? Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Limits.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.OrganizationId.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.OrganizationId.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.OrganizationName.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.OrganizationName.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ProcessId.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ProcessId.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ProcessType.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.ProcessType.set -> void Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.SpaceId.get -> string? +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.SpaceId.set -> void Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.SpaceName.get -> string? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Space_Id.get -> string? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Space_Id.set -> void -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Space_Name.get -> string? -Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Space_Name.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.SpaceName.set -> void Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Start.get -> string? Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Start.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.StartedAtTimestamp.get -> long +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.StartedAtTimestamp.set -> void +Steeltoe.Configuration.CloudFoundry.CloudFoundryApplicationOptions.Uris.get -> System.Collections.Generic.IList! Steeltoe.Configuration.CloudFoundry.CloudFoundryConfigurationBuilderExtensions Steeltoe.Configuration.CloudFoundry.CloudFoundryHostBuilderExtensions Steeltoe.Configuration.CloudFoundry.CloudFoundryServiceCollectionExtensions @@ -60,11 +70,3 @@ Steeltoe.Configuration.CloudFoundry.ICloudFoundrySettingsReader.InstanceInternal Steeltoe.Configuration.CloudFoundry.ICloudFoundrySettingsReader.InstanceIP.get -> string? Steeltoe.Configuration.CloudFoundry.ICloudFoundrySettingsReader.InstancePort.get -> string? Steeltoe.Configuration.CloudFoundry.ICloudFoundrySettingsReader.ServicesJson.get -> string? -Steeltoe.Configuration.CloudFoundry.Limits -Steeltoe.Configuration.CloudFoundry.Limits.Disk.get -> int -Steeltoe.Configuration.CloudFoundry.Limits.Disk.set -> void -Steeltoe.Configuration.CloudFoundry.Limits.Fds.get -> int -Steeltoe.Configuration.CloudFoundry.Limits.Fds.set -> void -Steeltoe.Configuration.CloudFoundry.Limits.Limits() -> void -Steeltoe.Configuration.CloudFoundry.Limits.Mem.get -> int -Steeltoe.Configuration.CloudFoundry.Limits.Mem.set -> void diff --git a/src/Configuration/src/ConfigServer/ConfigurationSchema.json b/src/Configuration/src/ConfigServer/ConfigurationSchema.json index 7c67dd4815..99f6369aeb 100644 --- a/src/Configuration/src/ConfigServer/ConfigurationSchema.json +++ b/src/Configuration/src/ConfigServer/ConfigurationSchema.json @@ -31,13 +31,23 @@ "description": "Gets or sets the local path to a private key file on disk (optional)." } }, - "description": "Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." + "description": "Configuration settings for certificate access. Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." } } }, "Spring": { "type": "object", "properties": { + "Application": { + "type": "object", + "properties": { + "Name": { + "type": "string", + "description": "Gets or sets the name of this application." + } + }, + "description": "Fallback configuration settings that describe this application." + }, "Cloud": { "type": "object", "properties": { diff --git a/src/Configuration/src/ConfigServer/Properties/AssemblyInfo.cs b/src/Configuration/src/ConfigServer/Properties/AssemblyInfo.cs index ffe185fc04..4b00d16231 100644 --- a/src/Configuration/src/ConfigServer/Properties/AssemblyInfo.cs +++ b/src/Configuration/src/ConfigServer/Properties/AssemblyInfo.cs @@ -5,8 +5,10 @@ using System.Runtime.CompilerServices; using Aspire; using Steeltoe.Common.Certificates; +using Steeltoe.Common.Configuration; using Steeltoe.Configuration.ConfigServer; +[assembly: ConfigurationSchema("Spring:Application", typeof(SpringApplicationSettings))] [assembly: ConfigurationSchema("Spring:Cloud:Config", typeof(ConfigServerClientOptions))] [assembly: ConfigurationSchema("Certificates:ConfigServer", typeof(CertificateSettings))] [assembly: LoggingCategories("Steeltoe", "Steeltoe.Configuration", "Steeltoe.Configuration.ConfigServer")] diff --git a/src/Configuration/test/CloudFoundry.Test/CloudFoundryApplicationOptionsTest.cs b/src/Configuration/test/CloudFoundry.Test/CloudFoundryApplicationOptionsTest.cs index 21e2f6e9ee..7adb4d07a8 100644 --- a/src/Configuration/test/CloudFoundry.Test/CloudFoundryApplicationOptionsTest.cs +++ b/src/Configuration/test/CloudFoundry.Test/CloudFoundryApplicationOptionsTest.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; +using Steeltoe.Common.TestResources; namespace Steeltoe.Configuration.CloudFoundry.Test; @@ -11,104 +12,96 @@ public sealed class CloudFoundryApplicationOptionsTest [Fact] public void Constructor_WithNoVcapApplicationConfiguration() { - var builder = new ConfigurationBuilder(); - IConfigurationRoot configurationRoot = builder.Build(); + var options = new CloudFoundryApplicationOptions(); - var options = new CloudFoundryApplicationOptions(configurationRoot); - - Assert.Null(options.CF_Api); - Assert.Null(options.ApplicationId); - Assert.Null(options.ApplicationName); - Assert.Null(options.ApplicationUris); - Assert.Null(options.Application_Uris); - Assert.Null(options.ApplicationVersion); - Assert.Null(options.Application_Version); - Assert.Null(options.InstanceId); - Assert.Equal(-1, options.InstanceIndex); - Assert.Equal(-1, options.Instance_Index); - Assert.Null(options.Limits); - Assert.Null(options.Name); - Assert.Null(options.SpaceId); - Assert.Null(options.Space_Id); - Assert.Null(options.SpaceName); - Assert.Null(options.Space_Name); - Assert.Null(options.Start); - Assert.Null(options.Uris); - Assert.Null(options.Version); - Assert.Null(options.Instance_IP); - Assert.Null(options.InstanceIP); - Assert.Null(options.Internal_IP); - Assert.Null(options.InternalIP); - Assert.Equal(-1, options.DiskLimit); - Assert.Equal(-1, options.FileDescriptorLimit); - Assert.Equal(-1, options.InstanceIndex); - Assert.Equal(-1, options.MemoryLimit); - Assert.Equal(-1, options.Port); + options.ApplicationId.Should().BeNull(); + options.ApplicationName.Should().Be("unknown"); + options.Uris.Should().BeEmpty(); + options.ApplicationVersion.Should().BeNull(); + options.Api.Should().BeNull(); + options.Limits.Should().BeNull(); + options.OrganizationId.Should().BeNull(); + options.OrganizationName.Should().BeNull(); + options.ProcessId.Should().BeNull(); + options.ProcessType.Should().BeNull(); + options.SpaceId.Should().BeNull(); + options.SpaceName.Should().BeNull(); + options.Start.Should().BeNull(); + options.StartedAtTimestamp.Should().Be(0); + options.InstanceId.Should().BeNull(); + options.InstanceIndex.Should().Be(-1); + options.InstancePort.Should().Be(-1); + options.InstanceIP.Should().BeNull(); + options.InternalIP.Should().BeNull(); } [Fact] public void Constructor_WithVcapApplicationConfiguration() { - const string configJson = """ + const string vcapApplicationJson = """ { - "vcap": { - "application" : { - "cf_api": "https://api.system.testcloud.com", - "application_id": "fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", - "application_name": "my-app", - "application_uris": [ - "my-app.10.244.0.34.xip.io" - ], - "application_version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca", - "limits": { - "disk": 1024, - "fds": 16384, - "mem": 256 - }, - "name": "my-app", - "space_id": "06450c72-4669-4dc6-8096-45f9777db68a", - "space_name": "my-space", - "uris": [ - "my-app.10.244.0.34.xip.io", - "my-app2.10.244.0.34.xip.io" - ], - "users": null, - "version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca" - } - } + "cf_api": "https://api.system.testcloud.com", + "application_id": "fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", + "application_name": "my-app", + "application_uris": [ + "my-app.10.244.0.34.xip.io", + "my-app2.10.244.0.34.xip.io" + ], + "application_version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca", + "limits": { + "disk": 1024, + "fds": 16384, + "mem": 256 + }, + "name": "my-app", + "space_id": "06450c72-4669-4dc6-8096-45f9777db68a", + "space_name": "my-space", + "uris": [ + "my-app.10.244.0.34.xip.io", + "my-app2.10.244.0.34.xip.io" + ], + "users": null, + "version": "fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca" } """; - using Stream stream = CloudFoundryConfigurationProvider.GetStream(configJson); - var jsonSource = new JsonStreamConfigurationSource(stream); - IConfigurationBuilder builder = new ConfigurationBuilder().Add(jsonSource); - IConfigurationRoot configurationRoot = builder.Build(); - - var options = new CloudFoundryApplicationOptions(configurationRoot); - - Assert.Equal("https://api.system.testcloud.com", options.CF_Api); - Assert.Equal("fa05c1a9-0fc1-4fbd-bae1-139850dec7a3", options.ApplicationId); - Assert.Equal("my-app", options.ApplicationName); - - Assert.NotNull(options.ApplicationUris); - Assert.NotNull(options.Application_Uris); - Assert.Single(options.ApplicationUris); - Assert.Single(options.Application_Uris); - Assert.Equal("my-app.10.244.0.34.xip.io", options.ApplicationUris.First()); - Assert.Equal("my-app.10.244.0.34.xip.io", options.Application_Uris.First()); + using var appScope = new EnvironmentVariableScope("VCAP_APPLICATION", vcapApplicationJson); + using var idScope = new EnvironmentVariableScope("CF_INSTANCE_GUID", "some-id"); + using var indexScope = new EnvironmentVariableScope("CF_INSTANCE_INDEX", "2"); + using var portScope = new EnvironmentVariableScope("CF_INSTANCE_PORT", "8765"); + using var ipScope = new EnvironmentVariableScope("CF_INSTANCE_IP", "1.2.3.4"); + using var internalIpScope = new EnvironmentVariableScope("CF_INSTANCE_INTERNAL_IP", "5.6.7.8"); - Assert.Equal("fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca", options.ApplicationVersion); - Assert.Equal("my-app", options.Name); - Assert.Equal("06450c72-4669-4dc6-8096-45f9777db68a", options.SpaceId); - Assert.Equal("06450c72-4669-4dc6-8096-45f9777db68a", options.Space_Id); - Assert.Equal("my-space", options.SpaceName); - Assert.Equal("my-space", options.Space_Name); + IConfigurationBuilder builder = new ConfigurationBuilder(); + builder.AddCloudFoundry(); + IConfigurationRoot configuration = builder.Build(); - Assert.NotNull(options.Uris); - Assert.Equal(2, options.Uris.Count()); - Assert.Contains("my-app.10.244.0.34.xip.io", options.Uris); - Assert.Contains("my-app2.10.244.0.34.xip.io", options.Uris); + var options = new CloudFoundryApplicationOptions(); + configuration.GetSection("vcap:application").Bind(options); - Assert.Equal("fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca", options.Version); + options.ApplicationId.Should().Be("fa05c1a9-0fc1-4fbd-bae1-139850dec7a3"); + options.ApplicationName.Should().Be("my-app"); + options.Uris.Should().HaveCount(2); + options.Uris[0].Should().Be("my-app.10.244.0.34.xip.io"); + options.Uris[1].Should().Be("my-app2.10.244.0.34.xip.io"); + options.ApplicationVersion.Should().Be("fb8fbcc6-8d58-479e-bcc7-3b4ce5a7f0ca"); + options.Api.Should().Be("https://api.system.testcloud.com"); + options.Limits.Should().NotBeNull(); + options.Limits!.Disk.Should().Be(1024); + options.Limits!.FileDescriptor.Should().Be(16384); + options.Limits!.Memory.Should().Be(256); + options.OrganizationId.Should().BeNull(); + options.OrganizationName.Should().BeNull(); + options.ProcessId.Should().BeNull(); + options.ProcessType.Should().BeNull(); + options.SpaceId.Should().Be("06450c72-4669-4dc6-8096-45f9777db68a"); + options.SpaceName.Should().Be("my-space"); + options.Start.Should().BeNull(); + options.StartedAtTimestamp.Should().Be(0); + options.InstanceId.Should().Be("some-id"); + options.InstanceIndex.Should().Be(2); + options.InstancePort.Should().Be(8765); + options.InstanceIP.Should().Be("1.2.3.4"); + options.InternalIP.Should().Be("5.6.7.8"); } } diff --git a/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs b/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs index d11aa6a36a..0f433e70d5 100644 --- a/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs +++ b/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs @@ -37,18 +37,16 @@ public void ConfigureCloudFoundryOptions_ConfiguresCloudFoundryOptions() } """); - IConfigurationRoot configurationRoot = new ConfigurationBuilder().AddCloudFoundry().Build(); + IConfiguration configurationRoot = new ConfigurationBuilder().AddCloudFoundry().Build(); var services = new ServiceCollection(); - services.ConfigureCloudFoundryOptions(configurationRoot); + services.AddSingleton(configurationRoot); + services.AddCloudFoundryOptions(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); var appOptions = serviceProvider.GetRequiredService>(); - Assert.NotNull(appOptions.Value); Assert.Equal("foo", appOptions.Value.ApplicationName); + Assert.Equal(16384, appOptions.Value.Limits?.FileDescriptor); Assert.Equal("playground", appOptions.Value.SpaceName); - - var serviceOptions = serviceProvider.GetRequiredService>(); - Assert.NotNull(serviceOptions.Value); } } diff --git a/src/Configuration/test/ConfigServer.Test/ConfigServerClientOptionsTest.cs b/src/Configuration/test/ConfigServer.Test/ConfigServerClientOptionsTest.cs index 98c03bba4d..bddc80c1aa 100644 --- a/src/Configuration/test/ConfigServer.Test/ConfigServerClientOptionsTest.cs +++ b/src/Configuration/test/ConfigServer.Test/ConfigServerClientOptionsTest.cs @@ -23,11 +23,9 @@ public void ConfigureConfigServerClientOptions_WithDefaults() services.AddSingleton(_ => builder.Build()); services.ConfigureConfigServerClientOptions(); - var service = services.BuildServiceProvider(true).GetService>(); - Assert.NotNull(service); - ConfigServerClientOptions options = service.Value; - Assert.NotNull(options); - TestHelper.VerifyDefaults(options); + var service = services.BuildServiceProvider(true).GetRequiredService>(); + + TestHelper.VerifyDefaults(service.Value); } [Fact] @@ -69,10 +67,9 @@ public void ConfigureConfigServerClientOptions_WithValues() services.AddSingleton(configurationRoot); services.ConfigureConfigServerClientOptions(); - var service = services.BuildServiceProvider(true).GetService>(); - Assert.NotNull(service); + var service = services.BuildServiceProvider(true).GetRequiredService>(); + ConfigServerClientOptions options = service.Value; - Assert.NotNull(options); Assert.True(options.Enabled); Assert.True(options.FailFast); diff --git a/src/Configuration/test/ConfigServer.Test/ConfigServerServiceCollectionExtensionsTest.cs b/src/Configuration/test/ConfigServer.Test/ConfigServerServiceCollectionExtensionsTest.cs index 90b945baf5..c6fa5ddf11 100644 --- a/src/Configuration/test/ConfigServer.Test/ConfigServerServiceCollectionExtensionsTest.cs +++ b/src/Configuration/test/ConfigServer.Test/ConfigServerServiceCollectionExtensionsTest.cs @@ -24,11 +24,9 @@ public void ConfigureConfigServerClientOptions_ConfiguresConfigServerClientOptio services.AddSingleton(configurationRoot); services.ConfigureConfigServerClientOptions(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var service = serviceProvider.GetService>(); - Assert.NotNull(service); - ConfigServerClientOptions options = service.Value; - Assert.NotNull(options); - TestHelper.VerifyDefaults(options); + var service = serviceProvider.GetRequiredService>(); + + TestHelper.VerifyDefaults(service.Value); } [Fact] @@ -39,9 +37,10 @@ public void ConfigureConfigServerClientOptions_ConfiguresCloudFoundryOptions() services.ConfigureConfigServerClientOptions(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var app = serviceProvider.GetService>(); - Assert.NotNull(app); - var service = serviceProvider.GetService>(); - Assert.NotNull(service); + var app = serviceProvider.GetRequiredService>(); + Assert.NotNull(app.Value.ApplicationName); + + var service = serviceProvider.GetRequiredService>(); + Assert.Empty(service.Value.Services); } } diff --git a/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTests.cs b/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTests.cs index 9f4ebc035d..634aa7f210 100644 --- a/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTests.cs +++ b/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTests.cs @@ -115,7 +115,7 @@ public void WebApplicationConfiguresIConfiguration_Spring_Application_Json() { using var scope = new EnvironmentVariableScope("SPRING_APPLICATION_JSON", "{\"foo.bar\":\"value\"}"); - WebApplicationBuilder? hostBuilder = TestHelpers.GetTestWebApplicationBuilder(); + WebApplicationBuilder hostBuilder = TestHelpers.GetTestWebApplicationBuilder(); hostBuilder.Configuration.AddSpringBootFromEnvironmentVariable(); WebApplication host = hostBuilder.Build(); @@ -128,7 +128,7 @@ public void WebApplicationConfiguresIConfiguration_Spring_Application_Json() [Fact] public void WebApplicationConfiguresIConfiguration_CmdLine() { - WebApplicationBuilder? hostBuilder = TestHelpers.GetTestWebApplicationBuilder([ + WebApplicationBuilder hostBuilder = TestHelpers.GetTestWebApplicationBuilder([ "Spring.Cloud.Stream.Bindings.Input.Destination=testDestination", "Spring.Cloud.Stream.Bindings.Input.Group=testGroup" ]); diff --git a/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs b/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs index 79a8bb51a4..3ecef3edf9 100644 --- a/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs +++ b/src/Connectors/src/Connectors/MongoDb/MongoDbHealthContributor.cs @@ -120,7 +120,8 @@ private static string GetHostNameFromConnectionString(string? connectionString) ConnectionString = connectionString }; - return (string)builder["server"]!; + string? hostName = (string?)builder["server"]; + return hostName ?? string.Empty; } } } diff --git a/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs b/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs index 4a12abe90a..395e604151 100644 --- a/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs +++ b/src/Connectors/src/Connectors/Redis/RedisHealthContributor.cs @@ -44,7 +44,8 @@ private static string GetHostNameFromConnectionString(string? connectionString) ConnectionString = connectionString }; - return (string)builder["host"]!; + string? hostName = (string?)builder["host"]; + return hostName ?? string.Empty; } internal void SetConnectionMultiplexer(object connectionMultiplexer) diff --git a/src/Discovery/src/Consul/ConfigurationSchema.json b/src/Discovery/src/Consul/ConfigurationSchema.json index 354f3a5a7c..593a01b2c3 100644 --- a/src/Discovery/src/Consul/ConfigurationSchema.json +++ b/src/Discovery/src/Consul/ConfigurationSchema.json @@ -235,9 +235,11 @@ "type": "object", "properties": { "Name": { - "type": "string" + "type": "string", + "description": "Gets or sets the name of this application." } - } + }, + "description": "Fallback configuration settings that describe this application." }, "Cloud": { "type": "object", diff --git a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs index 4849921b9f..74b6d553b6 100644 --- a/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs +++ b/src/Discovery/src/Consul/ConsulServiceCollectionExtensions.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Discovery; using Steeltoe.Common.Extensions; using Steeltoe.Common.HealthChecks; @@ -38,7 +37,7 @@ public static IServiceCollection AddConsulDiscoveryClient(this IServiceCollectio private static void ConfigureConsulServices(IServiceCollection services) { - services.RegisterDefaultApplicationInstanceInfo(); + services.AddApplicationInstanceInfo(); services.TryAddSingleton(); ConfigureConsulOptions(services); @@ -87,8 +86,7 @@ private static void AddConsulServices(IServiceCollection services) services.AddSingleton(serviceProvider => { var optionsMonitor = serviceProvider.GetRequiredService>(); - var instanceInfo = serviceProvider.GetRequiredService(); - return ConsulRegistration.Create(optionsMonitor, instanceInfo); + return ConsulRegistration.Create(optionsMonitor); }); services.AddSingleton(); diff --git a/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs b/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs index 8ec1c89668..5da857f66f 100644 --- a/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs +++ b/src/Discovery/src/Consul/PostConfigureConsulDiscoveryOptions.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; +using Steeltoe.Common; using Steeltoe.Common.Http; using Steeltoe.Common.Net; using Steeltoe.Discovery.Consul.Configuration; @@ -13,22 +15,29 @@ namespace Steeltoe.Discovery.Consul; internal sealed class PostConfigureConsulDiscoveryOptions : IPostConfigureOptions { + private const char SafeChar = '-'; + private readonly IConfiguration _configuration; private readonly InetUtils _inetUtils; + private readonly IApplicationInstanceInfo _applicationInstanceInfo; - public PostConfigureConsulDiscoveryOptions(IConfiguration configuration, InetUtils inetUtils) + public PostConfigureConsulDiscoveryOptions(IConfiguration configuration, InetUtils inetUtils, IApplicationInstanceInfo applicationInstanceInfo) { ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(inetUtils); + ArgumentNullException.ThrowIfNull(applicationInstanceInfo); _configuration = configuration; _inetUtils = inetUtils; + _applicationInstanceInfo = applicationInstanceInfo; } public void PostConfigure(string? name, ConsulDiscoveryOptions options) { ArgumentNullException.ThrowIfNull(options); + options.ServiceName = GetServiceName(options); + HostInfo? hostInfo = options.UseNetworkInterfaces ? _inetUtils.FindFirstNonLoopbackHostInfo() : null; options.HostName ??= hostInfo != null ? hostInfo.Hostname : DnsTools.ResolveHostName(); @@ -54,6 +63,14 @@ public void PostConfigure(string? name, ConsulDiscoveryOptions options) ICollection addresses = _configuration.GetListenAddresses(); SetPortsFromListenAddresses(options, addresses); } + + options.InstanceId = GetInstanceId(options); + } + + private string GetServiceName(ConsulDiscoveryOptions options) + { + string? serviceName = options.ServiceName ?? _applicationInstanceInfo.ApplicationName; + return NormalizeForConsul(serviceName, nameof(ConsulDiscoveryOptions.ServiceName)); } private void SetPortsFromListenAddresses(ConsulDiscoveryOptions options, IEnumerable listenOnAddresses) @@ -87,4 +104,51 @@ private void SetPortsFromListenAddresses(ConsulDiscoveryOptions options, IEnumer } } } + + private string GetInstanceId(ConsulDiscoveryOptions options) + { + string? instanceId = options.InstanceId; + + if (string.IsNullOrEmpty(instanceId)) + { + string defaultInstanceId = _applicationInstanceInfo.InstanceId ?? $"{Random.Shared.Next(10_000_000, 99_999_999):D8}"; + instanceId = $"{options.ServiceName}:{defaultInstanceId}"; + } + + return NormalizeForConsul(instanceId, nameof(ConsulDiscoveryOptions.InstanceId)); + } + + internal static string NormalizeForConsul(string? value, string propertyName) + { + if (value == null || !char.IsLetter(value[0]) || !char.IsLetterOrDigit(value[^1])) + { + throw new InvalidOperationException( + $"Consul property '{propertyName}' must not be empty, must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen. The value '{value}' is invalid."); + } + + var normalizedValueBuilder = new StringBuilder(); + char? previousChar = null; + + foreach (char ch in value) + { + char? charToAppend = null; + + if (char.IsLetterOrDigit(ch)) + { + charToAppend = ch; + } + else if (previousChar is not SafeChar) + { + charToAppend = SafeChar; + } + + if (charToAppend != null) + { + normalizedValueBuilder.Append(charToAppend); + previousChar = charToAppend; + } + } + + return normalizedValueBuilder.ToString(); + } } diff --git a/src/Discovery/src/Consul/Properties/AssemblyInfo.cs b/src/Discovery/src/Consul/Properties/AssemblyInfo.cs index 6c909d1462..ebf9b2798f 100644 --- a/src/Discovery/src/Consul/Properties/AssemblyInfo.cs +++ b/src/Discovery/src/Consul/Properties/AssemblyInfo.cs @@ -4,10 +4,11 @@ using System.Runtime.CompilerServices; using Aspire; +using Steeltoe.Common.Configuration; using Steeltoe.Common.Net; using Steeltoe.Discovery.Consul.Configuration; -[assembly: ConfigurationSchema("Spring:Application:Name", typeof(string))] +[assembly: ConfigurationSchema("Spring:Application", typeof(SpringApplicationSettings))] [assembly: ConfigurationSchema("Spring:Cloud:Discovery:Enabled", typeof(bool))] [assembly: ConfigurationSchema("Spring:Cloud:Inet", typeof(InetOptions))] [assembly: ConfigurationSchema("Consul", typeof(ConsulOptions))] diff --git a/src/Discovery/src/Consul/Registry/ConsulRegistration.cs b/src/Discovery/src/Consul/Registry/ConsulRegistration.cs index 2bf97b5ae3..1953db69fc 100644 --- a/src/Discovery/src/Consul/Registry/ConsulRegistration.cs +++ b/src/Discovery/src/Consul/Registry/ConsulRegistration.cs @@ -3,11 +3,8 @@ // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; -using System.Globalization; -using System.Text; using Consul; using Microsoft.Extensions.Options; -using Steeltoe.Common; using Steeltoe.Common.Discovery; using Steeltoe.Discovery.Consul.Configuration; using Steeltoe.Discovery.Consul.Util; @@ -19,7 +16,6 @@ namespace Steeltoe.Discovery.Consul.Registry; /// public sealed class ConsulRegistration : IServiceInstance { - private const char Separator = '-'; private readonly IOptionsMonitor _optionsMonitor; internal AgentServiceRegistration InnerRegistration { get; } @@ -80,28 +76,21 @@ internal ConsulRegistration(AgentServiceRegistration innerRegistration, IOptions /// /// Provides access to . /// - /// - /// Info about this app instance. - /// - internal static ConsulRegistration Create(IOptionsMonitor optionsMonitor, IApplicationInstanceInfo applicationInfo) + internal static ConsulRegistration Create(IOptionsMonitor optionsMonitor) { ArgumentNullException.ThrowIfNull(optionsMonitor); - ArgumentNullException.ThrowIfNull(applicationInfo); ConsulDiscoveryOptions options = optionsMonitor.CurrentValue; var agentServiceRegistration = new AgentServiceRegistration { - ID = GetInstanceId(options, applicationInfo), - Address = options.HostName + ID = options.InstanceId, + Address = options.HostName, + Name = options.ServiceName, + Tags = CreateTags(options), + Meta = CreateMetadata(options) }; - string appName = applicationInfo.GetApplicationNameInContext(SteeltoeComponent.Discovery, $"{ConsulDiscoveryOptions.ConfigurationPrefix}:serviceName"); - - agentServiceRegistration.Name = NormalizeForConsul(appName); - agentServiceRegistration.Tags = CreateTags(options); - agentServiceRegistration.Meta = CreateMetadata(options); - if (options.Port > 0) { agentServiceRegistration.Port = options.Port; @@ -136,65 +125,6 @@ private static string[] CreateTags(ConsulDiscoveryOptions options) return options.Tags.ToArray(); } - private static string GetInstanceId(ConsulDiscoveryOptions options, IApplicationInstanceInfo applicationInfo) - { - if (string.IsNullOrEmpty(options.InstanceId)) - { - return NormalizeForConsul(GetDefaultInstanceId(applicationInfo)); - } - - return NormalizeForConsul(options.InstanceId); - } - - private static string GetDefaultInstanceId(IApplicationInstanceInfo applicationInfo) - { - string appName = applicationInfo.GetApplicationNameInContext(SteeltoeComponent.Discovery, $"{ConsulDiscoveryOptions.ConfigurationPrefix}:serviceName"); - - string instanceId = applicationInfo.InstanceId; - - if (string.IsNullOrEmpty(instanceId)) - { - instanceId = Random.Shared.Next().ToString(CultureInfo.InvariantCulture); - } - - return $"{appName}:{instanceId}"; - } - - internal static string NormalizeForConsul(string serviceId) - { - if (serviceId == null || !char.IsLetter(serviceId[0]) || !char.IsLetterOrDigit(serviceId[^1])) - { - throw new ArgumentException( - $"Consul service IDs must not be empty, must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen: {serviceId}", - nameof(serviceId)); - } - - var normalized = new StringBuilder(); - char prev = default; - - foreach (char ch in serviceId) - { - char toAppend = default; - - if (char.IsLetterOrDigit(ch)) - { - toAppend = ch; - } - else if (prev is default(char) or not Separator) - { - toAppend = Separator; - } - - if (toAppend != default(char)) - { - normalized.Append(toAppend); - prev = toAppend; - } - } - - return normalized.ToString(); - } - internal static AgentServiceCheck CreateCheck(int port, ConsulDiscoveryOptions options) { var check = new AgentServiceCheck(); diff --git a/src/Discovery/src/Eureka/ConfigurationSchema.json b/src/Discovery/src/Eureka/ConfigurationSchema.json index 83f27ff9d8..9d71fcd9e4 100644 --- a/src/Discovery/src/Eureka/ConfigurationSchema.json +++ b/src/Discovery/src/Eureka/ConfigurationSchema.json @@ -31,7 +31,7 @@ "description": "Gets or sets the local path to a private key file on disk (optional)." } }, - "description": "Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." + "description": "Configuration settings for certificate access. Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." } } }, @@ -277,9 +277,11 @@ "type": "object", "properties": { "Name": { - "type": "string" + "type": "string", + "description": "Gets or sets the name of this application." } - } + }, + "description": "Fallback configuration settings that describe this application." }, "Cloud": { "type": "object", @@ -288,12 +290,15 @@ "type": "object", "properties": { "Enabled": { - "type": "boolean" + "type": "boolean", + "description": "Gets or sets a value indicating whether to enable the Eureka client. Default value: true." }, "RegistrationMethod": { - "type": "string" + "type": "string", + "description": "Gets or sets how to register on Cloud Foundry. Can be \"route\", \"direct\", or \"hostname\"." } - } + }, + "description": "Fallback configuration settings for Eureka." }, "Inet": { "type": "object", diff --git a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs index 08eaa40c66..1df32ca4a5 100644 --- a/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs +++ b/src/Discovery/src/Eureka/EurekaServiceCollectionExtensions.cs @@ -41,7 +41,7 @@ public static IServiceCollection AddEurekaDiscoveryClient(this IServiceCollectio private static void ConfigureEurekaServices(IServiceCollection services) { - services.RegisterDefaultApplicationInstanceInfo(); + services.AddApplicationInstanceInfo(); services.TryAddSingleton(); ConfigureEurekaClientOptions(services); diff --git a/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs b/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs index 57a585e4e1..bce7a1c166 100644 --- a/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs +++ b/src/Discovery/src/Eureka/PostConfigureEurekaInstanceOptions.cs @@ -69,7 +69,7 @@ private void SetHostNameAndIpAddress(EurekaInstanceOptions options) { if (!options.IsForceHostNameMethod()) { - string? firstAppUri = _appInfo.Uris?.FirstOrDefault(); + string? firstAppUri = _appInfo.Uris.FirstOrDefault(); if (!string.IsNullOrWhiteSpace(firstAppUri)) { @@ -130,8 +130,7 @@ private void SetAppName(EurekaInstanceOptions options) { if (string.IsNullOrWhiteSpace(options.AppName)) { - string? springAppName = _appInfo.GetApplicationNameInContext(SteeltoeComponent.Discovery); - options.AppName = !string.IsNullOrWhiteSpace(springAppName) ? springAppName : "UNKNOWN"; + options.AppName = _appInfo.ApplicationName; } } @@ -145,7 +144,7 @@ private void SetInstanceId(EurekaInstanceOptions options) { if (options.IsGoRouterMethod()) { - string? firstAppUri = _appInfo.Uris?.FirstOrDefault(); + string? firstAppUri = _appInfo.Uris.FirstOrDefault(); if (!string.IsNullOrWhiteSpace(firstAppUri)) { diff --git a/src/Discovery/src/Eureka/Properties/AssemblyInfo.cs b/src/Discovery/src/Eureka/Properties/AssemblyInfo.cs index e188d84aae..30f86863a5 100644 --- a/src/Discovery/src/Eureka/Properties/AssemblyInfo.cs +++ b/src/Discovery/src/Eureka/Properties/AssemblyInfo.cs @@ -5,12 +5,13 @@ using System.Runtime.CompilerServices; using Aspire; using Steeltoe.Common.Certificates; +using Steeltoe.Common.Configuration; using Steeltoe.Common.Net; +using Steeltoe.Discovery.Eureka; using Steeltoe.Discovery.Eureka.Configuration; -[assembly: ConfigurationSchema("Spring:Application:Name", typeof(string))] -[assembly: ConfigurationSchema("Spring:Cloud:Discovery:Enabled", typeof(bool))] -[assembly: ConfigurationSchema("Spring:Cloud:Discovery:RegistrationMethod", typeof(string))] +[assembly: ConfigurationSchema("Spring:Application", typeof(SpringApplicationSettings))] +[assembly: ConfigurationSchema("Spring:Cloud:Discovery", typeof(SpringDiscoverySettings))] [assembly: ConfigurationSchema("Spring:Cloud:Inet", typeof(InetOptions))] [assembly: ConfigurationSchema("Certificates:Eureka", typeof(CertificateSettings))] [assembly: ConfigurationSchema("Eureka:Client", typeof(EurekaClientOptions))] diff --git a/src/Discovery/src/Eureka/SpringDiscoverySettings.cs b/src/Discovery/src/Eureka/SpringDiscoverySettings.cs new file mode 100644 index 0000000000..b9e882ec8a --- /dev/null +++ b/src/Discovery/src/Eureka/SpringDiscoverySettings.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +namespace Steeltoe.Discovery.Eureka; + +/// +/// Fallback configuration settings for Eureka. +/// +internal sealed class SpringDiscoverySettings +{ + // This type only exists to enable JSON schema documentation via ConfigurationSchemaAttribute. + + /// + /// Gets or sets a value indicating whether to enable the Eureka client. Default value: true. + /// + public bool Enabled { get; set; } = true; + + /// + /// Gets or sets how to register on Cloud Foundry. Can be "route", "direct", or "hostname". + /// + public string? RegistrationMethod { get; set; } +} diff --git a/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs b/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs index 042973179d..b26c26b7ee 100644 --- a/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs +++ b/src/Discovery/test/Consul.Test/Discovery/PostConfigureConsulDiscoveryOptionsTest.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; +using Steeltoe.Common.Extensions; using Steeltoe.Common.Net; using Steeltoe.Common.TestResources; using Steeltoe.Discovery.Consul.Configuration; @@ -57,6 +58,7 @@ public void DoesNotUseNetworkInterfacesByDefault() var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddSingleton(inetUtilsMock.Object); + services.AddApplicationInstanceInfo(); services.AddOptions().BindConfiguration(ConsulDiscoveryOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureConsulDiscoveryOptions>(); @@ -84,6 +86,7 @@ public void CanUseNetworkInterfaces() var services = new ServiceCollection(); services.AddSingleton(configuration); services.AddSingleton(inetUtilsMock.Object); + services.AddApplicationInstanceInfo(); services.AddOptions().BindConfiguration(ConsulDiscoveryOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureConsulDiscoveryOptions>(); @@ -112,6 +115,7 @@ public void CanUseNetworkInterfacesWithoutReverseDnsOnIP() services.AddSingleton(configuration); services.AddLogging(); services.AddSingleton(); + services.AddApplicationInstanceInfo(); services.AddOptions().BindConfiguration(ConsulDiscoveryOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureConsulDiscoveryOptions>(); @@ -126,4 +130,16 @@ public void CanUseNetworkInterfacesWithoutReverseDnsOnIP() Assert.NotNull(options.HostName); Assert.InRange(noSlowReverseDnsQuery.ElapsedMilliseconds, 0, 1500); // testing with an actual reverse dns query results in around 5000 ms } + + [Fact] + public void NormalizeForConsul_ReturnsExpected() + { + Assert.Equal("abc1", PostConfigureConsulDiscoveryOptions.NormalizeForConsul("abc1", "name")); + Assert.Equal("ab-c1", PostConfigureConsulDiscoveryOptions.NormalizeForConsul("ab:c1", "name")); + Assert.Equal("ab-c1", PostConfigureConsulDiscoveryOptions.NormalizeForConsul("ab::c1", "name")); + + Assert.Throws(() => PostConfigureConsulDiscoveryOptions.NormalizeForConsul("9abc", "name")); + Assert.Throws(() => PostConfigureConsulDiscoveryOptions.NormalizeForConsul(":abc", "name")); + Assert.Throws(() => PostConfigureConsulDiscoveryOptions.NormalizeForConsul("abc:", "name")); + } } diff --git a/src/Discovery/test/Consul.Test/Registry/ConsulRegistrationTest.cs b/src/Discovery/test/Consul.Test/Registry/ConsulRegistrationTest.cs index 3402cb14e5..37e1e69c94 100644 --- a/src/Discovery/test/Consul.Test/Registry/ConsulRegistrationTest.cs +++ b/src/Discovery/test/Consul.Test/Registry/ConsulRegistrationTest.cs @@ -4,10 +4,7 @@ using System.Reflection; using Consul; -using Microsoft.Extensions.Configuration; -using Steeltoe.Common; using Steeltoe.Common.TestResources; -using Steeltoe.Configuration.CloudFoundry; using Steeltoe.Discovery.Consul.Configuration; using Steeltoe.Discovery.Consul.Registry; using Steeltoe.Discovery.Consul.Util; @@ -55,20 +52,14 @@ public void Constructor_SetsProperties() [Fact] public void CreateTags_ReturnsExpected() { - var options = new ConsulDiscoveryOptions + var appSettings = new Dictionary { - Tags = - { - "foo", - "bar" - }, - InstanceZone = "instancezone", - InstanceGroup = "instancegroup", - Scheme = "https" + ["consul:discovery:serviceName"] = "some", + ["consul:discovery:tags:0"] = "foo", + ["consul:discovery:tags:1"] = "bar" }; - var optionsMonitor = new TestOptionsMonitor(options); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(new ConfigurationBuilder().Build())); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); Assert.Equal(2, registration.Tags.Count); Assert.Contains("foo", registration.Tags); @@ -78,20 +69,17 @@ public void CreateTags_ReturnsExpected() [Fact] public void CreateMetadata_ReturnsExpected() { - var options = new ConsulDiscoveryOptions + var appSettings = new Dictionary { - Metadata = - { - ["foo"] = "bar", - ["baz"] = "qux" - }, - InstanceZone = "instancezone", - InstanceGroup = "instancegroup", - Scheme = "https" + ["consul:discovery:serviceName"] = "some", + ["consul:discovery:metadata:foo"] = "bar", + ["consul:discovery:metadata:baz"] = "qux", + ["consul:discovery:instanceZone"] = "instanceZone", + ["consul:discovery:instanceGroup"] = "instanceGroup", + ["consul:discovery:scheme"] = "https" }; - var optionsMonitor = new TestOptionsMonitor(options); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(new ConfigurationBuilder().Build())); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); IReadOnlyDictionary metadata = registration.Metadata; Assert.Equal(5, metadata.Keys.Count()); @@ -103,10 +91,10 @@ public void CreateMetadata_ReturnsExpected() Assert.Equal("qux", metadata["baz"]); Assert.Contains(metadata, x => x.Key == "zone"); - Assert.Equal("instancezone", metadata["zone"]); + Assert.Equal("instanceZone", metadata["zone"]); Assert.Contains(metadata, x => x.Key == "group"); - Assert.Equal("instancegroup", metadata["group"]); + Assert.Equal("instanceGroup", metadata["group"]); Assert.Contains(metadata, x => x.Key == "secure"); Assert.Equal("true", metadata["secure"]); @@ -115,42 +103,21 @@ public void CreateMetadata_ReturnsExpected() [Fact] public void AppName_SetAsExpected() { - var optionsMonitor = new TestOptionsMonitor(); var appsettings = new Dictionary(); - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - var appInstanceInfo = new ApplicationInstanceInfo(configuration); // default value is assembly name - var result = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); - Assert.Equal(Assembly.GetEntryAssembly()!.GetName().Name!.Replace('.', '-'), result.ServiceId); + ConsulRegistration registration = TestRegistrationFactory.Create(appsettings, false); + Assert.Equal(Assembly.GetEntryAssembly()!.GetName().Name!.Replace('.', '-'), registration.ServiceId); // followed by spring:application:name appsettings.Add("spring:application:name", "SpringApplicationName"); - configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - appInstanceInfo = new ApplicationInstanceInfo(configuration); - result = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); - Assert.Equal("SpringApplicationName", result.ServiceId); - - // Platform app name overrides spring name - appsettings.Add("application:name", "PlatformName"); - configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - appInstanceInfo = new ApplicationInstanceInfo(configuration); - result = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); - Assert.Equal("PlatformName", result.ServiceId); - - // Consul-specific value beats generic value - appsettings.Add("consul:serviceName", "ConsulServiceName"); - configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - appInstanceInfo = new ApplicationInstanceInfo(configuration); - result = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); - Assert.Equal("ConsulServiceName", result.ServiceId); + registration = TestRegistrationFactory.Create(appsettings, false); + Assert.Equal("SpringApplicationName", registration.ServiceId); // Consul-discovery is the highest priority appsettings.Add("consul:discovery:serviceName", "ConsulDiscoveryServiceName"); - configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - appInstanceInfo = new ApplicationInstanceInfo(configuration); - result = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); - Assert.Equal("ConsulDiscoveryServiceName", result.ServiceId); + registration = TestRegistrationFactory.Create(appsettings, false); + Assert.Equal("ConsulDiscoveryServiceName", registration.ServiceId); } [Fact] @@ -161,60 +128,31 @@ public void GetDefaultInstanceId_ReturnsExpected() { "consul:discovery:serviceName", "serviceName" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - - var optionsMonitor = new TestOptionsMonitor(); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); - + ConsulRegistration registration = TestRegistrationFactory.Create(appsettings, false); Assert.StartsWith("serviceName-", registration.InstanceId, StringComparison.Ordinal); - appsettings.Add("spring:application:instance_id", "springid"); - configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); - Assert.Equal("serviceName-springid", registration.InstanceId); - - appsettings.Add("vcap:application:instance_id", "vcapid"); - configuration = new ConfigurationBuilder().AddInMemoryCollection(appsettings).Build(); - registration = ConsulRegistration.Create(optionsMonitor, new CloudFoundryApplicationOptions(configuration)); - Assert.Equal("serviceName-vcapid", registration.InstanceId); + appsettings.Add("vcap:application:instance_id", "vcapId"); + registration = TestRegistrationFactory.Create(appsettings, true); + Assert.Equal("serviceName-vcapId", registration.InstanceId); } [Fact] public void GetInstanceId_ReturnsExpected() { - var options = new ConsulDiscoveryOptions + var appSettings = new Dictionary { - InstanceId = "instanceId" + ["consul:discovery:instanceId"] = "instanceId", + ["spring:application:name"] = "foobar" }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary - { - { "spring:application:name", "foobar" } - }).Build(); - - var optionsMonitor = new TestOptionsMonitor(options); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); - + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); Assert.Equal("instanceId", registration.InstanceId); - options.InstanceId = null; - - registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); + appSettings.Remove("consul:discovery:instanceId"); + registration = TestRegistrationFactory.Create(appSettings, false); Assert.StartsWith("foobar-", registration.InstanceId, StringComparison.Ordinal); } - [Fact] - public void NormalizeForConsul_ReturnsExpected() - { - Assert.Equal("abc1", ConsulRegistration.NormalizeForConsul("abc1")); - Assert.Equal("ab-c1", ConsulRegistration.NormalizeForConsul("ab:c1")); - Assert.Equal("ab-c1", ConsulRegistration.NormalizeForConsul("ab::c1")); - - Assert.Throws(() => ConsulRegistration.NormalizeForConsul("9abc")); - Assert.Throws(() => ConsulRegistration.NormalizeForConsul(":abc")); - Assert.Throws(() => ConsulRegistration.NormalizeForConsul("abc:")); - } - [Fact] public void CreateCheck_ReturnsExpected() { @@ -242,29 +180,24 @@ public void CreateCheck_ReturnsExpected() [Fact] public void CreateRegistration_ReturnsExpected() { - var options = new ConsulDiscoveryOptions + var appSettings = new Dictionary { - HostName = "some-host", - Port = 1100 + { "spring:application:name", "foobar" }, + { "consul:discovery:hostName", "some-host" }, + { "consul:discovery:port", "1100" } }; - IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary - { - { "spring:application:name", "foobar" } - }).Build(); - - var optionsMonitor = new TestOptionsMonitor(options); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); Assert.StartsWith("foobar-", registration.InstanceId, StringComparison.Ordinal); Assert.False(registration.IsSecure); Assert.Equal("foobar", registration.ServiceId); - Assert.Equal(options.HostName, registration.Host); + Assert.Equal("some-host", registration.Host); Assert.Equal(1100, registration.Port); - Assert.Equal(new Uri($"http://{options.HostName}:1100"), registration.Uri); + Assert.Equal(new Uri("http://some-host:1100"), registration.Uri); Assert.NotNull(registration.InnerRegistration); - Assert.Equal(options.HostName, registration.InnerRegistration.Address); + Assert.Equal("some-host", registration.InnerRegistration.Address); Assert.StartsWith("foobar-", registration.InnerRegistration.ID, StringComparison.Ordinal); Assert.Equal("foobar", registration.InnerRegistration.Name); Assert.Equal(1100, registration.InnerRegistration.Port); diff --git a/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistrarTest.cs b/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistrarTest.cs index 51fa55b946..4b434d0b2f 100644 --- a/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistrarTest.cs +++ b/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistrarTest.cs @@ -3,10 +3,8 @@ // See the LICENSE file in the project root for more information. using Consul; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Moq; -using Steeltoe.Common; using Steeltoe.Common.TestResources; using Steeltoe.Discovery.Consul.Configuration; using Steeltoe.Discovery.Consul.Registry; @@ -21,8 +19,7 @@ public sealed class ConsulServiceRegistrarTest public async Task Start_CallsRegistry() { var optionsMonitor = new TestOptionsMonitor(); - var appInstanceInfo = new ApplicationInstanceInfo(new ConfigurationBuilder().Build()); - var registration = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); + ConsulRegistration registration = TestRegistrationFactory.Create(new Dictionary(), false); (Mock clientMock, Mock agentMock) = CreateConsulClientAgentMock(registration); await using var registry = new ConsulServiceRegistry(clientMock.Object, optionsMonitor, null, NullLogger.Instance); @@ -37,13 +34,12 @@ public async Task Start_CallsRegistry() [Fact] public async Task Start_DoesNotCallRegistry() { - var optionsMonitor = new TestOptionsMonitor(new ConsulDiscoveryOptions + var optionsMonitor = TestOptionsMonitor.Create(new ConsulDiscoveryOptions { Register = false }); - var appInstanceInfo = new ApplicationInstanceInfo(new ConfigurationBuilder().Build()); - var registration = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); + ConsulRegistration registration = TestRegistrationFactory.Create(new Dictionary(), false); (Mock clientMock, Mock agentMock) = CreateConsulClientAgentMock(registration); await using var registry = new ConsulServiceRegistry(clientMock.Object, optionsMonitor, null, NullLogger.Instance); @@ -58,13 +54,12 @@ public async Task Start_DoesNotCallRegistry() [Fact] public async Task Start_DoesNotStart() { - var optionsMonitor = new TestOptionsMonitor(new ConsulDiscoveryOptions + var optionsMonitor = TestOptionsMonitor.Create(new ConsulDiscoveryOptions { Enabled = false }); - var appInstanceInfo = new ApplicationInstanceInfo(new ConfigurationBuilder().Build()); - var registration = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); + ConsulRegistration registration = TestRegistrationFactory.Create(new Dictionary(), false); (Mock clientMock, Mock agentMock) = CreateConsulClientAgentMock(registration); await using var registry = new ConsulServiceRegistry(clientMock.Object, optionsMonitor, null, NullLogger.Instance); @@ -80,8 +75,7 @@ public async Task Start_DoesNotStart() public async Task Dispose_CallsRegistry() { var optionsMonitor = new TestOptionsMonitor(); - var appInstanceInfo = new ApplicationInstanceInfo(new ConfigurationBuilder().Build()); - var registration = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); + ConsulRegistration registration = TestRegistrationFactory.Create(new Dictionary(), false); (Mock clientMock, Mock agentMock) = CreateConsulClientAgentMock(registration); await using var registry = new ConsulServiceRegistry(clientMock.Object, optionsMonitor, null, NullLogger.Instance); @@ -99,13 +93,12 @@ public async Task Dispose_CallsRegistry() [Fact] public async Task Dispose_DoesNotCallRegistry() { - var optionsMonitor = new TestOptionsMonitor(new ConsulDiscoveryOptions + var optionsMonitor = TestOptionsMonitor.Create(new ConsulDiscoveryOptions { Deregister = false }); - var appInstanceInfo = new ApplicationInstanceInfo(new ConfigurationBuilder().Build()); - var registration = ConsulRegistration.Create(optionsMonitor, appInstanceInfo); + ConsulRegistration registration = TestRegistrationFactory.Create(new Dictionary(), false); (Mock clientMock, Mock agentMock) = CreateConsulClientAgentMock(registration); await using var registry = new ConsulServiceRegistry(clientMock.Object, optionsMonitor, null, NullLogger.Instance); diff --git a/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistryTest.cs b/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistryTest.cs index e825aa2250..c560ffae4b 100644 --- a/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistryTest.cs +++ b/src/Discovery/test/Consul.Test/Registry/ConsulServiceRegistryTest.cs @@ -3,10 +3,8 @@ // See the LICENSE file in the project root for more information. using Consul; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; using Moq; -using Steeltoe.Common; using Steeltoe.Common.TestResources; using Steeltoe.Discovery.Consul.Configuration; using Steeltoe.Discovery.Consul.Registry; @@ -26,13 +24,12 @@ public async Task RegisterAsync_CallsServiceRegister_AddsHeartbeatToScheduler() await using var scheduler = new TtlScheduler(optionsMonitor, clientMoq.Object, NullLoggerFactory.Instance); await using var registry = new ConsulServiceRegistry(clientMoq.Object, optionsMonitor, scheduler, NullLogger.Instance); - IConfigurationBuilder builder = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + var appSettings = new Dictionary { { "spring:application:name", "foobar" } - }); + }; - IConfiguration configuration = builder.Build(); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); await registry.RegisterAsync(registration, CancellationToken.None); agentMoq.Verify(endpoint => endpoint.ServiceRegister(registration.InnerRegistration, default), Times.Once); @@ -53,13 +50,12 @@ public async Task DeregisterAsync_CallsServiceDeregister_RemovesHeartbeatFromSch await using var scheduler = new TtlScheduler(optionsMonitor, clientMoq.Object, NullLoggerFactory.Instance); await using var registry = new ConsulServiceRegistry(clientMoq.Object, optionsMonitor, scheduler, NullLogger.Instance); - IConfigurationBuilder builder = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + var appSettings = new Dictionary { { "spring:application:name", "foobar" } - }); + }; - IConfiguration configuration = builder.Build(); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); await registry.RegisterAsync(registration, CancellationToken.None); agentMoq.Verify(endpoint => endpoint.ServiceRegister(registration.InnerRegistration, default), Times.Once); @@ -83,13 +79,12 @@ public async Task SetStatusAsync_ThrowsInvalidStatus() var optionsMonitor = new TestOptionsMonitor(); await using var scheduler = new TtlScheduler(optionsMonitor, clientMoq.Object, NullLoggerFactory.Instance); - IConfigurationBuilder builder = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + var appSettings = new Dictionary { { "spring:application:name", "foobar" } - }); + }; - IConfiguration configuration = builder.Build(); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); await using var registry = new ConsulServiceRegistry(clientMoq.Object, optionsMonitor, scheduler, NullLogger.Instance); await Assert.ThrowsAsync(async () => await registry.SetStatusAsync(registration, string.Empty, CancellationToken.None)); @@ -105,13 +100,12 @@ public async Task SetStatusAsync_CallsConsulClient() var optionsMonitor = new TestOptionsMonitor(); await using var scheduler = new TtlScheduler(optionsMonitor, clientMoq.Object, NullLoggerFactory.Instance); - IConfigurationBuilder builder = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + var appSettings = new Dictionary { { "spring:application:name", "foobar" } - }); + }; - IConfiguration configuration = builder.Build(); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); await using var registry = new ConsulServiceRegistry(clientMoq.Object, optionsMonitor, scheduler, NullLogger.Instance); await registry.SetStatusAsync(registration, "Up", CancellationToken.None); @@ -126,13 +120,12 @@ public async Task GetStatusAsync_ReturnsExpected() { var optionsMonitor = new TestOptionsMonitor(); - IConfigurationBuilder builder = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + var appSettings = new Dictionary { { "spring:application:name", "foobar" } - }); + }; - IConfiguration configuration = builder.Build(); - var registration = ConsulRegistration.Create(optionsMonitor, new ApplicationInstanceInfo(configuration)); + ConsulRegistration registration = TestRegistrationFactory.Create(appSettings, false); var queryResult = new QueryResult { diff --git a/src/Discovery/test/Consul.Test/Registry/TestRegistrationFactory.cs b/src/Discovery/test/Consul.Test/Registry/TestRegistrationFactory.cs new file mode 100644 index 0000000000..4904592a98 --- /dev/null +++ b/src/Discovery/test/Consul.Test/Registry/TestRegistrationFactory.cs @@ -0,0 +1,50 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Steeltoe.Common; +using Steeltoe.Common.Extensions; +using Steeltoe.Common.Net; +using Steeltoe.Common.TestResources; +using Steeltoe.Configuration.CloudFoundry; +using Steeltoe.Discovery.Consul.Configuration; +using Steeltoe.Discovery.Consul.Registry; + +namespace Steeltoe.Discovery.Consul.Test.Registry; + +internal static class TestRegistrationFactory +{ + public static ConsulRegistration Create(IDictionary appSettings, bool useCloudFoundry) + { + IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(appSettings).Build(); + + var services = new ServiceCollection(); + services.AddSingleton(configuration); + + if (useCloudFoundry) + { + services.AddCloudFoundryOptions(); + } + else + { + services.AddApplicationInstanceInfo(); + } + + ServiceProvider serviceProvider = services.BuildServiceProvider(true); + var appInfo = serviceProvider.GetRequiredService(); + + var options = new ConsulDiscoveryOptions(); + configuration.GetSection("consul:discovery").Bind(options); + + var inetUtilsMock = new Mock(new TestOptionsMonitor(), NullLogger.Instance); + var configurer = new PostConfigureConsulDiscoveryOptions(configuration, inetUtilsMock.Object, appInfo); + configurer.PostConfigure(null, options); + + TestOptionsMonitor optionsMonitor = TestOptionsMonitor.Create(options); + return ConsulRegistration.Create(optionsMonitor); + } +} diff --git a/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs b/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs index ad00a999ae..16a74d3fd9 100644 --- a/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs +++ b/src/Discovery/test/Eureka.Test/PostConfigureEurekaInstanceOptionsTest.cs @@ -136,8 +136,7 @@ public void Sets_configuration_from_spring() var appSettings = new Dictionary { ["spring:cloud:discovery:registrationMethod"] = "route", - ["spring:application:name"] = "myapp", - ["spring:application:instance_id"] = "test-instance-id" + ["spring:application:name"] = "myapp" }; using ServiceProvider serviceProvider = BuildTestServiceProvider(appSettings); @@ -146,7 +145,6 @@ public void Sets_configuration_from_spring() instanceOptions.RegistrationMethod.Should().Be("route"); instanceOptions.AppName.Should().Be("myapp"); - instanceOptions.InstanceId.Should().Be("test-instance-id"); instanceOptions.VipAddress.Should().Be("myapp"); instanceOptions.SecureVipAddress.Should().Be("myapp"); } @@ -158,10 +156,8 @@ public void Does_not_override_explicit_settings_with_spring_settings() { ["spring:cloud:discovery:registrationMethod"] = "route", ["spring:application:name"] = "myapp", - ["spring:application:instance_id"] = "test-instance-id", ["eureka:instance:RegistrationMethod"] = "explicit-registration-method", - ["eureka:instance:AppName"] = "explicit-app-name", - ["eureka:instance:InstanceId"] = "explicit-instance-id" + ["eureka:instance:AppName"] = "explicit-app-name" }; using ServiceProvider serviceProvider = BuildTestServiceProvider(appSettings); @@ -170,7 +166,6 @@ public void Does_not_override_explicit_settings_with_spring_settings() instanceOptions.RegistrationMethod.Should().Be("explicit-registration-method"); instanceOptions.AppName.Should().Be("explicit-app-name"); - instanceOptions.InstanceId.Should().Be("explicit-instance-id"); instanceOptions.VipAddress.Should().Be("explicit-app-name"); instanceOptions.SecureVipAddress.Should().Be("explicit-app-name"); } @@ -356,7 +351,7 @@ private static ServiceProvider BuildTestServiceProvider(Dictionary(); - services.RegisterDefaultApplicationInstanceInfo(); + services.AddApplicationInstanceInfo(); services.AddOptions().BindConfiguration(EurekaInstanceOptions.ConfigurationPrefix); services.AddSingleton, PostConfigureEurekaInstanceOptions>(); diff --git a/src/Discovery/test/Eureka.Test/Transport/EurekaClientTest.cs b/src/Discovery/test/Eureka.Test/Transport/EurekaClientTest.cs index b70bd6b611..3b4a9eb866 100644 --- a/src/Discovery/test/Eureka.Test/Transport/EurekaClientTest.cs +++ b/src/Discovery/test/Eureka.Test/Transport/EurekaClientTest.cs @@ -173,7 +173,7 @@ public async Task RegisterAsync_ThrowsOnErrorResponse() var services = new ServiceCollection(); services.AddLogging(options => options.SetMinimumLevel(LogLevel.Trace).AddProvider(capturingLoggerProvider)); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -268,7 +268,7 @@ public async Task RegisterAsync_LogsWarningOnCloudWithLocalhost() var services = new ServiceCollection(); services.AddLogging(options => options.SetMinimumLevel(LogLevel.Trace).AddProvider(capturingLoggerProvider)); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -331,7 +331,7 @@ public async Task RegisterAsync_SendsRequestToServer() var services = new ServiceCollection(); services.AddLogging(options => options.SetMinimumLevel(LogLevel.Trace).AddProvider(capturingLoggerProvider)); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -514,7 +514,7 @@ public async Task DeregisterAsync_SendsRequestToServer() { var services = new ServiceCollection(); services.AddLogging(); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -535,7 +535,7 @@ public async Task HeartbeatAsync_SendsRequestToServer() { var services = new ServiceCollection(); services.AddLogging(); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -559,7 +559,7 @@ public async Task GetApplicationsAsync_SendsRequestToServer() { var services = new ServiceCollection(); services.AddLogging(); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -599,7 +599,7 @@ public async Task GetApplicationsAsync_ThrowsOnBrokenJsonResponse() var services = new ServiceCollection(); services.AddLogging(options => options.SetMinimumLevel(LogLevel.Trace).AddProvider(capturingLoggerProvider)); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -631,7 +631,7 @@ public async Task GetDeltaAsync_SendsRequestToServer() { var services = new ServiceCollection(); services.AddLogging(); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); @@ -667,7 +667,7 @@ public async Task GetByVipAsync_SendsRequestToServer() { var services = new ServiceCollection(); services.AddLogging(); - services.AddOptions(); + services.AddOptions(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Discovery/test/HttpClients.Test/DiscoveryHostBuilderExtensionsTest.cs b/src/Discovery/test/HttpClients.Test/DiscoveryHostBuilderExtensionsTest.cs index 85e39eaf3c..69ec31a374 100644 --- a/src/Discovery/test/HttpClients.Test/DiscoveryHostBuilderExtensionsTest.cs +++ b/src/Discovery/test/HttpClients.Test/DiscoveryHostBuilderExtensionsTest.cs @@ -41,11 +41,12 @@ public void AddEurekaDiscoveryClient_IHostBuilder_AddsServiceDiscovery_Eureka() hostBuilder.ConfigureServices(services => services.AddEurekaDiscoveryClient()); using IHost host = hostBuilder.Build(); - IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); - DiscoveryClientHostedService? hostedService = host.Services.GetServices().OfType().FirstOrDefault(); + IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); Assert.Single(discoveryClients); Assert.IsType(discoveryClients[0]); + + DiscoveryClientHostedService? hostedService = host.Services.GetServices().OfType().SingleOrDefault(); Assert.NotNull(hostedService); } @@ -71,12 +72,12 @@ public void AddConsulDiscoveryClient_IHostBuilder_AddsServiceDiscovery_Consul() hostBuilder.ConfigureServices(services => services.AddConsulDiscoveryClient()); using IHost host = hostBuilder.Build(); - IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); - IHostedService? hostedService = host.Services.GetServices().FirstOrDefault(); + IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); Assert.Single(discoveryClients); Assert.IsType(discoveryClients[0]); + + DiscoveryClientHostedService? hostedService = host.Services.GetServices().OfType().SingleOrDefault(); Assert.NotNull(hostedService); - Assert.IsType(hostedService); } } diff --git a/src/Discovery/test/HttpClients.Test/DiscoveryWebApplicationBuilderExtensionsTest.cs b/src/Discovery/test/HttpClients.Test/DiscoveryWebApplicationBuilderExtensionsTest.cs index c7312795e8..7c1ac23ffc 100644 --- a/src/Discovery/test/HttpClients.Test/DiscoveryWebApplicationBuilderExtensionsTest.cs +++ b/src/Discovery/test/HttpClients.Test/DiscoveryWebApplicationBuilderExtensionsTest.cs @@ -43,7 +43,7 @@ public void AddEurekaDiscoveryClient_WebApplicationBuilder_AddsServiceDiscovery_ Assert.Single(discoveryClients); Assert.IsType(discoveryClients[0]); - Assert.Single(host.Services.GetServices().Where(service => service is DiscoveryClientHostedService)); + Assert.Single(host.Services.GetServices().OfType()); } [Fact] @@ -58,7 +58,7 @@ public void AddConsulDiscoveryClient_WebApplicationBuilder_AddsServiceDiscovery_ IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); Assert.Single(discoveryClients); Assert.IsType(discoveryClients[0]); - Assert.Single(host.Services.GetServices().Where(service => service is DiscoveryClientHostedService)); + Assert.Single(host.Services.GetServices().OfType()); } [Fact] diff --git a/src/Discovery/test/HttpClients.Test/DiscoveryWebHostBuilderExtensionsTest.cs b/src/Discovery/test/HttpClients.Test/DiscoveryWebHostBuilderExtensionsTest.cs index d53aa9516e..3da8d22091 100644 --- a/src/Discovery/test/HttpClients.Test/DiscoveryWebHostBuilderExtensionsTest.cs +++ b/src/Discovery/test/HttpClients.Test/DiscoveryWebHostBuilderExtensionsTest.cs @@ -42,13 +42,12 @@ public void AddEurekaDiscoveryClient_IWebHostBuilder_AddsServiceDiscovery_Eureka hostBuilder.ConfigureServices(services => services.AddEurekaDiscoveryClient()); using IWebHost host = hostBuilder.Build(); - IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); + IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); Assert.Single(discoveryClients); Assert.IsType(discoveryClients[0]); - IHostedService[] hostedServices = host.Services.GetServices().ToArray(); - Assert.Contains(hostedServices, hostedService => hostedService is DiscoveryClientHostedService); + Assert.Single(host.Services.GetServices().OfType()); } [Fact] @@ -61,11 +60,11 @@ public void AddConsulDiscoveryClient_IWebHostBuilder_AddsServiceDiscovery_Consul hostBuilder.ConfigureServices(services => services.AddConsulDiscoveryClient()); using IWebHost host = hostBuilder.Build(); - IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); - var hostedService = host.Services.GetService(); + IDiscoveryClient[] discoveryClients = host.Services.GetServices().ToArray(); Assert.Single(discoveryClients); Assert.IsType(discoveryClients[0]); - Assert.IsType(hostedService); + + Assert.Single(host.Services.GetServices().OfType()); } } diff --git a/src/Management/src/Endpoint/ConfigurationSchema.json b/src/Management/src/Endpoint/ConfigurationSchema.json index 910e88bdfe..1265b6a580 100644 --- a/src/Management/src/Endpoint/ConfigurationSchema.json +++ b/src/Management/src/Endpoint/ConfigurationSchema.json @@ -836,9 +836,11 @@ "type": "object", "properties": { "Name": { - "type": "string" + "type": "string", + "description": "Gets or sets the name of this application." } - } + }, + "description": "Fallback configuration settings that describe this application." }, "Boot": { "type": "object", diff --git a/src/Management/src/Endpoint/Properties/AssemblyInfo.cs b/src/Management/src/Endpoint/Properties/AssemblyInfo.cs index c9845cedf9..d9f72170f4 100644 --- a/src/Management/src/Endpoint/Properties/AssemblyInfo.cs +++ b/src/Management/src/Endpoint/Properties/AssemblyInfo.cs @@ -4,6 +4,7 @@ using System.Runtime.CompilerServices; using Aspire; +using Steeltoe.Common.Configuration; using Steeltoe.Management.Diagnostics; using Steeltoe.Management.Endpoint; using Steeltoe.Management.Endpoint.CloudFoundry; @@ -24,7 +25,7 @@ using Steeltoe.Management.Endpoint.Trace; using Steeltoe.Management.Endpoint.Web.Hypermedia; -[assembly: ConfigurationSchema("Spring:Application:Name", typeof(string))] +[assembly: ConfigurationSchema("Spring:Application", typeof(SpringApplicationSettings))] [assembly: ConfigurationSchema("Spring:Boot:Admin:Client", typeof(SpringBootAdminClientOptions))] [assembly: ConfigurationSchema("Management:CloudFoundry:Enabled", typeof(bool))] [assembly: ConfigurationSchema("Management:Endpoints", typeof(ManagementOptions))] diff --git a/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs b/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs index 1d8b11a23f..d63a2f0f8d 100755 --- a/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs +++ b/src/Management/src/Endpoint/RouteMappings/RouteMappingsEndpointHandler.cs @@ -69,12 +69,13 @@ private IDictionary> GetMappingDescriptio { var descriptor = (ControllerActionDescriptor)description.ActionDescriptor; AspNetCoreRouteDetails details = GetRouteDetails(description); - mappingDescriptions.TryGetValue(descriptor.ControllerTypeInfo.FullName!, out IList? descriptions); + string controllerTypeName = descriptor.ControllerTypeInfo.FullName!; + mappingDescriptions.TryGetValue(controllerTypeName, out IList? descriptions); if (descriptions == null) { descriptions = new List(); - mappingDescriptions.Add(descriptor.ControllerTypeInfo.FullName!, descriptions); + mappingDescriptions.Add(controllerTypeName, descriptions); } var routeMappingDescription = new RouteMappingDescription(descriptor.MethodInfo, details); @@ -92,12 +93,13 @@ private IDictionary> GetMappingDescriptio } AspNetCoreRouteDetails details = GetRouteDetails(descriptor); - mappingDescriptions.TryGetValue(controllerDescriptor.ControllerTypeInfo.FullName!, out IList? descriptions); + string controllerTypeName = controllerDescriptor.ControllerTypeInfo.FullName!; + mappingDescriptions.TryGetValue(controllerTypeName, out IList? descriptions); if (descriptions == null) { descriptions = new List(); - mappingDescriptions.Add(controllerDescriptor.ControllerTypeInfo.FullName!, descriptions); + mappingDescriptions.Add(controllerTypeName, descriptions); } var routeMappingDescription = new RouteMappingDescription(controllerDescriptor.MethodInfo, details); diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs b/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs index f2bdab7d80..145fe0993a 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/ConfigureSpringBootAdminClientOptions.cs @@ -33,11 +33,10 @@ public void Configure(SpringBootAdminClientOptions options) { _configuration.GetSection(ManagementInfoPrefix).Bind(options); - // Require base path to be supplied directly, in the configuration, or in the app instance info - options.BasePath ??= GetBasePath() ?? _applicationInstanceInfo.Uris?.FirstOrDefault() ?? + options.BasePath ??= GetBasePath() ?? throw new InvalidOperationException($"Please set {ManagementInfoPrefix}:BasePath in order to register with Spring Boot Admin"); - options.ApplicationName ??= _applicationInstanceInfo.GetApplicationNameInContext(SteeltoeComponent.Management); + options.ApplicationName ??= _applicationInstanceInfo.ApplicationName; } private string? GetBasePath() diff --git a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs index c84de2a3cc..598dbd33b0 100644 --- a/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs +++ b/src/Management/src/Endpoint/SpringBootAdminClient/ServiceCollectionExtensions.cs @@ -27,7 +27,7 @@ public static IServiceCollection AddSpringBootAdminClient(this IServiceCollectio { ArgumentNullException.ThrowIfNull(services); - services.RegisterDefaultApplicationInstanceInfo(); + services.AddApplicationInstanceInfo(); services.AddOptions(); services.TryAddEnumerable(ServiceDescriptor.Transient, ConfigureManagementOptions>()); diff --git a/src/Management/src/Tasks/ConfigurationSchema.json b/src/Management/src/Tasks/ConfigurationSchema.json index f6565a4c91..6fbf21b833 100644 --- a/src/Management/src/Tasks/ConfigurationSchema.json +++ b/src/Management/src/Tasks/ConfigurationSchema.json @@ -17,7 +17,9 @@ "type": "object", "properties": { "RunTask": { - "type": "string" + "type": "string", + "description": "Gets or sets the name of the registered 'Steeltoe.Common.IApplicationTask' to run." } - } + }, + "description": "Configuration settings for registered application tasks." } diff --git a/src/Management/src/Tasks/Properties/AssemblyInfo.cs b/src/Management/src/Tasks/Properties/AssemblyInfo.cs index 67594ca299..569662fd77 100644 --- a/src/Management/src/Tasks/Properties/AssemblyInfo.cs +++ b/src/Management/src/Tasks/Properties/AssemblyInfo.cs @@ -4,8 +4,9 @@ using System.Runtime.CompilerServices; using Aspire; +using Steeltoe.Management.Tasks; -[assembly: ConfigurationSchema("RunTask", typeof(string))] +[assembly: ConfigurationSchema("", typeof(TaskSettings))] [assembly: LoggingCategories("Steeltoe", "Steeltoe.Management", "Steeltoe.Management.Tasks")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Management/src/Tasks/TaskSettings.cs b/src/Management/src/Tasks/TaskSettings.cs new file mode 100644 index 0000000000..5e18f728f7 --- /dev/null +++ b/src/Management/src/Tasks/TaskSettings.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using Steeltoe.Common; + +namespace Steeltoe.Management.Tasks; + +/// +/// Configuration settings for registered application tasks. +/// +internal sealed class TaskSettings +{ + // This type only exists to enable JSON schema documentation via ConfigurationSchemaAttribute. + + /// + /// Gets or sets the name of the registered to run. + /// + public string? RunTask { get; set; } +} diff --git a/src/Management/src/Tracing/ConfigurationSchema.json b/src/Management/src/Tracing/ConfigurationSchema.json index 3a47ef73c1..d9cad3f898 100644 --- a/src/Management/src/Tracing/ConfigurationSchema.json +++ b/src/Management/src/Tracing/ConfigurationSchema.json @@ -43,6 +43,10 @@ "type": "integer", "description": "Gets or sets the maximum payload size in bytes. Default value: 4096." }, + "Name": { + "type": "string", + "description": "Gets or sets the name of this application." + }, "NeverSample": { "type": "boolean", "description": "Gets or sets a value indicating whether traces should NEVER be captured. Default value: false." @@ -70,9 +74,11 @@ "type": "object", "properties": { "Name": { - "type": "string" + "type": "string", + "description": "Gets or sets the name of this application." } - } + }, + "description": "Fallback configuration settings that describe this application." } } } diff --git a/src/Management/src/Tracing/ConfigureTracingOptions.cs b/src/Management/src/Tracing/ConfigureTracingOptions.cs new file mode 100644 index 0000000000..dfaf8048db --- /dev/null +++ b/src/Management/src/Tracing/ConfigureTracingOptions.cs @@ -0,0 +1,36 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using Steeltoe.Common; + +namespace Steeltoe.Management.Tracing; + +internal sealed class ConfigureTracingOptions : IConfigureOptions +{ + private const string DefaultIngressIgnorePattern = "/actuator/.*|/cloudfoundryapplication/.*|.*\\.png|.*\\.css|.*\\.js|.*\\.html|/favicon.ico|.*\\.gif"; + private const string DefaultEgressIgnorePattern = "/api/v2/spans|/v2/apps/.*/permissions|/eureka/*"; + + private readonly IConfiguration _configuration; + private readonly IApplicationInstanceInfo _applicationInstanceInfo; + + public ConfigureTracingOptions(IConfiguration configuration, IApplicationInstanceInfo applicationInstanceInfo) + { + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(applicationInstanceInfo); + + _configuration = configuration; + _applicationInstanceInfo = applicationInstanceInfo; + } + + public void Configure(TracingOptions options) + { + _configuration.GetSection("management:tracing").Bind(options); + + options.Name ??= _applicationInstanceInfo.ApplicationName; + options.IngressIgnorePattern ??= DefaultIngressIgnorePattern; + options.EgressIgnorePattern ??= DefaultEgressIgnorePattern; + } +} diff --git a/src/Management/src/Tracing/Properties/AssemblyInfo.cs b/src/Management/src/Tracing/Properties/AssemblyInfo.cs index 6c0f7c7b5f..1f1373def3 100644 --- a/src/Management/src/Tracing/Properties/AssemblyInfo.cs +++ b/src/Management/src/Tracing/Properties/AssemblyInfo.cs @@ -4,9 +4,10 @@ using System.Runtime.CompilerServices; using Aspire; +using Steeltoe.Common.Configuration; using Steeltoe.Management.Tracing; -[assembly: ConfigurationSchema("Spring:Application:Name", typeof(string))] +[assembly: ConfigurationSchema("Spring:Application", typeof(SpringApplicationSettings))] [assembly: ConfigurationSchema("Management:Tracing", typeof(TracingOptions))] [assembly: LoggingCategories("Steeltoe", "Steeltoe.Management", "Steeltoe.Management.Tracing")] diff --git a/src/Management/src/Tracing/PublicAPI.Unshipped.txt b/src/Management/src/Tracing/PublicAPI.Unshipped.txt index d0759de405..faabc047f3 100644 --- a/src/Management/src/Tracing/PublicAPI.Unshipped.txt +++ b/src/Management/src/Tracing/PublicAPI.Unshipped.txt @@ -7,7 +7,7 @@ Steeltoe.Management.Tracing.TracingBaseServiceCollectionExtensions Steeltoe.Management.Tracing.TracingCoreServiceCollectionExtensions Steeltoe.Management.Tracing.TracingLogProcessor Steeltoe.Management.Tracing.TracingLogProcessor.Process(string! message) -> string! -Steeltoe.Management.Tracing.TracingLogProcessor.TracingLogProcessor(Steeltoe.Management.Tracing.TracingOptions! options) -> void +Steeltoe.Management.Tracing.TracingLogProcessor.TracingLogProcessor(Microsoft.Extensions.Options.IOptionsMonitor! optionsMonitor) -> void Steeltoe.Management.Tracing.TracingOptions Steeltoe.Management.Tracing.TracingOptions.AlwaysSample.get -> bool Steeltoe.Management.Tracing.TracingOptions.AlwaysSample.set -> void @@ -20,12 +20,13 @@ Steeltoe.Management.Tracing.TracingOptions.IngressIgnorePattern.set -> void Steeltoe.Management.Tracing.TracingOptions.MaxPayloadSizeInBytes.get -> int Steeltoe.Management.Tracing.TracingOptions.MaxPayloadSizeInBytes.set -> void Steeltoe.Management.Tracing.TracingOptions.Name.get -> string? +Steeltoe.Management.Tracing.TracingOptions.Name.set -> void Steeltoe.Management.Tracing.TracingOptions.NeverSample.get -> bool Steeltoe.Management.Tracing.TracingOptions.NeverSample.set -> void Steeltoe.Management.Tracing.TracingOptions.PropagationType.get -> string? Steeltoe.Management.Tracing.TracingOptions.PropagationType.set -> void Steeltoe.Management.Tracing.TracingOptions.SingleB3Header.get -> bool Steeltoe.Management.Tracing.TracingOptions.SingleB3Header.set -> void -Steeltoe.Management.Tracing.TracingOptions.TracingOptions(Steeltoe.Common.IApplicationInstanceInfo? appInfo, Microsoft.Extensions.Configuration.IConfiguration! configuration) -> void +Steeltoe.Management.Tracing.TracingOptions.TracingOptions() -> void Steeltoe.Management.Tracing.TracingOptions.UseShortTraceIds.get -> bool Steeltoe.Management.Tracing.TracingOptions.UseShortTraceIds.set -> void diff --git a/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs b/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs index 1668be214f..900691a687 100644 --- a/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs +++ b/src/Management/src/Tracing/TracingBaseServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ // See the LICENSE file in the project root for more information. using System.Text.RegularExpressions; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; @@ -57,11 +56,10 @@ public static IServiceCollection AddDistributedTracing(this IServiceCollection s { ArgumentNullException.ThrowIfNull(services); - services.AddOptions(); - services.RegisterDefaultApplicationInstanceInfo(); + services.AddApplicationInstanceInfo(); - services.TryAddSingleton(serviceProvider => - new TracingOptions(serviceProvider.GetRequiredService(), serviceProvider.GetRequiredService())); + services.AddOptions(); + services.TryAddEnumerable(ServiceDescriptor.Singleton, ConfigureTracingOptions>()); services.ConfigureOptionsWithChangeTokenSource(); @@ -108,23 +106,24 @@ public static IServiceCollection AddDistributedTracing(this IServiceCollection s action?.Invoke(tracerProviderBuilder); }); - services.AddOptions().Configure((options, serviceProvider) => - { - var tracingOptions = serviceProvider.GetRequiredService(); - - if (tracingOptions.EgressIgnorePattern != null) + services.AddOptions().Configure>( + (instrumentationOptions, tracingOptionsMonitor) => { - var pathMatcher = new Regex(tracingOptions.EgressIgnorePattern, RegexOptions.None, TimeSpan.FromSeconds(1)); - options.FilterHttpRequestMessage += requestMessage => !pathMatcher.IsMatch(requestMessage.RequestUri?.PathAndQuery ?? string.Empty); - } - }); + TracingOptions tracingOptions = tracingOptionsMonitor.CurrentValue; + + if (tracingOptions.EgressIgnorePattern != null) + { + var pathMatcher = new Regex(tracingOptions.EgressIgnorePattern, RegexOptions.None, TimeSpan.FromSeconds(1)); + + instrumentationOptions.FilterHttpRequestMessage += requestMessage => + !pathMatcher.IsMatch(requestMessage.RequestUri?.PathAndQuery ?? string.Empty); + } + }); services.ConfigureOpenTelemetryTracerProvider((serviceProvider, tracerProviderBuilder) => { - string appName = serviceProvider.GetRequiredService() - .GetApplicationNameInContext(SteeltoeComponent.Management, $"{TracingOptions.ConfigurationPrefix}:name"); - - var tracingOptions = serviceProvider.GetRequiredService(); + var tracingOptionsMonitor = serviceProvider.GetRequiredService>(); + TracingOptions tracingOptions = tracingOptionsMonitor.CurrentValue; ILogger logger = serviceProvider.GetRequiredService() .CreateLogger($"{typeof(TracingBaseServiceCollectionExtensions).Namespace}.Setup"); @@ -132,7 +131,7 @@ public static IServiceCollection AddDistributedTracing(this IServiceCollection s logger.LogTrace("Found Zipkin exporter: {ExportToZipkin}. Found Jaeger exporter: {ExportToJaeger}. Found OTLP exporter: {ExportToOtlp}.", exportToZipkin, exportToJaeger, exportToOpenTelemetryProtocol); - tracerProviderBuilder.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(appName)); + tracerProviderBuilder.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(tracingOptions.Name!)); if (string.Equals(tracingOptions.PropagationType, "B3", StringComparison.OrdinalIgnoreCase)) { @@ -162,14 +161,16 @@ public static IServiceCollection AddDistributedTracing(this IServiceCollection s private static void ConfigureZipkinOptions(IServiceCollection services) { - services.AddOptions().PostConfigure((options, traceOpts) => + services.AddOptions().PostConfigure>((zipkinExporterOptions, tracingOptionsMonitor) => { - options.UseShortTraceIds = traceOpts.UseShortTraceIds; - options.MaxPayloadSizeInBytes = traceOpts.MaxPayloadSizeInBytes; + TracingOptions tracingOptions = tracingOptionsMonitor.CurrentValue; - if (traceOpts.ExporterEndpoint != null) + zipkinExporterOptions.UseShortTraceIds = tracingOptions.UseShortTraceIds; + zipkinExporterOptions.MaxPayloadSizeInBytes = tracingOptions.MaxPayloadSizeInBytes; + + if (tracingOptions.ExporterEndpoint != null) { - options.Endpoint = traceOpts.ExporterEndpoint; + zipkinExporterOptions.Endpoint = tracingOptions.ExporterEndpoint; } }); } @@ -181,14 +182,16 @@ private static void AddZipkinExporter(TracerProviderBuilder builder) private static void ConfigureJaegerOptions(IServiceCollection services) { - services.AddOptions().PostConfigure((options, traceOpts) => + services.AddOptions().PostConfigure>((jaegerExporterOptions, tracingOptionsMonitor) => { - options.MaxPayloadSizeInBytes = traceOpts.MaxPayloadSizeInBytes; + TracingOptions tracingOptions = tracingOptionsMonitor.CurrentValue; + + jaegerExporterOptions.MaxPayloadSizeInBytes = tracingOptions.MaxPayloadSizeInBytes; - if (traceOpts.ExporterEndpoint != null) + if (tracingOptions.ExporterEndpoint != null) { - options.AgentHost = traceOpts.ExporterEndpoint.Host; - options.AgentPort = traceOpts.ExporterEndpoint.Port; + jaegerExporterOptions.AgentHost = tracingOptions.ExporterEndpoint.Host; + jaegerExporterOptions.AgentPort = tracingOptions.ExporterEndpoint.Port; } }); } @@ -200,11 +203,13 @@ private static void AddJaegerExporter(TracerProviderBuilder builder) private static void ConfigureOpenTelemetryProtocolOptions(IServiceCollection services) { - services.AddOptions().PostConfigure((options, traceOpts) => + services.AddOptions().PostConfigure>((otlpExporterOptions, tracingOptionsMonitor) => { - if (traceOpts.ExporterEndpoint != null) + TracingOptions tracingOptions = tracingOptionsMonitor.CurrentValue; + + if (tracingOptions.ExporterEndpoint != null) { - options.Endpoint = traceOpts.ExporterEndpoint; + otlpExporterOptions.Endpoint = tracingOptions.ExporterEndpoint; } }); } diff --git a/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs b/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs index 38f8a3f709..4f627c927e 100644 --- a/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs +++ b/src/Management/src/Tracing/TracingCoreServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using System.Text.RegularExpressions; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using OpenTelemetry.Instrumentation.AspNetCore; using OpenTelemetry.Trace; @@ -43,14 +44,17 @@ public static IServiceCollection AddDistributedTracingAspNetCore(this IServiceCo action += builder => builder.AddAspNetCoreInstrumentation(); - services.AddOptions().PostConfigure((instrumentationOptions, tracingOptions) => - { - if (tracingOptions.IngressIgnorePattern != null) + services.AddOptions().PostConfigure>( + (instrumentationOptions, tracingOptionsMonitor) => { - var pathMatcher = new Regex(tracingOptions.IngressIgnorePattern, RegexOptions.None, TimeSpan.FromSeconds(1)); - instrumentationOptions.Filter += context => !pathMatcher.IsMatch(context.Request.Path); - } - }); + TracingOptions tracingOptions = tracingOptionsMonitor.CurrentValue; + + if (tracingOptions.IngressIgnorePattern != null) + { + var pathMatcher = new Regex(tracingOptions.IngressIgnorePattern, RegexOptions.None, TimeSpan.FromSeconds(1)); + instrumentationOptions.Filter += context => !pathMatcher.IsMatch(context.Request.Path); + } + }); return services.AddDistributedTracing(action); } diff --git a/src/Management/src/Tracing/TracingLogProcessor.cs b/src/Management/src/Tracing/TracingLogProcessor.cs index 6c09b5a359..7cde0c41c3 100644 --- a/src/Management/src/Tracing/TracingLogProcessor.cs +++ b/src/Management/src/Tracing/TracingLogProcessor.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Text; +using Microsoft.Extensions.Options; using OpenTelemetry.Trace; using Steeltoe.Logging; @@ -10,13 +11,13 @@ namespace Steeltoe.Management.Tracing; public sealed class TracingLogProcessor : IDynamicMessageProcessor { - private readonly TracingOptions _options; + private readonly IOptionsMonitor _optionsMonitor; - public TracingLogProcessor(TracingOptions options) + public TracingLogProcessor(IOptionsMonitor optionsMonitor) { - ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(optionsMonitor); - _options = options; + _optionsMonitor = optionsMonitor; } public string Process(string message) @@ -27,15 +28,17 @@ public string Process(string message) if (currentSpan != null) { + TracingOptions options = _optionsMonitor.CurrentValue; + SpanContext context = currentSpan.Context; var sb = new StringBuilder(" ["); - sb.Append(_options.Name); + sb.Append(options.Name); sb.Append(','); string traceId = context.TraceId.ToHexString(); - if (traceId.Length > 16 && _options.UseShortTraceIds) + if (traceId.Length > 16 && options.UseShortTraceIds) { traceId = traceId.Substring(traceId.Length - 16, 16); } diff --git a/src/Management/src/Tracing/TracingOptions.cs b/src/Management/src/Tracing/TracingOptions.cs index bf0d09bf96..78badc2554 100644 --- a/src/Management/src/Tracing/TracingOptions.cs +++ b/src/Management/src/Tracing/TracingOptions.cs @@ -2,23 +2,14 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using Microsoft.Extensions.Configuration; -using Steeltoe.Common; - namespace Steeltoe.Management.Tracing; public sealed class TracingOptions { - internal const string ConfigurationPrefix = "management:tracing"; - internal const string DefaultIngressIgnorePattern = "/actuator/.*|/cloudfoundryapplication/.*|.*\\.png|.*\\.css|.*\\.js|.*\\.html|/favicon.ico|.*\\.gif"; - internal const string DefaultEgressIgnorePattern = "/api/v2/spans|/v2/apps/.*/permissions|/eureka/*"; - - private readonly IApplicationInstanceInfo? _applicationInstanceInfo; - /// - /// Gets the name of the application. + /// Gets or sets the name of this application. /// - public string? Name => _applicationInstanceInfo?.GetApplicationNameInContext(SteeltoeComponent.Management, $"{ConfigurationPrefix}:name"); + public string? Name { get; set; } /// /// Gets or sets a regular expression for requests coming into this application that should not be traced. Default value: @@ -73,24 +64,4 @@ public sealed class TracingOptions /// Gets or sets the endpoint used for exporting traces. /// public Uri? ExporterEndpoint { get; set; } - - public TracingOptions(IApplicationInstanceInfo? appInfo, IConfiguration configuration) - { - ArgumentNullException.ThrowIfNull(configuration); - - IConfigurationSection section = configuration.GetSection(ConfigurationPrefix); - section.Bind(this); - - _applicationInstanceInfo = appInfo; - - if (string.IsNullOrEmpty(IngressIgnorePattern)) - { - IngressIgnorePattern = DefaultIngressIgnorePattern; - } - - if (string.IsNullOrEmpty(EgressIgnorePattern)) - { - EgressIgnorePattern = DefaultEgressIgnorePattern; - } - } } diff --git a/src/Management/test/Endpoint.Test/BaseTest.cs b/src/Management/test/Endpoint.Test/BaseTest.cs index a823f34eb5..9b2b4af4dc 100644 --- a/src/Management/test/Endpoint.Test/BaseTest.cs +++ b/src/Management/test/Endpoint.Test/BaseTest.cs @@ -7,7 +7,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; -using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Management.Endpoint.Health; using Steeltoe.Management.Endpoint.Metrics; using Steeltoe.Management.Endpoint.Metrics.SystemDiagnosticsMetrics; @@ -103,7 +103,7 @@ private static IOptionsMonitor GetOptionsMonitorFromSettings var services = new ServiceCollection(); services.AddSingleton(configurationRoot); - services.AddSingleton(new ApplicationInstanceInfo(configurationRoot, string.Empty)); + services.AddApplicationInstanceInfo(); services.ConfigureOptions(configureOptionsType); services.AddLogging(); diff --git a/src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs b/src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs index 63951c6dd1..00bbccbac3 100644 --- a/src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs +++ b/src/Management/test/Endpoint.Test/ConfigureOptionsTest.cs @@ -24,7 +24,7 @@ public void Does_not_register_options_configurer_multiple_times() services.AddInfoActuator(); services.AddEnvironmentActuator(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); + ServiceProvider serviceProvider = services.BuildServiceProvider(true); IConfigureOptions[] configurers = serviceProvider.GetServices>().ToArray(); configurers.Should().HaveCount(1); @@ -44,7 +44,7 @@ public void Can_register_additional_options_configurer_upfront() services.AddTransient, CustomManagementOptionsConfigurer>(); services.AddInfoActuator(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); + ServiceProvider serviceProvider = services.BuildServiceProvider(true); IConfigureOptions[] configurers = serviceProvider.GetServices>().ToArray(); configurers.Should().HaveCount(2); @@ -66,7 +66,7 @@ public void Can_register_additional_options_configurer_afterwards() services.AddInfoActuator(); services.AddTransient, CustomManagementOptionsConfigurer>(); - ServiceProvider serviceProvider = services.BuildServiceProvider(); + ServiceProvider serviceProvider = services.BuildServiceProvider(true); IConfigureOptions[] configurers = serviceProvider.GetServices>().ToArray(); configurers.Should().HaveCount(2); diff --git a/src/Management/test/Endpoint.Test/Environment/EndpointServiceCollectionTest.cs b/src/Management/test/Endpoint.Test/Environment/EndpointServiceCollectionTest.cs index ca8fff1730..26312f593c 100644 --- a/src/Management/test/Endpoint.Test/Environment/EndpointServiceCollectionTest.cs +++ b/src/Management/test/Endpoint.Test/Environment/EndpointServiceCollectionTest.cs @@ -23,7 +23,8 @@ public void AddEnvironmentActuator_AddsCorrectServices() var appSettings = new Dictionary { ["management:endpoints:enabled"] = "false", - ["management:endpoints:path"] = "/cloudfoundryapplication" + ["management:endpoints:path"] = "/cloudfoundryapplication", + ["management:endpoints:env:path"] = "/some" }; var configurationBuilder = new ConfigurationBuilder(); @@ -34,8 +35,9 @@ public void AddEnvironmentActuator_AddsCorrectServices() services.AddEnvironmentActuator(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var options = serviceProvider.GetService>(); - Assert.NotNull(options); + var options = serviceProvider.GetRequiredService>(); + Assert.Equal("/some", options.CurrentValue.Path); + var handler = serviceProvider.GetService(); Assert.NotNull(handler); } diff --git a/src/Management/test/Endpoint.Test/Metrics/EndpointServiceCollectionExtensionsTest.cs b/src/Management/test/Endpoint.Test/Metrics/EndpointServiceCollectionExtensionsTest.cs index 6b3eaf134b..d39ef5109b 100644 --- a/src/Management/test/Endpoint.Test/Metrics/EndpointServiceCollectionExtensionsTest.cs +++ b/src/Management/test/Endpoint.Test/Metrics/EndpointServiceCollectionExtensionsTest.cs @@ -17,9 +17,10 @@ public sealed class EndpointServiceCollectionExtensionsTest : BaseTest [Fact] public void AddMetricsActuator_AddsCorrectServices() { - var services = new ServiceCollection(); - IConfiguration configuration = GetConfiguration(); + var builder = new ConfigurationBuilder(); + IConfiguration configuration = builder.Build(); + var services = new ServiceCollection(); services.AddOptions(); services.AddLogging(); services.AddSingleton(HostingHelpers.GetHostingEnvironment()); @@ -28,24 +29,15 @@ public void AddMetricsActuator_AddsCorrectServices() ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var diagnosticsManager = serviceProvider.GetService(); - Assert.NotNull(diagnosticsManager); - var hostedService = serviceProvider.GetService(); - Assert.NotNull(hostedService); - var optionsMonitor = serviceProvider.GetRequiredService>(); - Assert.NotNull(optionsMonitor.CurrentValue); + serviceProvider.GetService().Should().NotBeNull(); + serviceProvider.GetServices().OfType().Should().HaveCount(1); - IEnumerable observers = serviceProvider.GetServices(); - List list = observers.ToList(); - Assert.NotEmpty(list); + var optionsMonitor = serviceProvider.GetRequiredService>(); + optionsMonitor.CurrentValue.EgressIgnorePattern.Should().NotBeNullOrEmpty(); - var handler = serviceProvider.GetService(); - Assert.NotNull(handler); - } + IDiagnosticObserver[] observers = serviceProvider.GetServices().ToArray(); + observers.Should().NotBeEmpty(); - private IConfiguration GetConfiguration() - { - var builder = new ConfigurationBuilder(); - return builder.Build(); + serviceProvider.GetService().Should().NotBeNull(); } } diff --git a/src/Management/test/Endpoint.Test/Metrics/MetricsEndpointTest.cs b/src/Management/test/Endpoint.Test/Metrics/MetricsEndpointTest.cs index 1ad27eca34..bbaa7216d8 100644 --- a/src/Management/test/Endpoint.Test/Metrics/MetricsEndpointTest.cs +++ b/src/Management/test/Endpoint.Test/Metrics/MetricsEndpointTest.cs @@ -31,7 +31,7 @@ public async Task Invoke_WithNullMetricsRequest_ReturnsExpected() services.AddMetricsActuatorServices(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); @@ -65,7 +65,7 @@ public async Task Invoke_WithNullMetricsRequest_ReturnsExpected() services.AddMetricsActuatorServices(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); @@ -97,7 +97,7 @@ public async Task Invoke_WithMetricsRequest_ReturnsExpected() services.AddMetricsActuatorServices(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); @@ -166,7 +166,7 @@ public async Task Invoke_WithMetricsRequest_ReturnsExpected_IncludesAdditionalIn services.AddMetricsActuator(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); @@ -233,7 +233,7 @@ public async Task GetMetricSamples_ReturnsExpectedCounter() services.AddMetricsActuatorServices(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); @@ -267,7 +267,7 @@ public async Task GetAvailableTags_ReturnsExpected() services.AddMetricsActuatorServices(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); @@ -345,7 +345,7 @@ public async Task GetMetricMeasurements_ReturnsExpected() services.AddMetricsActuatorServices(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); @@ -524,7 +524,7 @@ public async Task GetMetric_ReturnsExpected() services.AddMetricsActuatorServices(); }; - MetricCollectionHostedService service = testContext.GetServices().OfType().First(); + MetricCollectionHostedService service = testContext.GetServices().OfType().Single(); await service.StartAsync(CancellationToken.None); diff --git a/src/Management/test/Endpoint.Test/Refresh/EndpointServiceCollectionTest.cs b/src/Management/test/Endpoint.Test/Refresh/EndpointServiceCollectionTest.cs index 4b0c3a96fe..55634e8fff 100644 --- a/src/Management/test/Endpoint.Test/Refresh/EndpointServiceCollectionTest.cs +++ b/src/Management/test/Endpoint.Test/Refresh/EndpointServiceCollectionTest.cs @@ -19,7 +19,8 @@ public void AddRefreshActuator_AddsCorrectServices() var appSettings = new Dictionary { ["management:endpoints:enabled"] = "false", - ["management:endpoints:path"] = "/cloudfoundryapplication" + ["management:endpoints:path"] = "/cloudfoundryapplication", + ["management:endpoints:refresh:path"] = "/some" }; var configurationBuilder = new ConfigurationBuilder(); @@ -30,8 +31,9 @@ public void AddRefreshActuator_AddsCorrectServices() services.AddRefreshActuator(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var options = serviceProvider.GetService>(); - Assert.NotNull(options); + var options = serviceProvider.GetRequiredService>(); + Assert.Equal("/some", options.CurrentValue.Path); + var handler = serviceProvider.GetService(); Assert.NotNull(handler); } diff --git a/src/Management/test/Endpoint.Test/Services/EndpointServiceCollectionTest.cs b/src/Management/test/Endpoint.Test/Services/EndpointServiceCollectionTest.cs index 20f870ef04..db412bec3b 100644 --- a/src/Management/test/Endpoint.Test/Services/EndpointServiceCollectionTest.cs +++ b/src/Management/test/Endpoint.Test/Services/EndpointServiceCollectionTest.cs @@ -19,7 +19,8 @@ public void AddServicesActuator_AddsCorrectServices() var appSettings = new Dictionary { ["management:endpoints:enabled"] = "false", - ["management:endpoints:path"] = "/cloudfoundryapplication" + ["management:endpoints:path"] = "/cloudfoundryapplication", + ["management:endpoints:services:path"] = "/some" }; var configurationBuilder = new ConfigurationBuilder(); @@ -30,8 +31,9 @@ public void AddServicesActuator_AddsCorrectServices() services.AddServicesActuator(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var options = serviceProvider.GetService>(); - Assert.NotNull(options); + var options = serviceProvider.GetRequiredService>(); + Assert.Equal("/some", options.CurrentValue.Path); + var handler = serviceProvider.GetService(); Assert.NotNull(handler); } diff --git a/src/Management/test/Endpoint.Test/SpringBootAdminClient/ServiceCollectionExtensionsTest.cs b/src/Management/test/Endpoint.Test/SpringBootAdminClient/ServiceCollectionExtensionsTest.cs index 395bc91253..0539c4704c 100644 --- a/src/Management/test/Endpoint.Test/SpringBootAdminClient/ServiceCollectionExtensionsTest.cs +++ b/src/Management/test/Endpoint.Test/SpringBootAdminClient/ServiceCollectionExtensionsTest.cs @@ -25,6 +25,6 @@ public void AddSpringBootAdminClient_AddsHostedService() services.AddSpringBootAdminClient(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - Assert.NotEmpty(serviceProvider.GetServices().OfType()); + Assert.Single(serviceProvider.GetServices().OfType()); } } diff --git a/src/Management/test/Endpoint.Test/SpringBootAdminClient/SpringBootAdminClientOptionsTest.cs b/src/Management/test/Endpoint.Test/SpringBootAdminClient/SpringBootAdminClientOptionsTest.cs index b1dd70ae7e..4db3ce551d 100644 --- a/src/Management/test/Endpoint.Test/SpringBootAdminClient/SpringBootAdminClientOptionsTest.cs +++ b/src/Management/test/Endpoint.Test/SpringBootAdminClient/SpringBootAdminClientOptionsTest.cs @@ -18,20 +18,6 @@ public void ConstructorFailsWithoutBaseAppUrl() Assert.Equal("Please set spring:boot:admin:client:BasePath in order to register with Spring Boot Admin", exception.Message); } - [Fact] - public void ConstructorUsesAppInfo() - { - var appsettings = new Dictionary - { - ["application:Uris:0"] = "http://somehost" - }; - - var options = GetOptionsFromSettings(appsettings); - - Assert.NotNull(options); - Assert.Equal("http://somehost", options.BasePath); - } - [Fact] public void Constructor_BindsConfiguration() { @@ -43,8 +29,7 @@ public void Constructor_BindsConfiguration() ["spring:boot:admin:client:url"] = "http://springbootadmin:9090", ["spring:boot:admin:client:metadata:user.name"] = "userName", ["spring:boot:admin:client:metadata:user.password"] = "userPassword", - ["spring:application:name"] = "MySteeltoeApplication", - ["ApplicationName"] = "OtherApplicationName" + ["spring:application:name"] = "MySteeltoeApplication" }; var options = GetOptionsFromSettings(appsettings); diff --git a/src/Management/test/Endpoint.Test/ThreadDump/EndpointServiceCollectionTest.cs b/src/Management/test/Endpoint.Test/ThreadDump/EndpointServiceCollectionTest.cs index 726282d1a4..3fe663802c 100644 --- a/src/Management/test/Endpoint.Test/ThreadDump/EndpointServiceCollectionTest.cs +++ b/src/Management/test/Endpoint.Test/ThreadDump/EndpointServiceCollectionTest.cs @@ -32,10 +32,12 @@ public void AddThreadDumpActuator_AddsCorrectServices() services.AddSingleton(configurationRoot); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var options = serviceProvider.GetService>(); - Assert.NotNull(options); + var options = serviceProvider.GetRequiredService>(); + Assert.False(options.CurrentValue.Enabled); + var threadDumper = serviceProvider.GetService(); Assert.NotNull(threadDumper); + var handler = serviceProvider.GetService(); Assert.NotNull(handler); } diff --git a/src/Management/test/Endpoint.Test/Trace/EndpointServiceCollectionTest.cs b/src/Management/test/Endpoint.Test/Trace/EndpointServiceCollectionTest.cs index c2f65cca27..987019f550 100644 --- a/src/Management/test/Endpoint.Test/Trace/EndpointServiceCollectionTest.cs +++ b/src/Management/test/Endpoint.Test/Trace/EndpointServiceCollectionTest.cs @@ -12,19 +12,19 @@ namespace Steeltoe.Management.Endpoint.Test.Trace; public sealed class EndpointServiceCollectionTest : BaseTest { - private readonly Dictionary _appSettings = new() - { - ["management:endpoints:enabled"] = "false", - ["management:endpoints:path"] = "/cloudfoundryapplication", - ["management:endpoints:trace:enabled"] = "false" - }; - [Fact] public void AddTraceActuator_AddsCorrectServices() { + var appSettings = new Dictionary + { + ["management:endpoints:enabled"] = "false", + ["management:endpoints:path"] = "/cloudfoundryapplication", + ["management:endpoints:httpTrace:enabled"] = "false" + }; + var services = new ServiceCollection(); var configurationBuilder = new ConfigurationBuilder(); - configurationBuilder.AddInMemoryCollection(_appSettings); + configurationBuilder.AddInMemoryCollection(appSettings); IConfigurationRoot configurationRoot = configurationBuilder.Build(); services.AddLogging(); @@ -33,8 +33,9 @@ public void AddTraceActuator_AddsCorrectServices() services.AddTraceActuator(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var options = serviceProvider.GetService>(); - Assert.NotNull(options); + var options = serviceProvider.GetRequiredService>(); + Assert.False(options.CurrentValue.Enabled); + var handler = serviceProvider.GetService(); Assert.NotNull(handler); @@ -47,9 +48,16 @@ public void AddTraceActuator_AddsCorrectServices() [Fact] public void AddTraceActuatorV1_AddsCorrectServices() { + var appSettings = new Dictionary + { + ["management:endpoints:enabled"] = "false", + ["management:endpoints:path"] = "/cloudfoundryapplication", + ["management:endpoints:trace:enabled"] = "false" + }; + var services = new ServiceCollection(); var configurationBuilder = new ConfigurationBuilder(); - configurationBuilder.AddInMemoryCollection(_appSettings); + configurationBuilder.AddInMemoryCollection(appSettings); IConfigurationRoot configurationRoot = configurationBuilder.Build(); services.AddLogging(); @@ -58,8 +66,9 @@ public void AddTraceActuatorV1_AddsCorrectServices() services.AddTraceActuator(MediaTypeVersion.V1); ServiceProvider serviceProvider = services.BuildServiceProvider(true); - var options = serviceProvider.GetService>(); - Assert.NotNull(options); + var options = serviceProvider.GetRequiredService>(); + Assert.False(options.Get("V1").Enabled); + var handler = serviceProvider.GetService(); Assert.NotNull(handler); diff --git a/src/Management/test/Endpoint.Test/Trace/TraceEndpointOptionsTest.cs b/src/Management/test/Endpoint.Test/Trace/TraceEndpointOptionsTest.cs index ed62fbb89b..4533ced8c1 100644 --- a/src/Management/test/Endpoint.Test/Trace/TraceEndpointOptionsTest.cs +++ b/src/Management/test/Endpoint.Test/Trace/TraceEndpointOptionsTest.cs @@ -29,26 +29,76 @@ public void Constructor_InitializesWithDefaults() } [Fact] - public void Constructor_BindsConfigurationCorrectly() + public void Constructor_BindsConfigurationCorrectly_V1() { var appsettings = new Dictionary { ["management:endpoints:enabled"] = "false", ["management:endpoints:path"] = "/cloudfoundryapplication", ["management:endpoints:loggers:enabled"] = "false", - ["management:endpoints:httptrace:enabled"] = "true", - ["management:endpoints:httptrace:capacity"] = "1000", - ["management:endpoints:httptrace:addTimeTaken"] = "false", - ["management:endpoints:httptrace:addRequestHeaders"] = "false", - ["management:endpoints:httptrace:addResponseHeaders"] = "false", - ["management:endpoints:httptrace:addPathInfo"] = "true", - ["management:endpoints:httptrace:addUserPrincipal"] = "true", - ["management:endpoints:httptrace:addParameters"] = "true", - ["management:endpoints:httptrace:addQueryString"] = "true", - ["management:endpoints:httptrace:addAuthType"] = "true", - ["management:endpoints:httptrace:addRemoteAddress"] = "true", - ["management:endpoints:httptrace:addSessionId"] = "true", - ["management:endpoints:cloudfoundry:validatecertificates"] = "true", + ["management:endpoints:trace:enabled"] = "true", + ["management:endpoints:trace:capacity"] = "1000", + ["management:endpoints:trace:addTimeTaken"] = "false", + ["management:endpoints:trace:addRequestHeaders"] = "false", + ["management:endpoints:trace:addResponseHeaders"] = "false", + ["management:endpoints:trace:addPathInfo"] = "true", + ["management:endpoints:trace:addUserPrincipal"] = "true", + ["management:endpoints:trace:addParameters"] = "true", + ["management:endpoints:trace:addQueryString"] = "true", + ["management:endpoints:trace:addAuthType"] = "true", + ["management:endpoints:trace:addRemoteAddress"] = "true", + ["management:endpoints:trace:addSessionId"] = "true", + ["management:endpoints:cloudfoundry:validateCertificates"] = "true", + ["management:endpoints:cloudfoundry:enabled"] = "true" + }; + + TraceEndpointOptions endpointOptions = GetOptionsMonitorFromSettings(appsettings).Get("V1"); + + CloudFoundryEndpointOptions cloudFoundryEndpointOptions = + GetOptionsFromSettings(appsettings); + + Assert.True(cloudFoundryEndpointOptions.Enabled); + Assert.Equal(string.Empty, cloudFoundryEndpointOptions.Id); + Assert.Equal(string.Empty, cloudFoundryEndpointOptions.Path); + Assert.True(cloudFoundryEndpointOptions.ValidateCertificates); + + Assert.True(endpointOptions.Enabled); + Assert.Equal("trace", endpointOptions.Id); + Assert.Equal("trace", endpointOptions.Path); + Assert.Equal(1000, endpointOptions.Capacity); + Assert.False(endpointOptions.AddTimeTaken); + Assert.False(endpointOptions.AddRequestHeaders); + Assert.False(endpointOptions.AddResponseHeaders); + Assert.True(endpointOptions.AddPathInfo); + Assert.True(endpointOptions.AddUserPrincipal); + Assert.True(endpointOptions.AddParameters); + Assert.True(endpointOptions.AddQueryString); + Assert.True(endpointOptions.AddAuthType); + Assert.True(endpointOptions.AddRemoteAddress); + Assert.True(endpointOptions.AddSessionId); + } + + [Fact] + public void Constructor_BindsConfigurationCorrectly_V2() + { + var appsettings = new Dictionary + { + ["management:endpoints:enabled"] = "false", + ["management:endpoints:path"] = "/cloudfoundryapplication", + ["management:endpoints:loggers:enabled"] = "false", + ["management:endpoints:httpTrace:enabled"] = "true", + ["management:endpoints:httpTrace:capacity"] = "1000", + ["management:endpoints:httpTrace:addTimeTaken"] = "false", + ["management:endpoints:httpTrace:addRequestHeaders"] = "false", + ["management:endpoints:httpTrace:addResponseHeaders"] = "false", + ["management:endpoints:httpTrace:addPathInfo"] = "true", + ["management:endpoints:httpTrace:addUserPrincipal"] = "true", + ["management:endpoints:httpTrace:addParameters"] = "true", + ["management:endpoints:httpTrace:addQueryString"] = "true", + ["management:endpoints:httpTrace:addAuthType"] = "true", + ["management:endpoints:httpTrace:addRemoteAddress"] = "true", + ["management:endpoints:httpTrace:addSessionId"] = "true", + ["management:endpoints:cloudfoundry:validateCertificates"] = "true", ["management:endpoints:cloudfoundry:enabled"] = "true" }; diff --git a/src/Management/test/Tracing.Test/TestBase.cs b/src/Management/test/Tracing.Test/TestBase.cs index f47e8b94f0..4fb2863550 100644 --- a/src/Management/test/Tracing.Test/TestBase.cs +++ b/src/Management/test/Tracing.Test/TestBase.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; using Steeltoe.Logging; @@ -36,14 +37,16 @@ protected IConfiguration GetConfiguration(Dictionary moreSettin protected void ValidateServiceCollectionCommon(ServiceProvider serviceProvider) { // confirm Steeltoe types were registered - Assert.NotNull(serviceProvider.GetService()); + TracingOptions tracingOptions = serviceProvider.GetRequiredService>().Value; + tracingOptions.Name.Should().NotBeNull(); + Assert.IsType(serviceProvider.GetRequiredService()); // confirm OpenTelemetry types were registered var tracerProvider = serviceProvider.GetService(); Assert.NotNull(tracerProvider); - var hst = serviceProvider.GetService(); - Assert.NotNull(hst); + IHostedService[] hostedServices = serviceProvider.GetServices().ToArray(); + Assert.Single(hostedServices, hostedService => hostedService.GetType().Name == "TelemetryHostedService"); } protected void ValidateServiceCollectionBase(ServiceProvider serviceProvider) diff --git a/src/Management/test/Tracing.Test/TracingBaseServiceCollectionExtensionsTest.cs b/src/Management/test/Tracing.Test/TracingBaseServiceCollectionExtensionsTest.cs index e21eb787e5..c3698451b3 100644 --- a/src/Management/test/Tracing.Test/TracingBaseServiceCollectionExtensionsTest.cs +++ b/src/Management/test/Tracing.Test/TracingBaseServiceCollectionExtensionsTest.cs @@ -30,13 +30,18 @@ public void AddDistributedTracing_WiresIncludedExporters() IServiceCollection services = new ServiceCollection().AddSingleton(GetConfiguration()).AddLogging(); ServiceProvider serviceProvider = services.AddDistributedTracing(null).BuildServiceProvider(true); - var hst = serviceProvider.GetService(); - Assert.NotNull(hst); + + IHostedService[] hostedServices = serviceProvider.GetServices().ToArray(); + Assert.Single(hostedServices, hostedService => hostedService.GetType().Name == "TelemetryHostedService"); + var tracerProvider = serviceProvider.GetService(); Assert.NotNull(tracerProvider); - Assert.NotNull(serviceProvider.GetService>()); - Assert.NotNull(serviceProvider.GetService>()); + var zipkinOptions = serviceProvider.GetRequiredService>(); + Assert.NotNull(zipkinOptions.Value.Endpoint); + + var jaegerOptions = serviceProvider.GetRequiredService>(); + Assert.NotNull(jaegerOptions.Value.Endpoint); } [Fact] @@ -50,8 +55,10 @@ public void AddDistributedTracing_ConfiguresSamplers() services.AddLogging(); ServiceProvider serviceProvider = services.AddDistributedTracing(null).BuildServiceProvider(true); - var hst = serviceProvider.GetService(); - Assert.NotNull(hst); + + IHostedService[] hostedServices = serviceProvider.GetServices().ToArray(); + Assert.Single(hostedServices, hostedService => hostedService.GetType().Name == "TelemetryHostedService"); + var tracerProvider = serviceProvider.GetService(); Assert.NotNull(tracerProvider); @@ -62,8 +69,10 @@ public void AddDistributedTracing_ConfiguresSamplers() })); serviceProvider = services.AddLogging().AddDistributedTracing(null).BuildServiceProvider(true); - hst = serviceProvider.GetService(); - Assert.NotNull(hst); + + hostedServices = serviceProvider.GetServices().ToArray(); + Assert.Single(hostedServices, hostedService => hostedService.GetType().Name == "TelemetryHostedService"); + tracerProvider = serviceProvider.GetService(); Assert.NotNull(tracerProvider); } diff --git a/src/Management/test/Tracing.Test/TracingCoreServiceCollectionExtensionsTest.cs b/src/Management/test/Tracing.Test/TracingCoreServiceCollectionExtensionsTest.cs index 765d85466e..88b7642583 100644 --- a/src/Management/test/Tracing.Test/TracingCoreServiceCollectionExtensionsTest.cs +++ b/src/Management/test/Tracing.Test/TracingCoreServiceCollectionExtensionsTest.cs @@ -29,12 +29,15 @@ public void AddDistributedTracingAspNetCore_WiresIncludedExporters() IServiceCollection services = new ServiceCollection().AddSingleton(GetConfiguration()).AddLogging(); ServiceProvider serviceProvider = services.AddDistributedTracing(null).BuildServiceProvider(true); - var hst = serviceProvider.GetService(); - Assert.NotNull(hst); + + IHostedService[] hostedServices = serviceProvider.GetServices().ToArray(); + Assert.Single(hostedServices, hostedService => hostedService.GetType().Name == "TelemetryHostedService"); + var tracerProvider = serviceProvider.GetService(); Assert.NotNull(tracerProvider); - Assert.NotNull(serviceProvider.GetService>()); + var otlpOptions = serviceProvider.GetRequiredService>(); + Assert.NotNull(otlpOptions.Value.Endpoint); } [Fact] diff --git a/src/Management/test/Tracing.Test/TracingLogProcessorTest.cs b/src/Management/test/Tracing.Test/TracingLogProcessorTest.cs index 3d5c405edd..6f76445ef1 100644 --- a/src/Management/test/Tracing.Test/TracingLogProcessorTest.cs +++ b/src/Management/test/Tracing.Test/TracingLogProcessorTest.cs @@ -3,9 +3,12 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using OpenTelemetry; using OpenTelemetry.Trace; using Steeltoe.Common; +using Steeltoe.Common.Extensions; using Steeltoe.Common.TestResources; namespace Steeltoe.Management.Tracing.Test; @@ -15,9 +18,9 @@ public sealed class TracingLogProcessorTest [Fact] public void Process_NoCurrentSpan_DoesNothing() { - using TracerProvider? openTelemetry = Sdk.CreateTracerProviderBuilder().AddSource("tracername").Build(); - var options = new TracingOptions(null, new ConfigurationBuilder().Build()); - var processor = new TracingLogProcessor(options); + using TracerProvider openTelemetry = Sdk.CreateTracerProviderBuilder().AddSource("tracername").Build(); + var optionsMonitor = new TestOptionsMonitor(); + var processor = new TracingLogProcessor(optionsMonitor); string result = processor.Process("InputLogMessage"); @@ -27,14 +30,15 @@ public void Process_NoCurrentSpan_DoesNothing() [Fact] public void Process_CurrentSpan_ReturnsExpected() { - using TracerProvider? openTelemetry = Sdk.CreateTracerProviderBuilder().AddSource("tracername").Build(); + using TracerProvider openTelemetry = Sdk.CreateTracerProviderBuilder().AddSource("tracername").Build(); - IConfiguration configuration = TestHelpers.GetConfigurationFromDictionary(new Dictionary + var appSettings = new Dictionary { ["management:tracing:name"] = "foobar" - }); + }; - var processor = new TracingLogProcessor(new TracingOptions(new ApplicationInstanceInfo(configuration), configuration)); + IOptionsMonitor optionsMonitor = GetTracingOptionsMonitor(appSettings); + var processor = new TracingLogProcessor(optionsMonitor); Tracer tracer = TracerProvider.Default.GetTracer("tracername"); TelemetrySpan span = tracer.StartActiveSpan("spanName"); @@ -63,19 +67,17 @@ public void Process_CurrentSpan_ReturnsExpected() [Fact] public void Process_UseShortTraceIds() { - var appsettings = new Dictionary + var appSettings = new Dictionary { ["management:tracing:name"] = "foobar", ["management:tracing:useShortTraceIds"] = "true" }; - IConfiguration configuration = TestHelpers.GetConfigurationFromDictionary(appsettings); - var options = new TracingOptions(new ApplicationInstanceInfo(configuration), configuration); - - using TracerProvider? openTelemetry = Sdk.CreateTracerProviderBuilder().AddSource("tracername").Build(); + IOptionsMonitor optionsMonitor = GetTracingOptionsMonitor(appSettings); + using TracerProvider openTelemetry = Sdk.CreateTracerProviderBuilder().AddSource("tracername").Build(); Tracer tracer = TracerProvider.Default.GetTracer("tracername"); TelemetrySpan span = tracer.StartActiveSpan("spanName"); - var processor = new TracingLogProcessor(options); + var processor = new TracingLogProcessor(optionsMonitor); string result = processor.Process("InputLogMessage"); @@ -92,4 +94,24 @@ public void Process_UseShortTraceIds() Assert.Contains(span.Context.SpanId.ToHexString(), result, StringComparison.Ordinal); Assert.Contains("foobar", result, StringComparison.Ordinal); } + + private IOptionsMonitor GetTracingOptionsMonitor(IDictionary appSettings) + { + var options = new TracingOptions(); + + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddApplicationInstanceInfo(); + ServiceProvider serviceProvider = services.BuildServiceProvider(true); + + var appInfo = serviceProvider.GetRequiredService(); + var configurer = new ConfigureTracingOptions(configuration, appInfo); + configurer.Configure(options); + + return TestOptionsMonitor.Create(options); + } } diff --git a/src/Management/test/Tracing.Test/TracingOptionsTest.cs b/src/Management/test/Tracing.Test/TracingOptionsTest.cs index e549581b62..fb07cb146d 100644 --- a/src/Management/test/Tracing.Test/TracingOptionsTest.cs +++ b/src/Management/test/Tracing.Test/TracingOptionsTest.cs @@ -4,8 +4,9 @@ using System.Reflection; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Steeltoe.Common; -using Steeltoe.Common.TestResources; +using Steeltoe.Common.Extensions; namespace Steeltoe.Management.Tracing.Test; @@ -14,80 +15,84 @@ public sealed class TracingOptionsTest [Fact] public void InitializedWithDefaults() { - IConfiguration configuration = TestHelpers.GetConfigurationFromDictionary(new Dictionary()); - var options = new TracingOptions(new ApplicationInstanceInfo(configuration), configuration); - - Assert.Equal(Assembly.GetEntryAssembly()!.GetName().Name, options.Name); - Assert.Equal(TracingOptions.DefaultIngressIgnorePattern, options.IngressIgnorePattern); - Assert.False(options.AlwaysSample); - Assert.False(options.NeverSample); - Assert.False(options.UseShortTraceIds); - Assert.Equal(TracingOptions.DefaultEgressIgnorePattern, options.EgressIgnorePattern); + var options = new TracingOptions(); + + options.Name.Should().BeNull(); + options.IngressIgnorePattern.Should().BeNull(); + options.EgressIgnorePattern.Should().BeNull(); + options.MaxPayloadSizeInBytes.Should().Be(4096); + options.AlwaysSample.Should().BeFalse(); + options.NeverSample.Should().BeFalse(); + options.UseShortTraceIds.Should().BeFalse(); + options.PropagationType.Should().Be("B3"); + options.SingleB3Header.Should().BeTrue(); + options.ExporterEndpoint.Should().BeNull(); } [Fact] public void BindsConfigurationCorrectly() { - var appsettings = new Dictionary + var appSettings = new Dictionary { ["management:tracing:name"] = "foobar", - ["management:tracing:ingressIgnorePattern"] = "pattern", - ["management:tracing:egressIgnorePattern"] = "pattern", + ["management:tracing:ingressIgnorePattern"] = "pattern-in", + ["management:tracing:egressIgnorePattern"] = "pattern-out", ["management:tracing:alwaysSample"] = "true", ["management:tracing:neverSample"] = "true", ["management:tracing:useShortTraceIds"] = "true" }; - IConfiguration configuration = TestHelpers.GetConfigurationFromDictionary(appsettings); - var options = new TracingOptions(new ApplicationInstanceInfo(configuration), configuration); + TracingOptions options = ConfigureTracingOptions(appSettings); - Assert.Equal("foobar", options.Name); - Assert.Equal("pattern", options.IngressIgnorePattern); - Assert.True(options.AlwaysSample); - Assert.True(options.NeverSample); - Assert.True(options.UseShortTraceIds); - Assert.Equal("pattern", options.EgressIgnorePattern); + options.Name.Should().Be("foobar"); + options.IngressIgnorePattern.Should().Be("pattern-in"); + options.EgressIgnorePattern.Should().Be("pattern-out"); + options.MaxPayloadSizeInBytes.Should().Be(4096); + options.AlwaysSample.Should().BeTrue(); + options.NeverSample.Should().BeTrue(); + options.UseShortTraceIds.Should().BeTrue(); + options.PropagationType.Should().Be("B3"); + options.SingleB3Header.Should().BeTrue(); + options.ExporterEndpoint.Should().BeNull(); } [Fact] public void ApplicationName_ReturnsExpected() { - var appsettings = new Dictionary(); - var builder = new ConfigurationBuilder(); - builder.AddInMemoryCollection(appsettings); - IConfigurationRoot configurationRoot = builder.Build(); - var appInstanceInfo = new ApplicationInstanceInfo(configurationRoot); + var appSettings = new Dictionary(); // Uses Assembly name as default - var options = new TracingOptions(appInstanceInfo, configurationRoot); - Assert.Equal(Assembly.GetEntryAssembly()!.GetName().Name, options.Name); + TracingOptions options = ConfigureTracingOptions(appSettings); + options.Name.Should().Be(Assembly.GetEntryAssembly()!.GetName().Name); // Finds Spring app name - appsettings.Add("spring:application:name", "SpringApplicationName"); - configurationRoot = builder.Build(); - appInstanceInfo = new ApplicationInstanceInfo(configurationRoot); - options = new TracingOptions(appInstanceInfo, configurationRoot); - Assert.Equal("SpringApplicationName", options.Name); - - // Platform app name overrides spring name - appsettings.Add("application:name", "PlatformName"); - configurationRoot = builder.Build(); - appInstanceInfo = new ApplicationInstanceInfo(configurationRoot); - options = new TracingOptions(appInstanceInfo, configurationRoot); - Assert.Equal("PlatformName", options.Name); - - // Finds and uses management name - appsettings.Add("management:name", "ManagementName"); - configurationRoot = builder.Build(); - appInstanceInfo = new ApplicationInstanceInfo(configurationRoot); - options = new TracingOptions(appInstanceInfo, configurationRoot); - Assert.Equal("ManagementName", options.Name); - - // management:tracing name beats all else - appsettings.Add("management:tracing:name", "ManagementTracingName"); - configurationRoot = builder.Build(); - appInstanceInfo = new ApplicationInstanceInfo(configurationRoot); - options = new TracingOptions(appInstanceInfo, configurationRoot); - Assert.Equal("ManagementTracingName", options.Name); + appSettings.Add("spring:application:name", "SpringApplicationName"); + options = ConfigureTracingOptions(appSettings); + options.Name.Should().Be("SpringApplicationName"); + + // management:tracing:name beats all else + appSettings.Add("management:tracing:name", "ManagementTracingName"); + options = ConfigureTracingOptions(appSettings); + options.Name.Should().Be("ManagementTracingName"); + } + + private TracingOptions ConfigureTracingOptions(IDictionary appSettings) + { + var options = new TracingOptions(); + + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddApplicationInstanceInfo(); + ServiceProvider serviceProvider = services.BuildServiceProvider(true); + + var appInfo = serviceProvider.GetRequiredService(); + var configurer = new ConfigureTracingOptions(configuration, appInfo); + configurer.Configure(options); + + return options; } } diff --git a/src/Security/src/Authorization.Certificate/ConfigurationSchema.json b/src/Security/src/Authorization.Certificate/ConfigurationSchema.json index 0b6f8d7359..ab3a6c4181 100644 --- a/src/Security/src/Authorization.Certificate/ConfigurationSchema.json +++ b/src/Security/src/Authorization.Certificate/ConfigurationSchema.json @@ -34,7 +34,7 @@ "description": "Gets or sets the local path to a private key file on disk (optional)." } }, - "description": "Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." + "description": "Configuration settings for certificate access. Indicates where to load a 'System.Security.Cryptography.X509Certificates.X509Certificate2' from." } } } From 9353c8d72ab3a04434be72d2d78e6e50dcf8034a Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Fri, 9 Aug 2024 13:40:36 +0200 Subject: [PATCH 10/30] Enable NRT project-wide in Common --- src/Common/src/Common/ApplicationInstanceInfo.cs | 2 -- src/Common/src/Common/ArgumentGuard.cs | 2 -- src/Common/src/Common/AssemblyLoader.cs | 2 -- .../src/Common/CasingConventions/EnumExtensions.cs | 2 -- .../SnakeCaseAllCapsEnumMemberJsonConverter.cs | 2 -- .../CasingConventions/SnakeCaseEnumConverter.cs | 2 -- .../src/Common/Configuration/CertificateOptions.cs | 2 -- .../Configuration/ConfigurationKeyConverter.cs | 2 -- .../Configuration/ConfigurationValuesHelper.cs | 2 -- .../Configuration/PropertyPlaceHolderHelper.cs | 2 -- .../Configuration/SpringApplicationSettings.cs | 2 -- .../src/Common/ConfigureApplicationInstanceInfo.cs | 2 -- src/Common/src/Common/Discovery/IDiscoveryClient.cs | 2 -- src/Common/src/Common/Discovery/IServiceInstance.cs | 2 -- .../src/Common/DynamicTypeAccess/InstanceAccessor.cs | 2 -- .../src/Common/DynamicTypeAccess/PackageResolver.cs | 2 -- .../Common/DynamicTypeAccess/ReflectionAccessor.cs | 2 -- src/Common/src/Common/DynamicTypeAccess/Shim.cs | 2 -- src/Common/src/Common/DynamicTypeAccess/TaskShim.cs | 2 -- .../src/Common/DynamicTypeAccess/TypeAccessor.cs | 2 -- .../src/Common/Extensions/ExceptionExtensions.cs | 2 -- .../Common/Extensions/ServiceCollectionExtensions.cs | 2 -- src/Common/src/Common/Extensions/UriExtensions.cs | 2 -- .../src/Common/HealthChecks/HealthAggregator.cs | 2 -- .../src/Common/HealthChecks/HealthCheckResult.cs | 2 -- .../src/Common/HealthChecks/IHealthAggregator.cs | 2 -- .../src/Common/HealthChecks/IHealthContributor.cs | 2 -- src/Common/src/Common/IApplicationInstanceInfo.cs | 12 +++++------- src/Common/src/Common/IApplicationTask.cs | 2 -- src/Common/src/Common/Net/DnsTools.cs | 2 -- src/Common/src/Common/Net/HostInfo.cs | 2 -- src/Common/src/Common/Net/InetOptions.cs | 2 -- src/Common/src/Common/Net/InetUtils.cs | 2 -- src/Common/src/Common/Platform.cs | 2 -- src/Common/src/Common/SecurityUtilities.cs | 2 -- src/Common/src/Common/Steeltoe.Common.csproj | 1 + 36 files changed, 6 insertions(+), 75 deletions(-) diff --git a/src/Common/src/Common/ApplicationInstanceInfo.cs b/src/Common/src/Common/ApplicationInstanceInfo.cs index 94bbec85d2..da75ec6f55 100644 --- a/src/Common/src/Common/ApplicationInstanceInfo.cs +++ b/src/Common/src/Common/ApplicationInstanceInfo.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common; /// diff --git a/src/Common/src/Common/ArgumentGuard.cs b/src/Common/src/Common/ArgumentGuard.cs index 09b489adfa..5ee13a1f3a 100644 --- a/src/Common/src/Common/ArgumentGuard.cs +++ b/src/Common/src/Common/ArgumentGuard.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Common/src/Common/AssemblyLoader.cs b/src/Common/src/Common/AssemblyLoader.cs index 53eabb60ad..d602ea6475 100644 --- a/src/Common/src/Common/AssemblyLoader.cs +++ b/src/Common/src/Common/AssemblyLoader.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Reflection; namespace Steeltoe.Common; diff --git a/src/Common/src/Common/CasingConventions/EnumExtensions.cs b/src/Common/src/Common/CasingConventions/EnumExtensions.cs index 69ef0f9207..a1323d3ac8 100644 --- a/src/Common/src/Common/CasingConventions/EnumExtensions.cs +++ b/src/Common/src/Common/CasingConventions/EnumExtensions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.CasingConventions; public static class EnumExtensions diff --git a/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs b/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs index c3a96ba682..582ce49144 100644 --- a/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs +++ b/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Text.Json; using System.Text.Json.Serialization; diff --git a/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs b/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs index 29fd360a9b..d57ccbc69c 100644 --- a/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs +++ b/src/Common/src/Common/CasingConventions/SnakeCaseEnumConverter.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Text; using System.Text.Json; using System.Text.Json.Serialization; diff --git a/src/Common/src/Common/Configuration/CertificateOptions.cs b/src/Common/src/Common/Configuration/CertificateOptions.cs index ebad1dc8ce..15863ed42f 100644 --- a/src/Common/src/Common/Configuration/CertificateOptions.cs +++ b/src/Common/src/Common/Configuration/CertificateOptions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Security.Cryptography.X509Certificates; namespace Steeltoe.Common.Configuration; diff --git a/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs b/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs index eec5dcbc2f..754145e8fa 100644 --- a/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs +++ b/src/Common/src/Common/Configuration/ConfigurationKeyConverter.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Text; using System.Text.RegularExpressions; using Microsoft.Extensions.Configuration; diff --git a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs index 7f2f75bdb4..2daaf2f0ad 100644 --- a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs +++ b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Globalization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Abstractions; diff --git a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs index 9880e791ad..99e5060dae 100644 --- a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs +++ b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Diagnostics.CodeAnalysis; using System.Text; using Microsoft.Extensions.Configuration; diff --git a/src/Common/src/Common/Configuration/SpringApplicationSettings.cs b/src/Common/src/Common/Configuration/SpringApplicationSettings.cs index f9b0d85321..3f25cb7115 100644 --- a/src/Common/src/Common/Configuration/SpringApplicationSettings.cs +++ b/src/Common/src/Common/Configuration/SpringApplicationSettings.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.Configuration; /// diff --git a/src/Common/src/Common/ConfigureApplicationInstanceInfo.cs b/src/Common/src/Common/ConfigureApplicationInstanceInfo.cs index e3c8ac6912..ffde36b0dc 100644 --- a/src/Common/src/Common/ConfigureApplicationInstanceInfo.cs +++ b/src/Common/src/Common/ConfigureApplicationInstanceInfo.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; diff --git a/src/Common/src/Common/Discovery/IDiscoveryClient.cs b/src/Common/src/Common/Discovery/IDiscoveryClient.cs index 671ec8ffc1..598095b2a9 100644 --- a/src/Common/src/Common/Discovery/IDiscoveryClient.cs +++ b/src/Common/src/Common/Discovery/IDiscoveryClient.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.Discovery; /// diff --git a/src/Common/src/Common/Discovery/IServiceInstance.cs b/src/Common/src/Common/Discovery/IServiceInstance.cs index 53b3af71ef..8f23b8ef3d 100644 --- a/src/Common/src/Common/Discovery/IServiceInstance.cs +++ b/src/Common/src/Common/Discovery/IServiceInstance.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.Discovery; public interface IServiceInstance diff --git a/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs b/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs index 3f992f1ad4..cb46cb4ed4 100644 --- a/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs +++ b/src/Common/src/Common/DynamicTypeAccess/InstanceAccessor.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.DynamicTypeAccess; /// diff --git a/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs b/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs index 7b2f67c7f0..f05bf9751b 100644 --- a/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs +++ b/src/Common/src/Common/DynamicTypeAccess/PackageResolver.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Collections.Immutable; using System.Reflection; diff --git a/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs b/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs index 322e933855..33f4b3ee46 100644 --- a/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs +++ b/src/Common/src/Common/DynamicTypeAccess/ReflectionAccessor.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Reflection; namespace Steeltoe.Common.DynamicTypeAccess; diff --git a/src/Common/src/Common/DynamicTypeAccess/Shim.cs b/src/Common/src/Common/DynamicTypeAccess/Shim.cs index e91d55c941..e1bcac4704 100644 --- a/src/Common/src/Common/DynamicTypeAccess/Shim.cs +++ b/src/Common/src/Common/DynamicTypeAccess/Shim.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.DynamicTypeAccess; /// diff --git a/src/Common/src/Common/DynamicTypeAccess/TaskShim.cs b/src/Common/src/Common/DynamicTypeAccess/TaskShim.cs index 746ed6fe37..da7443ded0 100644 --- a/src/Common/src/Common/DynamicTypeAccess/TaskShim.cs +++ b/src/Common/src/Common/DynamicTypeAccess/TaskShim.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.DynamicTypeAccess; /// diff --git a/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs b/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs index 37792fb428..1ce57f05ec 100644 --- a/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs +++ b/src/Common/src/Common/DynamicTypeAccess/TypeAccessor.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.DynamicTypeAccess; /// diff --git a/src/Common/src/Common/Extensions/ExceptionExtensions.cs b/src/Common/src/Common/Extensions/ExceptionExtensions.cs index f4318f5e01..afb89a8f02 100644 --- a/src/Common/src/Common/Extensions/ExceptionExtensions.cs +++ b/src/Common/src/Common/Extensions/ExceptionExtensions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Reflection; namespace Steeltoe.Common.Extensions; diff --git a/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs index 3a47eb0d53..2c5aa7f7eb 100644 --- a/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs +++ b/src/Common/src/Common/Extensions/ServiceCollectionExtensions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; diff --git a/src/Common/src/Common/Extensions/UriExtensions.cs b/src/Common/src/Common/Extensions/UriExtensions.cs index c36a405ddb..5a9be4dbdb 100644 --- a/src/Common/src/Common/Extensions/UriExtensions.cs +++ b/src/Common/src/Common/Extensions/UriExtensions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Diagnostics.CodeAnalysis; using System.Net; diff --git a/src/Common/src/Common/HealthChecks/HealthAggregator.cs b/src/Common/src/Common/HealthChecks/HealthAggregator.cs index c96d631b2c..b5125da011 100644 --- a/src/Common/src/Common/HealthChecks/HealthAggregator.cs +++ b/src/Common/src/Common/HealthChecks/HealthAggregator.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Collections.Concurrent; using Microsoft.Extensions.Diagnostics.HealthChecks; using Steeltoe.Common.CasingConventions; diff --git a/src/Common/src/Common/HealthChecks/HealthCheckResult.cs b/src/Common/src/Common/HealthChecks/HealthCheckResult.cs index 0083acdc89..790650b725 100644 --- a/src/Common/src/Common/HealthChecks/HealthCheckResult.cs +++ b/src/Common/src/Common/HealthChecks/HealthCheckResult.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.HealthChecks; /// diff --git a/src/Common/src/Common/HealthChecks/IHealthAggregator.cs b/src/Common/src/Common/HealthChecks/IHealthAggregator.cs index 955de4e496..a9259ba474 100644 --- a/src/Common/src/Common/HealthChecks/IHealthAggregator.cs +++ b/src/Common/src/Common/HealthChecks/IHealthAggregator.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Steeltoe.Common.HealthChecks; diff --git a/src/Common/src/Common/HealthChecks/IHealthContributor.cs b/src/Common/src/Common/HealthChecks/IHealthContributor.cs index 9671bf415b..42766d6956 100644 --- a/src/Common/src/Common/HealthChecks/IHealthContributor.cs +++ b/src/Common/src/Common/HealthChecks/IHealthContributor.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.HealthChecks; /// diff --git a/src/Common/src/Common/IApplicationInstanceInfo.cs b/src/Common/src/Common/IApplicationInstanceInfo.cs index 7e1862db22..50434a4615 100644 --- a/src/Common/src/Common/IApplicationInstanceInfo.cs +++ b/src/Common/src/Common/IApplicationInstanceInfo.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common; /// @@ -11,15 +9,15 @@ namespace Steeltoe.Common; /// public interface IApplicationInstanceInfo { - /// - /// Gets the name of this application. - /// - string? ApplicationName { get; } - // These properties exist to avoid taking a dependency on Configuration.CloudFoundry in other Steeltoe projects. internal string? ApplicationId { get; } internal string? InstanceId { get; } internal int InstanceIndex { get; } internal IList Uris { get; } internal string? InternalIP { get; } + + /// + /// Gets the name of this application. + /// + string? ApplicationName { get; } } diff --git a/src/Common/src/Common/IApplicationTask.cs b/src/Common/src/Common/IApplicationTask.cs index c2b922bd42..61766c8a0f 100644 --- a/src/Common/src/Common/IApplicationTask.cs +++ b/src/Common/src/Common/IApplicationTask.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common; /// diff --git a/src/Common/src/Common/Net/DnsTools.cs b/src/Common/src/Common/Net/DnsTools.cs index 565b9d1df9..ed97cfb290 100644 --- a/src/Common/src/Common/Net/DnsTools.cs +++ b/src/Common/src/Common/Net/DnsTools.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Net; using System.Net.Sockets; diff --git a/src/Common/src/Common/Net/HostInfo.cs b/src/Common/src/Common/Net/HostInfo.cs index 40867f50c9..c95080af4c 100644 --- a/src/Common/src/Common/Net/HostInfo.cs +++ b/src/Common/src/Common/Net/HostInfo.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.Net; internal sealed class HostInfo diff --git a/src/Common/src/Common/Net/InetOptions.cs b/src/Common/src/Common/Net/InetOptions.cs index 32356cf278..e8935447a9 100644 --- a/src/Common/src/Common/Net/InetOptions.cs +++ b/src/Common/src/Common/Net/InetOptions.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - namespace Steeltoe.Common.Net; /// diff --git a/src/Common/src/Common/Net/InetUtils.cs b/src/Common/src/Common/Net/InetUtils.cs index f3f258fcb9..7819684ad0 100644 --- a/src/Common/src/Common/Net/InetUtils.cs +++ b/src/Common/src/Common/Net/InetUtils.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; diff --git a/src/Common/src/Common/Platform.cs b/src/Common/src/Common/Platform.cs index ec436a0a4a..4180ebad0a 100644 --- a/src/Common/src/Common/Platform.cs +++ b/src/Common/src/Common/Platform.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Runtime.InteropServices; namespace Steeltoe.Common; diff --git a/src/Common/src/Common/SecurityUtilities.cs b/src/Common/src/Common/SecurityUtilities.cs index bebfbd78bb..306631e17f 100644 --- a/src/Common/src/Common/SecurityUtilities.cs +++ b/src/Common/src/Common/SecurityUtilities.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#nullable enable - using System.Diagnostics.CodeAnalysis; using System.Net; diff --git a/src/Common/src/Common/Steeltoe.Common.csproj b/src/Common/src/Common/Steeltoe.Common.csproj index e0f928d693..8ef7984093 100644 --- a/src/Common/src/Common/Steeltoe.Common.csproj +++ b/src/Common/src/Common/Steeltoe.Common.csproj @@ -4,6 +4,7 @@ Steeltoe common library health;health-checks;service-discovery;network true + enable From 1e5f72873f2784003ea5ae613c5ad42c9aa3eb49 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Fri, 9 Aug 2024 13:57:33 +0200 Subject: [PATCH 11/30] Enable NRT solution-wide --- shared.props | 1 + .../Steeltoe.Bootstrap.AutoConfiguration.csproj | 1 - .../Steeltoe.Bootstrap.AutoConfiguration.Test.csproj | 1 - .../Steeltoe.Bootstrap.EmptyAutoConfiguration.Test.csproj | 1 - src/Common/src/Certificates/Steeltoe.Common.Certificates.csproj | 1 - src/Common/src/Common/ConfigurationSchemaAttributes.cs | 2 -- src/Common/src/Common/Steeltoe.Common.csproj | 1 - src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj | 1 - src/Common/src/Http/Steeltoe.Common.Http.csproj | 1 - src/Common/src/Logging/Steeltoe.Common.Logging.csproj | 1 - src/Common/src/Net/Steeltoe.Common.Net.csproj | 1 - .../Certificates.Test/Steeltoe.Common.Certificates.Test.csproj | 1 - src/Common/test/Common.Test/Steeltoe.Common.Test.csproj | 1 - .../test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj | 1 - src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj | 1 - .../test/Logging.Test/Steeltoe.Common.Logging.Test.csproj | 1 - src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj | 1 - .../test/TestResources/Steeltoe.Common.TestResources.csproj | 1 - .../src/Abstractions/Steeltoe.Configuration.Abstractions.csproj | 1 - .../Steeltoe.Configuration.CloudFoundry.ServiceBinding.csproj | 1 - .../src/CloudFoundry/Steeltoe.Configuration.CloudFoundry.csproj | 1 - .../src/ConfigServer/Steeltoe.Configuration.ConfigServer.csproj | 1 - .../src/Encryption/Steeltoe.Configuration.Encryption.csproj | 1 - .../Steeltoe.Configuration.Kubernetes.ServiceBinding.csproj | 1 - .../src/Placeholder/Steeltoe.Configuration.Placeholder.csproj | 1 - .../src/RandomValue/Steeltoe.Configuration.RandomValue.csproj | 1 - .../src/SpringBoot/Steeltoe.Configuration.SpringBoot.csproj | 1 - ...eeltoe.Configuration.CloudFoundry.ServiceBinding.Test.csproj | 1 - .../Steeltoe.Configuration.CloudFoundry.Test.csproj | 1 - .../Steeltoe.Configuration.ConfigServer.Discovery.Test.csproj | 1 - .../Steeltoe.Configuration.ConfigServer.Integration.Test.csproj | 1 - .../Steeltoe.Configuration.ConfigServer.Test.csproj | 1 - .../Steeltoe.Configuration.Encryption.Test.csproj | 1 - ...Steeltoe.Configuration.Kubernetes.ServiceBinding.Test.csproj | 1 - .../Steeltoe.Configuration.Placeholder.Test.csproj | 1 - .../Steeltoe.Configuration.RandomValue.Test.csproj | 1 - .../Steeltoe.Configuration.SpringBoot.Test.csproj | 1 - src/Connectors/src/Connectors/Steeltoe.Connectors.csproj | 1 - .../Steeltoe.Connectors.EntityFrameworkCore.csproj | 1 - .../test/Connectors.Test/Steeltoe.Connectors.Test.csproj | 1 - .../Steeltoe.Connectors.EntityFrameworkCore.Test.csproj | 1 - .../src/Configuration/Steeltoe.Discovery.Configuration.csproj | 1 - src/Discovery/src/Consul/Steeltoe.Discovery.Consul.csproj | 1 - src/Discovery/src/Eureka/Steeltoe.Discovery.Eureka.csproj | 1 - .../src/HttpClients/Steeltoe.Discovery.HttpClients.csproj | 1 - .../Steeltoe.Discovery.Configuration.Test.csproj | 1 - .../test/Consul.Test/Steeltoe.Discovery.Consul.Test.csproj | 1 - .../test/Eureka.Test/Steeltoe.Discovery.Eureka.Test.csproj | 1 - .../HttpClients.Test/Steeltoe.Discovery.HttpClients.Test.csproj | 1 - .../src/Abstractions/Steeltoe.Logging.Abstractions.csproj | 1 - .../src/DynamicLogger/Steeltoe.Logging.DynamicLogger.csproj | 1 - .../src/DynamicSerilog/Steeltoe.Logging.DynamicSerilog.csproj | 1 - .../Steeltoe.Logging.DynamicLogger.Test.csproj | 1 - .../Steeltoe.Logging.DynamicSerilog.Test.csproj | 1 - .../src/Abstractions/Steeltoe.Management.Abstractions.csproj | 1 - src/Management/src/Endpoint/Steeltoe.Management.Endpoint.csproj | 1 - .../src/Prometheus/Steeltoe.Management.Prometheus.csproj | 1 - src/Management/src/Tasks/Steeltoe.Management.Tasks.csproj | 1 - src/Management/src/Tracing/Steeltoe.Management.Tracing.csproj | 1 - .../src/Wavefront/Steeltoe.Management.Wavefront.csproj | 1 - .../test/Endpoint.Test/Steeltoe.Management.Endpoint.Test.csproj | 1 - .../Prometheus.Test/Steeltoe.Management.Prometheus.Test.csproj | 1 - .../test/Tasks.Test/Steeltoe.Management.Tasks.Test.csproj | 1 - .../test/Tracing.Test/Steeltoe.Management.Tracing.Test.csproj | 1 - .../Wavefront.Test/Steeltoe.Management.Wavefront.Test.csproj | 1 - .../Steeltoe.Security.Authentication.JwtBearer.csproj | 1 - .../Steeltoe.Security.Authentication.OpenIdConnect.csproj | 1 - .../Steeltoe.Security.Authorization.Certificate.csproj | 1 - .../Steeltoe.Security.DataProtection.Redis.csproj | 1 - .../Steeltoe.Security.Authentication.JwtBearer.Test.csproj | 1 - .../Steeltoe.Security.Authentication.OpenIdConnect.Test.csproj | 1 - .../Steeltoe.Security.Authorization.Certificate.Test.csproj | 1 - .../Steeltoe.Security.DataProtection.Redis.Test.csproj | 1 - .../ConfigurationSchemaGenerator.csproj | 1 - .../ConfigurationSchemaGenerator.Tests.csproj | 1 - 75 files changed, 1 insertion(+), 75 deletions(-) diff --git a/shared.props b/shared.props index bd976f21ec..017962a958 100644 --- a/shared.props +++ b/shared.props @@ -1,6 +1,7 @@ latest + enable enable true false diff --git a/src/Bootstrap/src/AutoConfiguration/Steeltoe.Bootstrap.AutoConfiguration.csproj b/src/Bootstrap/src/AutoConfiguration/Steeltoe.Bootstrap.AutoConfiguration.csproj index fedde363a9..79a4123e03 100644 --- a/src/Bootstrap/src/AutoConfiguration/Steeltoe.Bootstrap.AutoConfiguration.csproj +++ b/src/Bootstrap/src/AutoConfiguration/Steeltoe.Bootstrap.AutoConfiguration.csproj @@ -4,7 +4,6 @@ Package for automatically configuring Steeltoe packages that have separately been added to a project. Autoconfiguration;automatic configuration;application bootstrapping true - enable diff --git a/src/Bootstrap/test/AutoConfiguration.Test/Steeltoe.Bootstrap.AutoConfiguration.Test.csproj b/src/Bootstrap/test/AutoConfiguration.Test/Steeltoe.Bootstrap.AutoConfiguration.Test.csproj index eacad97fcf..5e7dea4d6e 100644 --- a/src/Bootstrap/test/AutoConfiguration.Test/Steeltoe.Bootstrap.AutoConfiguration.Test.csproj +++ b/src/Bootstrap/test/AutoConfiguration.Test/Steeltoe.Bootstrap.AutoConfiguration.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Bootstrap/test/EmptyAutoConfiguration.Test/Steeltoe.Bootstrap.EmptyAutoConfiguration.Test.csproj b/src/Bootstrap/test/EmptyAutoConfiguration.Test/Steeltoe.Bootstrap.EmptyAutoConfiguration.Test.csproj index 65c3544cf5..c0b8325a63 100644 --- a/src/Bootstrap/test/EmptyAutoConfiguration.Test/Steeltoe.Bootstrap.EmptyAutoConfiguration.Test.csproj +++ b/src/Bootstrap/test/EmptyAutoConfiguration.Test/Steeltoe.Bootstrap.EmptyAutoConfiguration.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Common/src/Certificates/Steeltoe.Common.Certificates.csproj b/src/Common/src/Certificates/Steeltoe.Common.Certificates.csproj index 6c7e2a46b9..b110926728 100644 --- a/src/Common/src/Certificates/Steeltoe.Common.Certificates.csproj +++ b/src/Common/src/Certificates/Steeltoe.Common.Certificates.csproj @@ -4,7 +4,6 @@ Steeltoe common library for using certificates security;pem;certificate true - enable diff --git a/src/Common/src/Common/ConfigurationSchemaAttributes.cs b/src/Common/src/Common/ConfigurationSchemaAttributes.cs index e64d6f9d6e..7ad0228c6e 100644 --- a/src/Common/src/Common/ConfigurationSchemaAttributes.cs +++ b/src/Common/src/Common/ConfigurationSchemaAttributes.cs @@ -1,5 +1,3 @@ -#nullable enable - #pragma warning disable SA1636 // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. diff --git a/src/Common/src/Common/Steeltoe.Common.csproj b/src/Common/src/Common/Steeltoe.Common.csproj index 8ef7984093..e0f928d693 100644 --- a/src/Common/src/Common/Steeltoe.Common.csproj +++ b/src/Common/src/Common/Steeltoe.Common.csproj @@ -4,7 +4,6 @@ Steeltoe common library health;health-checks;service-discovery;network true - enable diff --git a/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj b/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj index d2ff0d2f40..b8a439c232 100644 --- a/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj +++ b/src/Common/src/Hosting/Steeltoe.Common.Hosting.csproj @@ -4,7 +4,6 @@ Steeltoe library for common hosting-related utilities NET Core;Cloud Hosting; true - enable diff --git a/src/Common/src/Http/Steeltoe.Common.Http.csproj b/src/Common/src/Http/Steeltoe.Common.Http.csproj index c658be020e..bc238e8810 100644 --- a/src/Common/src/Http/Steeltoe.Common.Http.csproj +++ b/src/Common/src/Http/Steeltoe.Common.Http.csproj @@ -4,7 +4,6 @@ Steeltoe common library for HTTP http; discovery; loadbalancing true - enable diff --git a/src/Common/src/Logging/Steeltoe.Common.Logging.csproj b/src/Common/src/Logging/Steeltoe.Common.Logging.csproj index 51950c3d72..27472071a5 100644 --- a/src/Common/src/Logging/Steeltoe.Common.Logging.csproj +++ b/src/Common/src/Logging/Steeltoe.Common.Logging.csproj @@ -4,7 +4,6 @@ Steeltoe library for common logging-related utilities logging true - enable diff --git a/src/Common/src/Net/Steeltoe.Common.Net.csproj b/src/Common/src/Net/Steeltoe.Common.Net.csproj index de82f6394d..d0b2ca36d4 100644 --- a/src/Common/src/Net/Steeltoe.Common.Net.csproj +++ b/src/Common/src/Net/Steeltoe.Common.Net.csproj @@ -4,7 +4,6 @@ Steeltoe common library for network interaction Windows-file-sharing; network-file-system true - enable diff --git a/src/Common/test/Certificates.Test/Steeltoe.Common.Certificates.Test.csproj b/src/Common/test/Certificates.Test/Steeltoe.Common.Certificates.Test.csproj index c80746d28d..d8f8a79c90 100644 --- a/src/Common/test/Certificates.Test/Steeltoe.Common.Certificates.Test.csproj +++ b/src/Common/test/Certificates.Test/Steeltoe.Common.Certificates.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj b/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj index 774ca0666a..a466bce300 100644 --- a/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj +++ b/src/Common/test/Common.Test/Steeltoe.Common.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj b/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj index f8a54d2c77..fa458da51f 100644 --- a/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj +++ b/src/Common/test/Hosting.Test/Steeltoe.Common.Hosting.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj b/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj index 79194e8ab9..725845961e 100644 --- a/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj +++ b/src/Common/test/Http.Test/Steeltoe.Common.Http.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj b/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj index 900c80c1fb..fbfe9daa8a 100644 --- a/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj +++ b/src/Common/test/Logging.Test/Steeltoe.Common.Logging.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj b/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj index c321980aca..723bcb6e1f 100644 --- a/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj +++ b/src/Common/test/Net.Test/Steeltoe.Common.Net.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Common/test/TestResources/Steeltoe.Common.TestResources.csproj b/src/Common/test/TestResources/Steeltoe.Common.TestResources.csproj index ecaf1a6021..c18b16486b 100644 --- a/src/Common/test/TestResources/Steeltoe.Common.TestResources.csproj +++ b/src/Common/test/TestResources/Steeltoe.Common.TestResources.csproj @@ -2,7 +2,6 @@ net8.0 false - enable diff --git a/src/Configuration/src/Abstractions/Steeltoe.Configuration.Abstractions.csproj b/src/Configuration/src/Abstractions/Steeltoe.Configuration.Abstractions.csproj index df859419e0..9d566f2497 100644 --- a/src/Configuration/src/Abstractions/Steeltoe.Configuration.Abstractions.csproj +++ b/src/Configuration/src/Abstractions/Steeltoe.Configuration.Abstractions.csproj @@ -5,7 +5,6 @@ Abstractions used in Steeltoe Configuration libraries abstractions;configuration true - enable diff --git a/src/Configuration/src/CloudFoundry.ServiceBinding/Steeltoe.Configuration.CloudFoundry.ServiceBinding.csproj b/src/Configuration/src/CloudFoundry.ServiceBinding/Steeltoe.Configuration.CloudFoundry.ServiceBinding.csproj index ea24e64bab..48ea46da24 100644 --- a/src/Configuration/src/CloudFoundry.ServiceBinding/Steeltoe.Configuration.CloudFoundry.ServiceBinding.csproj +++ b/src/Configuration/src/CloudFoundry.ServiceBinding/Steeltoe.Configuration.CloudFoundry.ServiceBinding.csproj @@ -4,7 +4,6 @@ Configuration Provider for reading CloudFoundry Service Bindings Configuration;CloudFoundry;Services;Bindings true - enable diff --git a/src/Configuration/src/CloudFoundry/Steeltoe.Configuration.CloudFoundry.csproj b/src/Configuration/src/CloudFoundry/Steeltoe.Configuration.CloudFoundry.csproj index 0d4cd4e751..62fe1f770e 100644 --- a/src/Configuration/src/CloudFoundry/Steeltoe.Configuration.CloudFoundry.csproj +++ b/src/Configuration/src/CloudFoundry/Steeltoe.Configuration.CloudFoundry.csproj @@ -4,7 +4,6 @@ Configuration Provider for reading Cloud Foundry Environment Variables configuration;CloudFoundry;vcap true - enable diff --git a/src/Configuration/src/ConfigServer/Steeltoe.Configuration.ConfigServer.csproj b/src/Configuration/src/ConfigServer/Steeltoe.Configuration.ConfigServer.csproj index 1015b73355..6be853cf61 100644 --- a/src/Configuration/src/ConfigServer/Steeltoe.Configuration.ConfigServer.csproj +++ b/src/Configuration/src/ConfigServer/Steeltoe.Configuration.ConfigServer.csproj @@ -4,7 +4,6 @@ Configuration provider for reading from Spring Cloud Config Server configuration;Spring Cloud;Spring Cloud Config Server true - enable diff --git a/src/Configuration/src/Encryption/Steeltoe.Configuration.Encryption.csproj b/src/Configuration/src/Encryption/Steeltoe.Configuration.Encryption.csproj index c30d6cf567..816d5de07a 100644 --- a/src/Configuration/src/Encryption/Steeltoe.Configuration.Encryption.csproj +++ b/src/Configuration/src/Encryption/Steeltoe.Configuration.Encryption.csproj @@ -4,7 +4,6 @@ Configuration provider for resolving property encryptions in configuration values configuration;encryptions;spring boot true - enable diff --git a/src/Configuration/src/Kubernetes.ServiceBinding/Steeltoe.Configuration.Kubernetes.ServiceBinding.csproj b/src/Configuration/src/Kubernetes.ServiceBinding/Steeltoe.Configuration.Kubernetes.ServiceBinding.csproj index 704e2bcdd3..108b72525e 100644 --- a/src/Configuration/src/Kubernetes.ServiceBinding/Steeltoe.Configuration.Kubernetes.ServiceBinding.csproj +++ b/src/Configuration/src/Kubernetes.ServiceBinding/Steeltoe.Configuration.Kubernetes.ServiceBinding.csproj @@ -4,7 +4,6 @@ Configuration Provider for reading Kubernetes Service Bindings Configuration;Kubernetes;Services;Bindings true - enable diff --git a/src/Configuration/src/Placeholder/Steeltoe.Configuration.Placeholder.csproj b/src/Configuration/src/Placeholder/Steeltoe.Configuration.Placeholder.csproj index 34514190e6..1c48bfdc22 100644 --- a/src/Configuration/src/Placeholder/Steeltoe.Configuration.Placeholder.csproj +++ b/src/Configuration/src/Placeholder/Steeltoe.Configuration.Placeholder.csproj @@ -4,7 +4,6 @@ Configuration provider for resolving property placeholders in configuration values configuration;placeholders;spring boot true - enable diff --git a/src/Configuration/src/RandomValue/Steeltoe.Configuration.RandomValue.csproj b/src/Configuration/src/RandomValue/Steeltoe.Configuration.RandomValue.csproj index 8fb5b9b3b7..734ffb4173 100644 --- a/src/Configuration/src/RandomValue/Steeltoe.Configuration.RandomValue.csproj +++ b/src/Configuration/src/RandomValue/Steeltoe.Configuration.RandomValue.csproj @@ -4,7 +4,6 @@ Configuration provider for generating random values configuration;random values true - enable diff --git a/src/Configuration/src/SpringBoot/Steeltoe.Configuration.SpringBoot.csproj b/src/Configuration/src/SpringBoot/Steeltoe.Configuration.SpringBoot.csproj index 23d2d1010c..ce8345bb10 100644 --- a/src/Configuration/src/SpringBoot/Steeltoe.Configuration.SpringBoot.csproj +++ b/src/Configuration/src/SpringBoot/Steeltoe.Configuration.SpringBoot.csproj @@ -4,7 +4,6 @@ Configuration provider for reading Spring Boot style configuration configuration;springboot true - enable diff --git a/src/Configuration/test/CloudFoundry.ServiceBinding.Test/Steeltoe.Configuration.CloudFoundry.ServiceBinding.Test.csproj b/src/Configuration/test/CloudFoundry.ServiceBinding.Test/Steeltoe.Configuration.CloudFoundry.ServiceBinding.Test.csproj index eddf1b1b3b..27c772ef90 100644 --- a/src/Configuration/test/CloudFoundry.ServiceBinding.Test/Steeltoe.Configuration.CloudFoundry.ServiceBinding.Test.csproj +++ b/src/Configuration/test/CloudFoundry.ServiceBinding.Test/Steeltoe.Configuration.CloudFoundry.ServiceBinding.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/CloudFoundry.Test/Steeltoe.Configuration.CloudFoundry.Test.csproj b/src/Configuration/test/CloudFoundry.Test/Steeltoe.Configuration.CloudFoundry.Test.csproj index ad135b2c4d..ddcb4ad1f4 100644 --- a/src/Configuration/test/CloudFoundry.Test/Steeltoe.Configuration.CloudFoundry.Test.csproj +++ b/src/Configuration/test/CloudFoundry.Test/Steeltoe.Configuration.CloudFoundry.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/ConfigServer.Discovery.Test/Steeltoe.Configuration.ConfigServer.Discovery.Test.csproj b/src/Configuration/test/ConfigServer.Discovery.Test/Steeltoe.Configuration.ConfigServer.Discovery.Test.csproj index 5cd42122a6..b16b41e2db 100644 --- a/src/Configuration/test/ConfigServer.Discovery.Test/Steeltoe.Configuration.ConfigServer.Discovery.Test.csproj +++ b/src/Configuration/test/ConfigServer.Discovery.Test/Steeltoe.Configuration.ConfigServer.Discovery.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/ConfigServer.Integration.Test/Steeltoe.Configuration.ConfigServer.Integration.Test.csproj b/src/Configuration/test/ConfigServer.Integration.Test/Steeltoe.Configuration.ConfigServer.Integration.Test.csproj index f8be3106fa..6523e52f50 100644 --- a/src/Configuration/test/ConfigServer.Integration.Test/Steeltoe.Configuration.ConfigServer.Integration.Test.csproj +++ b/src/Configuration/test/ConfigServer.Integration.Test/Steeltoe.Configuration.ConfigServer.Integration.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/ConfigServer.Test/Steeltoe.Configuration.ConfigServer.Test.csproj b/src/Configuration/test/ConfigServer.Test/Steeltoe.Configuration.ConfigServer.Test.csproj index eb326eae29..d9e3110273 100644 --- a/src/Configuration/test/ConfigServer.Test/Steeltoe.Configuration.ConfigServer.Test.csproj +++ b/src/Configuration/test/ConfigServer.Test/Steeltoe.Configuration.ConfigServer.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/Encryption.Test/Steeltoe.Configuration.Encryption.Test.csproj b/src/Configuration/test/Encryption.Test/Steeltoe.Configuration.Encryption.Test.csproj index 9f3e1f7f90..977006b03f 100644 --- a/src/Configuration/test/Encryption.Test/Steeltoe.Configuration.Encryption.Test.csproj +++ b/src/Configuration/test/Encryption.Test/Steeltoe.Configuration.Encryption.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/Kubernetes.ServiceBinding.Test/Steeltoe.Configuration.Kubernetes.ServiceBinding.Test.csproj b/src/Configuration/test/Kubernetes.ServiceBinding.Test/Steeltoe.Configuration.Kubernetes.ServiceBinding.Test.csproj index 43b3447c04..cf6cae6831 100644 --- a/src/Configuration/test/Kubernetes.ServiceBinding.Test/Steeltoe.Configuration.Kubernetes.ServiceBinding.Test.csproj +++ b/src/Configuration/test/Kubernetes.ServiceBinding.Test/Steeltoe.Configuration.Kubernetes.ServiceBinding.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/Placeholder.Test/Steeltoe.Configuration.Placeholder.Test.csproj b/src/Configuration/test/Placeholder.Test/Steeltoe.Configuration.Placeholder.Test.csproj index 5ddbfadddc..4b66b3e5c7 100644 --- a/src/Configuration/test/Placeholder.Test/Steeltoe.Configuration.Placeholder.Test.csproj +++ b/src/Configuration/test/Placeholder.Test/Steeltoe.Configuration.Placeholder.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/RandomValue.Test/Steeltoe.Configuration.RandomValue.Test.csproj b/src/Configuration/test/RandomValue.Test/Steeltoe.Configuration.RandomValue.Test.csproj index aeb3c94197..d0ab095b9a 100644 --- a/src/Configuration/test/RandomValue.Test/Steeltoe.Configuration.RandomValue.Test.csproj +++ b/src/Configuration/test/RandomValue.Test/Steeltoe.Configuration.RandomValue.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Configuration/test/SpringBoot.Test/Steeltoe.Configuration.SpringBoot.Test.csproj b/src/Configuration/test/SpringBoot.Test/Steeltoe.Configuration.SpringBoot.Test.csproj index 7e9609335d..7dae9a9e1a 100644 --- a/src/Configuration/test/SpringBoot.Test/Steeltoe.Configuration.SpringBoot.Test.csproj +++ b/src/Configuration/test/SpringBoot.Test/Steeltoe.Configuration.SpringBoot.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Connectors/src/Connectors/Steeltoe.Connectors.csproj b/src/Connectors/src/Connectors/Steeltoe.Connectors.csproj index 39f88a9deb..92f8fbf380 100644 --- a/src/Connectors/src/Connectors/Steeltoe.Connectors.csproj +++ b/src/Connectors/src/Connectors/Steeltoe.Connectors.csproj @@ -4,7 +4,6 @@ Connectors for using service bindings in your application connectors;services true - enable diff --git a/src/Connectors/src/EntityFrameworkCore/Steeltoe.Connectors.EntityFrameworkCore.csproj b/src/Connectors/src/EntityFrameworkCore/Steeltoe.Connectors.EntityFrameworkCore.csproj index 7b241e6011..2d57cb2876 100644 --- a/src/Connectors/src/EntityFrameworkCore/Steeltoe.Connectors.EntityFrameworkCore.csproj +++ b/src/Connectors/src/EntityFrameworkCore/Steeltoe.Connectors.EntityFrameworkCore.csproj @@ -4,7 +4,6 @@ Package for using Steeltoe Connectors with Entity Framework Core connectors;EFCore;EntityFrameworkCore;EF;Entity Framework Core;entity-framework-core;services true - enable diff --git a/src/Connectors/test/Connectors.Test/Steeltoe.Connectors.Test.csproj b/src/Connectors/test/Connectors.Test/Steeltoe.Connectors.Test.csproj index 0a1a789747..55c020af0d 100644 --- a/src/Connectors/test/Connectors.Test/Steeltoe.Connectors.Test.csproj +++ b/src/Connectors/test/Connectors.Test/Steeltoe.Connectors.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Connectors/test/EntityFrameworkCore.Test/Steeltoe.Connectors.EntityFrameworkCore.Test.csproj b/src/Connectors/test/EntityFrameworkCore.Test/Steeltoe.Connectors.EntityFrameworkCore.Test.csproj index a80ec1f305..b45e7f120e 100644 --- a/src/Connectors/test/EntityFrameworkCore.Test/Steeltoe.Connectors.EntityFrameworkCore.Test.csproj +++ b/src/Connectors/test/EntityFrameworkCore.Test/Steeltoe.Connectors.EntityFrameworkCore.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Discovery/src/Configuration/Steeltoe.Discovery.Configuration.csproj b/src/Discovery/src/Configuration/Steeltoe.Discovery.Configuration.csproj index 3917ebdc55..4d71f834d0 100644 --- a/src/Discovery/src/Configuration/Steeltoe.Discovery.Configuration.csproj +++ b/src/Discovery/src/Configuration/Steeltoe.Discovery.Configuration.csproj @@ -4,7 +4,6 @@ Client for service discovery from application configuration service-discovery;service-registry;configuration-based true - enable diff --git a/src/Discovery/src/Consul/Steeltoe.Discovery.Consul.csproj b/src/Discovery/src/Consul/Steeltoe.Discovery.Consul.csproj index 3966315432..6e3551e2d9 100644 --- a/src/Discovery/src/Consul/Steeltoe.Discovery.Consul.csproj +++ b/src/Discovery/src/Consul/Steeltoe.Discovery.Consul.csproj @@ -4,7 +4,6 @@ Steeltoe compatibility package for service discovery and registration with Hashicorp Consul service-discovery;service-registry;Consul;hashicorp true - enable diff --git a/src/Discovery/src/Eureka/Steeltoe.Discovery.Eureka.csproj b/src/Discovery/src/Eureka/Steeltoe.Discovery.Eureka.csproj index 3546ce7404..863d7f3cd3 100644 --- a/src/Discovery/src/Eureka/Steeltoe.Discovery.Eureka.csproj +++ b/src/Discovery/src/Eureka/Steeltoe.Discovery.Eureka.csproj @@ -4,7 +4,6 @@ Client for service discovery and registration with Neflix Eureka service-discovery;service-registry;Netflix-Eureka;netflix;eureka true - enable diff --git a/src/Discovery/src/HttpClients/Steeltoe.Discovery.HttpClients.csproj b/src/Discovery/src/HttpClients/Steeltoe.Discovery.HttpClients.csproj index b8a4f5bbf5..0aac4ab2b5 100644 --- a/src/Discovery/src/HttpClients/Steeltoe.Discovery.HttpClients.csproj +++ b/src/Discovery/src/HttpClients/Steeltoe.Discovery.HttpClients.csproj @@ -4,7 +4,6 @@ Base package for using Steeltoe Service Discovery service-discovery;service-registry;load-balancing;round-robin;httpclient;httpclientfactory true - enable diff --git a/src/Discovery/test/Configuration.Test/Steeltoe.Discovery.Configuration.Test.csproj b/src/Discovery/test/Configuration.Test/Steeltoe.Discovery.Configuration.Test.csproj index 7eff728a55..0a640dc01b 100644 --- a/src/Discovery/test/Configuration.Test/Steeltoe.Discovery.Configuration.Test.csproj +++ b/src/Discovery/test/Configuration.Test/Steeltoe.Discovery.Configuration.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Discovery/test/Consul.Test/Steeltoe.Discovery.Consul.Test.csproj b/src/Discovery/test/Consul.Test/Steeltoe.Discovery.Consul.Test.csproj index fe2cb3a1f3..d5f27aecab 100644 --- a/src/Discovery/test/Consul.Test/Steeltoe.Discovery.Consul.Test.csproj +++ b/src/Discovery/test/Consul.Test/Steeltoe.Discovery.Consul.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Discovery/test/Eureka.Test/Steeltoe.Discovery.Eureka.Test.csproj b/src/Discovery/test/Eureka.Test/Steeltoe.Discovery.Eureka.Test.csproj index 4b67728adb..1370a7be19 100644 --- a/src/Discovery/test/Eureka.Test/Steeltoe.Discovery.Eureka.Test.csproj +++ b/src/Discovery/test/Eureka.Test/Steeltoe.Discovery.Eureka.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Discovery/test/HttpClients.Test/Steeltoe.Discovery.HttpClients.Test.csproj b/src/Discovery/test/HttpClients.Test/Steeltoe.Discovery.HttpClients.Test.csproj index 6c8b4413af..0a27762eae 100644 --- a/src/Discovery/test/HttpClients.Test/Steeltoe.Discovery.HttpClients.Test.csproj +++ b/src/Discovery/test/HttpClients.Test/Steeltoe.Discovery.HttpClients.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Logging/src/Abstractions/Steeltoe.Logging.Abstractions.csproj b/src/Logging/src/Abstractions/Steeltoe.Logging.Abstractions.csproj index 7651a53ce4..ecdf195606 100644 --- a/src/Logging/src/Abstractions/Steeltoe.Logging.Abstractions.csproj +++ b/src/Logging/src/Abstractions/Steeltoe.Logging.Abstractions.csproj @@ -5,7 +5,6 @@ Abstractions for use with dynamic logging abstractions;logging;dynamic-logging;log-management true - enable diff --git a/src/Logging/src/DynamicLogger/Steeltoe.Logging.DynamicLogger.csproj b/src/Logging/src/DynamicLogger/Steeltoe.Logging.DynamicLogger.csproj index 69b7fcc321..a2eadd4577 100644 --- a/src/Logging/src/DynamicLogger/Steeltoe.Logging.DynamicLogger.csproj +++ b/src/Logging/src/DynamicLogger/Steeltoe.Logging.DynamicLogger.csproj @@ -4,7 +4,6 @@ Steeltoe Dynamic Console Logger logging;dynamic-logging;console;log-management;monitoring true - enable diff --git a/src/Logging/src/DynamicSerilog/Steeltoe.Logging.DynamicSerilog.csproj b/src/Logging/src/DynamicSerilog/Steeltoe.Logging.DynamicSerilog.csproj index 5520a1d491..c069c7d8b8 100644 --- a/src/Logging/src/DynamicSerilog/Steeltoe.Logging.DynamicSerilog.csproj +++ b/src/Logging/src/DynamicSerilog/Steeltoe.Logging.DynamicSerilog.csproj @@ -4,7 +4,6 @@ Steeltoe library for enabling dynamic management of Serilog. logging;dynamic-logging;serilog;log-management;monitoring true - enable diff --git a/src/Logging/test/DynamicLogger.Test/Steeltoe.Logging.DynamicLogger.Test.csproj b/src/Logging/test/DynamicLogger.Test/Steeltoe.Logging.DynamicLogger.Test.csproj index bfbc03f95b..401f220861 100644 --- a/src/Logging/test/DynamicLogger.Test/Steeltoe.Logging.DynamicLogger.Test.csproj +++ b/src/Logging/test/DynamicLogger.Test/Steeltoe.Logging.DynamicLogger.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Logging/test/DynamicSerilog.Test/Steeltoe.Logging.DynamicSerilog.Test.csproj b/src/Logging/test/DynamicSerilog.Test/Steeltoe.Logging.DynamicSerilog.Test.csproj index d914f8d165..ab0ab437da 100644 --- a/src/Logging/test/DynamicSerilog.Test/Steeltoe.Logging.DynamicSerilog.Test.csproj +++ b/src/Logging/test/DynamicSerilog.Test/Steeltoe.Logging.DynamicSerilog.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Management/src/Abstractions/Steeltoe.Management.Abstractions.csproj b/src/Management/src/Abstractions/Steeltoe.Management.Abstractions.csproj index 606ae9ceb2..db953d02bc 100644 --- a/src/Management/src/Abstractions/Steeltoe.Management.Abstractions.csproj +++ b/src/Management/src/Abstractions/Steeltoe.Management.Abstractions.csproj @@ -5,7 +5,6 @@ Abstractions for application management and monitoring abstractions;log-management;monitoring;actuator true - enable diff --git a/src/Management/src/Endpoint/Steeltoe.Management.Endpoint.csproj b/src/Management/src/Endpoint/Steeltoe.Management.Endpoint.csproj index 7bbb7afb30..b9b2069404 100755 --- a/src/Management/src/Endpoint/Steeltoe.Management.Endpoint.csproj +++ b/src/Management/src/Endpoint/Steeltoe.Management.Endpoint.csproj @@ -5,7 +5,6 @@ actuators;management;monitoring;Spring Cloud true true - enable $(DefineConstants);MEMORYMARSHAL_SUPPORT diff --git a/src/Management/src/Prometheus/Steeltoe.Management.Prometheus.csproj b/src/Management/src/Prometheus/Steeltoe.Management.Prometheus.csproj index 1460dc8a4b..519f7004ff 100644 --- a/src/Management/src/Prometheus/Steeltoe.Management.Prometheus.csproj +++ b/src/Management/src/Prometheus/Steeltoe.Management.Prometheus.csproj @@ -4,7 +4,6 @@ Adds Prometheus support for Steeltoe management endpoints actuators;management;monitoring;distributed tracing;metrics;prometheus true - enable diff --git a/src/Management/src/Tasks/Steeltoe.Management.Tasks.csproj b/src/Management/src/Tasks/Steeltoe.Management.Tasks.csproj index db06cd4c38..aa37e3ce72 100644 --- a/src/Management/src/Tasks/Steeltoe.Management.Tasks.csproj +++ b/src/Management/src/Tasks/Steeltoe.Management.Tasks.csproj @@ -4,7 +4,6 @@ Extensions for running tasks embedded in your ASP.NET Core application. Ideal for cf run-task in Cloud Foundry. tasks;management;monitoring;aspnetcore;Spring Cloud;cf run-task true - enable diff --git a/src/Management/src/Tracing/Steeltoe.Management.Tracing.csproj b/src/Management/src/Tracing/Steeltoe.Management.Tracing.csproj index 4918f04dc1..ba4fcdafec 100644 --- a/src/Management/src/Tracing/Steeltoe.Management.Tracing.csproj +++ b/src/Management/src/Tracing/Steeltoe.Management.Tracing.csproj @@ -4,7 +4,6 @@ Enables request tracing in distributed systems. management;monitoring;distributed tracing true - enable diff --git a/src/Management/src/Wavefront/Steeltoe.Management.Wavefront.csproj b/src/Management/src/Wavefront/Steeltoe.Management.Wavefront.csproj index 6f1b440a44..70e23d55f6 100644 --- a/src/Management/src/Wavefront/Steeltoe.Management.Wavefront.csproj +++ b/src/Management/src/Wavefront/Steeltoe.Management.Wavefront.csproj @@ -4,7 +4,6 @@ Adds Wavefront support for Steeltoe management endpoints actuators;management;monitoring;distributed tracing;metrics;wavefront true - enable diff --git a/src/Management/test/Endpoint.Test/Steeltoe.Management.Endpoint.Test.csproj b/src/Management/test/Endpoint.Test/Steeltoe.Management.Endpoint.Test.csproj index cf95e3507d..be61bb63a1 100644 --- a/src/Management/test/Endpoint.Test/Steeltoe.Management.Endpoint.Test.csproj +++ b/src/Management/test/Endpoint.Test/Steeltoe.Management.Endpoint.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Management/test/Prometheus.Test/Steeltoe.Management.Prometheus.Test.csproj b/src/Management/test/Prometheus.Test/Steeltoe.Management.Prometheus.Test.csproj index 93e8d0d23f..e2d38aac65 100644 --- a/src/Management/test/Prometheus.Test/Steeltoe.Management.Prometheus.Test.csproj +++ b/src/Management/test/Prometheus.Test/Steeltoe.Management.Prometheus.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Management/test/Tasks.Test/Steeltoe.Management.Tasks.Test.csproj b/src/Management/test/Tasks.Test/Steeltoe.Management.Tasks.Test.csproj index a1d685b06c..5e483939ee 100644 --- a/src/Management/test/Tasks.Test/Steeltoe.Management.Tasks.Test.csproj +++ b/src/Management/test/Tasks.Test/Steeltoe.Management.Tasks.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Management/test/Tracing.Test/Steeltoe.Management.Tracing.Test.csproj b/src/Management/test/Tracing.Test/Steeltoe.Management.Tracing.Test.csproj index 8e7651c158..81839cd02d 100644 --- a/src/Management/test/Tracing.Test/Steeltoe.Management.Tracing.Test.csproj +++ b/src/Management/test/Tracing.Test/Steeltoe.Management.Tracing.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Management/test/Wavefront.Test/Steeltoe.Management.Wavefront.Test.csproj b/src/Management/test/Wavefront.Test/Steeltoe.Management.Wavefront.Test.csproj index 1e86d72ede..c47dc52a8f 100644 --- a/src/Management/test/Wavefront.Test/Steeltoe.Management.Wavefront.Test.csproj +++ b/src/Management/test/Wavefront.Test/Steeltoe.Management.Wavefront.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Security/src/Authentication.JwtBearer/Steeltoe.Security.Authentication.JwtBearer.csproj b/src/Security/src/Authentication.JwtBearer/Steeltoe.Security.Authentication.JwtBearer.csproj index 1a1efb125d..a130497097 100644 --- a/src/Security/src/Authentication.JwtBearer/Steeltoe.Security.Authentication.JwtBearer.csproj +++ b/src/Security/src/Authentication.JwtBearer/Steeltoe.Security.Authentication.JwtBearer.csproj @@ -4,7 +4,6 @@ Library for using JWT Bearer tokens with UAA-based systems, including Cloud Foundry CloudFoundry;uaa;security;jwt;bearer true - enable diff --git a/src/Security/src/Authentication.OpenIdConnect/Steeltoe.Security.Authentication.OpenIdConnect.csproj b/src/Security/src/Authentication.OpenIdConnect/Steeltoe.Security.Authentication.OpenIdConnect.csproj index 60b94c15fa..98ae1da05d 100644 --- a/src/Security/src/Authentication.OpenIdConnect/Steeltoe.Security.Authentication.OpenIdConnect.csproj +++ b/src/Security/src/Authentication.OpenIdConnect/Steeltoe.Security.Authentication.OpenIdConnect.csproj @@ -4,7 +4,6 @@ Library for using OpenID Connect with UAA-based systems, including Cloud Foundry CloudFoundry;uaa;security;sso;openid;oidc true - enable diff --git a/src/Security/src/Authorization.Certificate/Steeltoe.Security.Authorization.Certificate.csproj b/src/Security/src/Authorization.Certificate/Steeltoe.Security.Authorization.Certificate.csproj index 286d038a16..80fe4f0041 100644 --- a/src/Security/src/Authorization.Certificate/Steeltoe.Security.Authorization.Certificate.csproj +++ b/src/Security/src/Authorization.Certificate/Steeltoe.Security.Authorization.Certificate.csproj @@ -4,7 +4,6 @@ This package provides support for authorization with client certificates. aspnetcore;authorization;security;x509;certificate;mutualtls true - enable diff --git a/src/Security/src/DataProtection.Redis/Steeltoe.Security.DataProtection.Redis.csproj b/src/Security/src/DataProtection.Redis/Steeltoe.Security.DataProtection.Redis.csproj index fdb9fc27e1..a4f497d89b 100644 --- a/src/Security/src/DataProtection.Redis/Steeltoe.Security.DataProtection.Redis.csproj +++ b/src/Security/src/DataProtection.Redis/Steeltoe.Security.DataProtection.Redis.csproj @@ -4,7 +4,6 @@ Support for storing data protection keys in Redis. CloudFoundry;aspnetcore;security;dataprotection;redis true - enable diff --git a/src/Security/test/Authentication.JwtBearer.Test/Steeltoe.Security.Authentication.JwtBearer.Test.csproj b/src/Security/test/Authentication.JwtBearer.Test/Steeltoe.Security.Authentication.JwtBearer.Test.csproj index 70352f988f..b06bc9f452 100644 --- a/src/Security/test/Authentication.JwtBearer.Test/Steeltoe.Security.Authentication.JwtBearer.Test.csproj +++ b/src/Security/test/Authentication.JwtBearer.Test/Steeltoe.Security.Authentication.JwtBearer.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Security/test/Authentication.OpenIdConnect.Test/Steeltoe.Security.Authentication.OpenIdConnect.Test.csproj b/src/Security/test/Authentication.OpenIdConnect.Test/Steeltoe.Security.Authentication.OpenIdConnect.Test.csproj index 7fb9379020..c6e437666e 100644 --- a/src/Security/test/Authentication.OpenIdConnect.Test/Steeltoe.Security.Authentication.OpenIdConnect.Test.csproj +++ b/src/Security/test/Authentication.OpenIdConnect.Test/Steeltoe.Security.Authentication.OpenIdConnect.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Security/test/Authorization.Certificate.Test/Steeltoe.Security.Authorization.Certificate.Test.csproj b/src/Security/test/Authorization.Certificate.Test/Steeltoe.Security.Authorization.Certificate.Test.csproj index f84c976f96..f709ece594 100644 --- a/src/Security/test/Authorization.Certificate.Test/Steeltoe.Security.Authorization.Certificate.Test.csproj +++ b/src/Security/test/Authorization.Certificate.Test/Steeltoe.Security.Authorization.Certificate.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Security/test/DataProtection.Redis.Test/Steeltoe.Security.DataProtection.Redis.Test.csproj b/src/Security/test/DataProtection.Redis.Test/Steeltoe.Security.DataProtection.Redis.Test.csproj index e52279adce..d39a90ef02 100644 --- a/src/Security/test/DataProtection.Redis.Test/Steeltoe.Security.DataProtection.Redis.Test.csproj +++ b/src/Security/test/DataProtection.Redis.Test/Steeltoe.Security.DataProtection.Redis.Test.csproj @@ -1,7 +1,6 @@ net8.0 - enable diff --git a/src/Tools/src/ConfigurationSchemaGenerator/ConfigurationSchemaGenerator.csproj b/src/Tools/src/ConfigurationSchemaGenerator/ConfigurationSchemaGenerator.csproj index 3914f0b570..7d7f8396c5 100644 --- a/src/Tools/src/ConfigurationSchemaGenerator/ConfigurationSchemaGenerator.csproj +++ b/src/Tools/src/ConfigurationSchemaGenerator/ConfigurationSchemaGenerator.csproj @@ -4,7 +4,6 @@ false Exe enable - annotations - - - - - - $(NoWarn);SA1401;S1168;S2360;S3900;S3956;S4004;S4023 - diff --git a/src/Common/src/Certificates/PublicAPI.Unshipped.txt b/src/Common/src/Certificates/PublicAPI.Unshipped.txt index 2c95369d08..51b5683989 100644 --- a/src/Common/src/Certificates/PublicAPI.Unshipped.txt +++ b/src/Common/src/Certificates/PublicAPI.Unshipped.txt @@ -1,7 +1,11 @@ #nullable enable static Steeltoe.Common.Certificates.CertificateConfigurationExtensions.AddAppInstanceIdentityCertificate(this Microsoft.Extensions.Configuration.IConfigurationBuilder! builder) -> Microsoft.Extensions.Configuration.IConfigurationBuilder! static Steeltoe.Common.Certificates.CertificateConfigurationExtensions.AddAppInstanceIdentityCertificate(this Microsoft.Extensions.Configuration.IConfigurationBuilder! builder, System.Guid? organizationId, System.Guid? spaceId) -> Microsoft.Extensions.Configuration.IConfigurationBuilder! -static Steeltoe.Common.Certificates.CertificateServiceCollectionExtensions.ConfigureCertificateOptions(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, string? certificateName) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! -static Steeltoe.Common.Certificates.CertificateServiceCollectionExtensions.ConfigureCertificateOptions(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, string? certificateName, Microsoft.Extensions.FileProviders.IFileProvider? fileProvider) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Steeltoe.Common.Certificates.CertificateServiceCollectionExtensions.ConfigureCertificateOptions(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, string! certificateName) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! Steeltoe.Common.Certificates.CertificateConfigurationExtensions +Steeltoe.Common.Certificates.CertificateOptions +Steeltoe.Common.Certificates.CertificateOptions.Certificate.get -> System.Security.Cryptography.X509Certificates.X509Certificate2? +Steeltoe.Common.Certificates.CertificateOptions.Certificate.set -> void +Steeltoe.Common.Certificates.CertificateOptions.CertificateOptions() -> void +Steeltoe.Common.Certificates.CertificateOptions.IssuerChain.get -> System.Collections.Generic.IList! Steeltoe.Common.Certificates.CertificateServiceCollectionExtensions diff --git a/src/Common/src/Common/PublicAPI.Shipped.txt b/src/Common/src/Common/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Common/src/Common/PublicAPI.Unshipped.txt b/src/Common/src/Common/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..b9c14c6c00 --- /dev/null +++ b/src/Common/src/Common/PublicAPI.Unshipped.txt @@ -0,0 +1,82 @@ +#nullable enable +override Steeltoe.Common.CasingConventions.SnakeCaseAllCapsEnumMemberJsonConverter.CanConvert(System.Type! typeToConvert) -> bool +override Steeltoe.Common.CasingConventions.SnakeCaseAllCapsEnumMemberJsonConverter.CreateConverter(System.Type! typeToConvert, System.Text.Json.JsonSerializerOptions! options) -> System.Text.Json.Serialization.JsonConverter! +static Steeltoe.Common.CasingConventions.EnumExtensions.ToSnakeCaseString(this TEnum value, Steeltoe.Common.CasingConventions.SnakeCaseStyle style) -> string! +static Steeltoe.Common.Extensions.ServiceCollectionExtensions.AddApplicationInstanceInfo(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Steeltoe.Common.Platform.IsCloudFoundry.get -> bool +static Steeltoe.Common.Platform.IsCloudHosted.get -> bool +static Steeltoe.Common.Platform.IsContainerized.get -> bool +static Steeltoe.Common.Platform.IsKubernetes.get -> bool +static Steeltoe.Common.Platform.IsLinux.get -> bool +static Steeltoe.Common.Platform.IsOSX.get -> bool +static Steeltoe.Common.Platform.IsWindows.get -> bool +Steeltoe.Common.ApplicationInstanceInfo +Steeltoe.Common.ApplicationInstanceInfo.ApplicationId.get -> string? +Steeltoe.Common.ApplicationInstanceInfo.ApplicationId.set -> void +Steeltoe.Common.ApplicationInstanceInfo.ApplicationInstanceInfo() -> void +Steeltoe.Common.ApplicationInstanceInfo.ApplicationName.get -> string? +Steeltoe.Common.ApplicationInstanceInfo.ApplicationName.set -> void +Steeltoe.Common.ApplicationInstanceInfo.InstanceId.get -> string? +Steeltoe.Common.ApplicationInstanceInfo.InstanceId.set -> void +Steeltoe.Common.ApplicationInstanceInfo.InstanceIndex.get -> int +Steeltoe.Common.ApplicationInstanceInfo.InstanceIndex.set -> void +Steeltoe.Common.ApplicationInstanceInfo.InternalIP.get -> string? +Steeltoe.Common.ApplicationInstanceInfo.InternalIP.set -> void +Steeltoe.Common.ApplicationInstanceInfo.Uris.get -> System.Collections.Generic.IList! +Steeltoe.Common.CasingConventions.EnumExtensions +Steeltoe.Common.CasingConventions.SnakeCaseAllCapsEnumMemberJsonConverter +Steeltoe.Common.CasingConventions.SnakeCaseAllCapsEnumMemberJsonConverter.SnakeCaseAllCapsEnumMemberJsonConverter() -> void +Steeltoe.Common.CasingConventions.SnakeCaseStyle +Steeltoe.Common.CasingConventions.SnakeCaseStyle.AllCaps = 0 -> Steeltoe.Common.CasingConventions.SnakeCaseStyle +Steeltoe.Common.CasingConventions.SnakeCaseStyle.NoCaps = 1 -> Steeltoe.Common.CasingConventions.SnakeCaseStyle +Steeltoe.Common.Discovery.IDiscoveryClient +Steeltoe.Common.Discovery.IDiscoveryClient.Description.get -> string! +Steeltoe.Common.Discovery.IDiscoveryClient.GetInstancesAsync(string! serviceId, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!>! +Steeltoe.Common.Discovery.IDiscoveryClient.GetLocalServiceInstance() -> Steeltoe.Common.Discovery.IServiceInstance? +Steeltoe.Common.Discovery.IDiscoveryClient.GetServiceIdsAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!>! +Steeltoe.Common.Discovery.IDiscoveryClient.ShutdownAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Steeltoe.Common.Discovery.IServiceInstance +Steeltoe.Common.Discovery.IServiceInstance.Host.get -> string! +Steeltoe.Common.Discovery.IServiceInstance.IsSecure.get -> bool +Steeltoe.Common.Discovery.IServiceInstance.Metadata.get -> System.Collections.Generic.IReadOnlyDictionary! +Steeltoe.Common.Discovery.IServiceInstance.Port.get -> int +Steeltoe.Common.Discovery.IServiceInstance.ServiceId.get -> string! +Steeltoe.Common.Discovery.IServiceInstance.Uri.get -> System.Uri! +Steeltoe.Common.Extensions.ServiceCollectionExtensions +Steeltoe.Common.HealthChecks.HealthCheckResult +Steeltoe.Common.HealthChecks.HealthCheckResult.Description.get -> string? +Steeltoe.Common.HealthChecks.HealthCheckResult.Description.set -> void +Steeltoe.Common.HealthChecks.HealthCheckResult.Details.get -> System.Collections.Generic.IDictionary! +Steeltoe.Common.HealthChecks.HealthCheckResult.HealthCheckResult() -> void +Steeltoe.Common.HealthChecks.HealthCheckResult.Status.get -> Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Common.HealthChecks.HealthCheckResult.Status.set -> void +Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Common.HealthChecks.HealthStatus.Down = 4 -> Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Common.HealthChecks.HealthStatus.OutOfService = 3 -> Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Common.HealthChecks.HealthStatus.Unknown = 0 -> Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Common.HealthChecks.HealthStatus.Up = 1 -> Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Common.HealthChecks.HealthStatus.Warning = 2 -> Steeltoe.Common.HealthChecks.HealthStatus +Steeltoe.Common.HealthChecks.IHealthAggregator +Steeltoe.Common.HealthChecks.IHealthAggregator.AggregateAsync(System.Collections.Generic.ICollection! contributors, System.Collections.Generic.ICollection! healthCheckRegistrations, System.IServiceProvider! serviceProvider, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Steeltoe.Common.HealthChecks.IHealthContributor +Steeltoe.Common.HealthChecks.IHealthContributor.CheckHealthAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Steeltoe.Common.HealthChecks.IHealthContributor.Id.get -> string! +Steeltoe.Common.IApplicationInstanceInfo +Steeltoe.Common.IApplicationInstanceInfo.ApplicationName.get -> string? +Steeltoe.Common.IApplicationTask +Steeltoe.Common.IApplicationTask.RunAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Steeltoe.Common.Net.InetOptions +Steeltoe.Common.Net.InetOptions.DefaultHostname.get -> string? +Steeltoe.Common.Net.InetOptions.DefaultHostname.set -> void +Steeltoe.Common.Net.InetOptions.DefaultIPAddress.get -> string? +Steeltoe.Common.Net.InetOptions.DefaultIPAddress.set -> void +Steeltoe.Common.Net.InetOptions.IgnoredInterfaces.get -> string? +Steeltoe.Common.Net.InetOptions.IgnoredInterfaces.set -> void +Steeltoe.Common.Net.InetOptions.InetOptions() -> void +Steeltoe.Common.Net.InetOptions.PreferredNetworks.get -> string? +Steeltoe.Common.Net.InetOptions.PreferredNetworks.set -> void +Steeltoe.Common.Net.InetOptions.SkipReverseDnsLookup.get -> bool +Steeltoe.Common.Net.InetOptions.SkipReverseDnsLookup.set -> void +Steeltoe.Common.Net.InetOptions.UseOnlySiteLocalInterfaces.get -> bool +Steeltoe.Common.Net.InetOptions.UseOnlySiteLocalInterfaces.set -> void +Steeltoe.Common.Platform diff --git a/src/Common/src/Hosting/PublicAPI.Shipped.txt b/src/Common/src/Hosting/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Common/src/Hosting/PublicAPI.Unshipped.txt b/src/Common/src/Hosting/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..7dc5c58110 --- /dev/null +++ b/src/Common/src/Hosting/PublicAPI.Unshipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/Common/src/Http/HttpClientPooling/IValidateCertificatesOptions.cs b/src/Common/src/Http/HttpClientPooling/IValidateCertificatesOptions.cs index 1ae701fe1f..d0015b0d76 100644 --- a/src/Common/src/Http/HttpClientPooling/IValidateCertificatesOptions.cs +++ b/src/Common/src/Http/HttpClientPooling/IValidateCertificatesOptions.cs @@ -7,7 +7,7 @@ namespace Steeltoe.Common.Http.HttpClientPooling; /// /// Indicates that an options type provides a boolean to turn off certificate validation. /// -public interface IValidateCertificatesOptions +internal interface IValidateCertificatesOptions { bool ValidateCertificates { get; set; } } diff --git a/src/Common/src/Http/PublicAPI.Shipped.txt b/src/Common/src/Http/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Common/src/Http/PublicAPI.Unshipped.txt b/src/Common/src/Http/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..4fbff9eb6d --- /dev/null +++ b/src/Common/src/Http/PublicAPI.Unshipped.txt @@ -0,0 +1,5 @@ +#nullable enable +Steeltoe.Common.Http.HttpClientPooling.HttpClientHandlerFactory +Steeltoe.Common.Http.HttpClientPooling.HttpClientHandlerFactory.Create() -> System.Net.Http.HttpClientHandler! +Steeltoe.Common.Http.HttpClientPooling.HttpClientHandlerFactory.HttpClientHandlerFactory() -> void +Steeltoe.Common.Http.HttpClientPooling.HttpClientHandlerFactory.Using(System.Net.Http.HttpClientHandler! handler) -> Steeltoe.Common.Http.HttpClientPooling.HttpClientHandlerFactory! diff --git a/src/Common/src/Logging/PublicAPI.Shipped.txt b/src/Common/src/Logging/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Common/src/Logging/PublicAPI.Unshipped.txt b/src/Common/src/Logging/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..82cfe70800 --- /dev/null +++ b/src/Common/src/Logging/PublicAPI.Unshipped.txt @@ -0,0 +1,6 @@ +#nullable enable +static Steeltoe.Common.Logging.BootstrapLoggerFactory.Default.get -> Steeltoe.Common.Logging.IBootstrapLoggerFactory! +Steeltoe.Common.Logging.BootstrapLoggerFactory +Steeltoe.Common.Logging.IBootstrapLoggerFactory +Steeltoe.Common.Logging.IBootstrapLoggerFactory.Update(Microsoft.Extensions.Configuration.IConfiguration! configuration) -> void +Steeltoe.Common.Logging.IBootstrapLoggerFactory.Update(Microsoft.Extensions.Logging.ILoggerFactory! loggerFactory) -> void diff --git a/src/Common/src/Net/NativeMethods.cs b/src/Common/src/Net/NativeMethods.cs index 1bfec593a7..2c8cc0d9f8 100644 --- a/src/Common/src/Net/NativeMethods.cs +++ b/src/Common/src/Net/NativeMethods.cs @@ -4,6 +4,8 @@ using System.Runtime.InteropServices; +#pragma warning disable SA1401 // Fields should be private + namespace Steeltoe.Common.Net; internal static class NativeMethods diff --git a/src/Common/src/Net/PublicAPI.Shipped.txt b/src/Common/src/Net/PublicAPI.Shipped.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Common/src/Net/PublicAPI.Unshipped.txt b/src/Common/src/Net/PublicAPI.Unshipped.txt new file mode 100644 index 0000000000..387e5879d1 --- /dev/null +++ b/src/Common/src/Net/PublicAPI.Unshipped.txt @@ -0,0 +1,4 @@ +#nullable enable +Steeltoe.Common.Net.WindowsNetworkFileShare +Steeltoe.Common.Net.WindowsNetworkFileShare.Dispose() -> void +Steeltoe.Common.Net.WindowsNetworkFileShare.WindowsNetworkFileShare(string! networkName, System.Net.NetworkCredential! credentials) -> void From 03d3ecee6f9d58260a16d792a88efa914723170c Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Wed, 14 Aug 2024 17:07:18 +0200 Subject: [PATCH 24/30] Add tests for HostBuilderWrapper --- .../Hosting.Test/HostBuilderWrapperTest.cs | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 src/Common/test/Hosting.Test/HostBuilderWrapperTest.cs diff --git a/src/Common/test/Hosting.Test/HostBuilderWrapperTest.cs b/src/Common/test/Hosting.Test/HostBuilderWrapperTest.cs new file mode 100644 index 0000000000..feab472810 --- /dev/null +++ b/src/Common/test/Hosting.Test/HostBuilderWrapperTest.cs @@ -0,0 +1,130 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Steeltoe.Common.TestResources; + +namespace Steeltoe.Common.Hosting.Test; + +public sealed class HostBuilderWrapperTest +{ + [Fact] + public void WebApplicationBuilder_Wraps() + { + var appSettings = new Dictionary + { + ["foo"] = "bar" + }; + + var capturingLoggerProvider = new CapturingLoggerProvider(category => category.StartsWith("Test", StringComparison.Ordinal)); + + WebApplicationBuilder builder = WebApplication.CreateBuilder(); + builder.WebHost.UseDefaultServiceProvider(options => options.ValidateScopes = true); + + HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); + wrapper.ConfigureServices(services => services.AddSingleton()); + wrapper.ConfigureAppConfiguration(configurationBuilder => configurationBuilder.AddInMemoryCollection(appSettings)); + wrapper.ConfigureLogging(loggingBuilder => loggingBuilder.AddProvider(capturingLoggerProvider)); + wrapper.ConfigureWebHost(hostBuilder => hostBuilder.UseUrls("http://*:8888")); + wrapper.ConfigureServices((contextWrapper, _) => contextWrapper.HostEnvironment.ApplicationName = "TestApp"); + + WebApplication app = builder.Build(); + + app.Services.GetService().Should().NotBeNull(); + app.Configuration.GetValue("foo").Should().Be("bar"); + + var loggerFactory = app.Services.GetRequiredService(); + ILogger logger = loggerFactory.CreateLogger("Test"); + + logger.LogInformation("LogLine"); + capturingLoggerProvider.GetAll().Should().Contain("INFO Test: LogLine"); + + app.Configuration.GetValue("urls").Should().Be("http://*:8888"); + + app.Environment.ApplicationName.Should().Be("TestApp"); + } + + [Fact] + public void WebHostBuilder_Wraps() + { + var appSettings = new Dictionary + { + ["foo"] = "bar" + }; + + var capturingLoggerProvider = new CapturingLoggerProvider(category => category.StartsWith("Test", StringComparison.Ordinal)); + + IWebHostBuilder builder = new WebHostBuilder().Configure(HostingHelpers.EmptyAction); + builder.UseDefaultServiceProvider(options => options.ValidateScopes = true); + + HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); + wrapper.ConfigureServices(services => services.AddSingleton()); + wrapper.ConfigureAppConfiguration(configurationBuilder => configurationBuilder.AddInMemoryCollection(appSettings)); + wrapper.ConfigureLogging(loggingBuilder => loggingBuilder.AddProvider(capturingLoggerProvider)); + wrapper.ConfigureWebHost(hostBuilder => hostBuilder.UseUrls("http://*:8888")); + wrapper.ConfigureServices((contextWrapper, _) => contextWrapper.HostEnvironment.ApplicationName = "TestApp"); + + IWebHost app = builder.Build(); + + app.Services.GetService().Should().NotBeNull(); + var configuration = app.Services.GetRequiredService(); + configuration.GetValue("foo").Should().Be("bar"); + + var loggerFactory = app.Services.GetRequiredService(); + ILogger logger = loggerFactory.CreateLogger("Test"); + + logger.LogInformation("LogLine"); + capturingLoggerProvider.GetAll().Should().Contain("INFO Test: LogLine"); + + configuration.GetValue("urls").Should().Be("http://*:8888"); + + var webHostEnvironment = app.Services.GetRequiredService(); + webHostEnvironment.ApplicationName.Should().Be("TestApp"); + } + + [Fact] + public void GenericHostBuilder_Wraps() + { + var appSettings = new Dictionary + { + ["foo"] = "bar" + }; + + var capturingLoggerProvider = new CapturingLoggerProvider(category => category.StartsWith("Test", StringComparison.Ordinal)); + + IHostBuilder builder = new HostBuilder(); + builder.UseDefaultServiceProvider(options => options.ValidateScopes = true); + + HostBuilderWrapper wrapper = HostBuilderWrapper.Wrap(builder); + wrapper.ConfigureServices(services => services.AddSingleton()); + wrapper.ConfigureAppConfiguration(configurationBuilder => configurationBuilder.AddInMemoryCollection(appSettings)); + wrapper.ConfigureLogging(loggingBuilder => loggingBuilder.AddProvider(capturingLoggerProvider)); + wrapper.ConfigureWebHost(hostBuilder => hostBuilder.UseUrls("http://*:8888")); + wrapper.ConfigureServices((contextWrapper, _) => contextWrapper.HostEnvironment.ApplicationName = "TestApp"); + + IHost app = builder.Build(); + + app.Services.GetService().Should().NotBeNull(); + var configuration = app.Services.GetRequiredService(); + configuration.GetValue("foo").Should().Be("bar"); + + var loggerFactory = app.Services.GetRequiredService(); + ILogger logger = loggerFactory.CreateLogger("Test"); + + logger.LogInformation("LogLine"); + capturingLoggerProvider.GetAll().Should().Contain("INFO Test: LogLine"); + + configuration.GetValue("urls").Should().Be("http://*:8888"); + + var hostEnvironment = app.Services.GetRequiredService(); + hostEnvironment.ApplicationName.Should().Be("TestApp"); + } + + private sealed class InjectableType; +} From 7be15fc486383fa7770bb9781283bc2eccee92ce Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Wed, 14 Aug 2024 17:12:19 +0200 Subject: [PATCH 25/30] Rename test classes to singular form --- ...LoggerFactoryTests.cs => BootstrapperLoggerFactoryTest.cs} | 2 +- .../{AesTextDecryptorTests.cs => AesTextDecryptorTest.cs} | 2 +- ...igurationTests.cs => HostedSpringBootConfigurationTest.cs} | 2 +- ...eDetectionTests.cs => ConfigurationChangeDetectionTest.cs} | 2 +- .../{CosmosDbConnectorTests.cs => CosmosDbConnectorTest.cs} | 2 +- ...gBuilderTests.cs => MongoDbConnectionStringBuilderTest.cs} | 2 +- .../{MongoDbConnectorTests.cs => MongoDbConnectorTest.cs} | 2 +- .../{MySqlConnectorTests.cs => MySqlConnectorTest.cs} | 2 +- .../Oracle/{MySqlConnectorTests.cs => MySqlConnectorTest.cs} | 2 +- ...PostgreSqlConnectorTests.cs => PostgreSqlConnectorTest.cs} | 2 +- ...BuilderTests.cs => RabbitMQConnectionStringBuilderTest.cs} | 2 +- .../{RabbitMQConnectorTests.cs => RabbitMQConnectorTest.cs} | 2 +- ...ingBuilderTests.cs => RedisConnectionStringBuilderTest.cs} | 2 +- .../Redis/{RedisConnectorTests.cs => RedisConnectorTest.cs} | 2 +- .../{SqlServerConnectorTests.cs => SqlServerConnectorTest.cs} | 2 +- .../{SqlServerConnectorTests.cs => SqlServerConnectorTest.cs} | 2 +- .../Discovery/{TtlSchedulerTests.cs => TtlSchedulerTest.cs} | 2 +- .../Eureka.Test/{CloudFoundryTests.cs => CloudFoundryTest.cs} | 2 +- .../{ContentNegotiationTests.cs => ContentNegotiationTest.cs} | 2 +- ...MigrationsEndpointTests.cs => DbMigrationsEndpointTest.cs} | 4 ++-- .../Prometheus.Test/{PrometheusTests.cs => PrometheusTest.cs} | 2 +- .../{WavefrontMetricsTests.cs => WavefrontMetricsTest.cs} | 2 +- 22 files changed, 23 insertions(+), 23 deletions(-) rename src/Common/test/Logging.Test/{BootstrapperLoggerFactoryTests.cs => BootstrapperLoggerFactoryTest.cs} (98%) rename src/Configuration/test/Encryption.Test/Decryption/{AesTextDecryptorTests.cs => AesTextDecryptorTest.cs} (97%) rename src/Configuration/test/SpringBoot.Test/{HostedSpringBootConfigurationTests.cs => HostedSpringBootConfigurationTest.cs} (99%) rename src/Connectors/test/Connectors.Test/{ConfigurationChangeDetectionTests.cs => ConfigurationChangeDetectionTest.cs} (99%) rename src/Connectors/test/Connectors.Test/CosmosDb/{CosmosDbConnectorTests.cs => CosmosDbConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/MongoDb/{MongoDbConnectionStringBuilderTests.cs => MongoDbConnectionStringBuilderTest.cs} (98%) rename src/Connectors/test/Connectors.Test/MongoDb/{MongoDbConnectorTests.cs => MongoDbConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/MySql/MySqlConnector/{MySqlConnectorTests.cs => MySqlConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/MySql/Oracle/{MySqlConnectorTests.cs => MySqlConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/PostgreSql/{PostgreSqlConnectorTests.cs => PostgreSqlConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/RabbitMQ/{RabbitMQConnectionStringBuilderTests.cs => RabbitMQConnectionStringBuilderTest.cs} (97%) rename src/Connectors/test/Connectors.Test/RabbitMQ/{RabbitMQConnectorTests.cs => RabbitMQConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/Redis/{RedisConnectionStringBuilderTests.cs => RedisConnectionStringBuilderTest.cs} (97%) rename src/Connectors/test/Connectors.Test/Redis/{RedisConnectorTests.cs => RedisConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/SqlServer/MicrosoftData/{SqlServerConnectorTests.cs => SqlServerConnectorTest.cs} (99%) rename src/Connectors/test/Connectors.Test/SqlServer/SystemData/{SqlServerConnectorTests.cs => SqlServerConnectorTest.cs} (99%) rename src/Discovery/test/Consul.Test/Discovery/{TtlSchedulerTests.cs => TtlSchedulerTest.cs} (99%) rename src/Discovery/test/Eureka.Test/{CloudFoundryTests.cs => CloudFoundryTest.cs} (99%) rename src/Management/test/Endpoint.Test/ContentNegotiation/{ContentNegotiationTests.cs => ContentNegotiationTest.cs} (99%) rename src/Management/test/Endpoint.Test/DbMigrations/{DbMigrationsEndpointTests.cs => DbMigrationsEndpointTest.cs} (97%) rename src/Management/test/Prometheus.Test/{PrometheusTests.cs => PrometheusTest.cs} (95%) rename src/Management/test/Wavefront.Test/{WavefrontMetricsTests.cs => WavefrontMetricsTest.cs} (99%) diff --git a/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTests.cs b/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTest.cs similarity index 98% rename from src/Common/test/Logging.Test/BootstrapperLoggerFactoryTests.cs rename to src/Common/test/Logging.Test/BootstrapperLoggerFactoryTest.cs index 7b4be9bedc..4e40a0ad7b 100644 --- a/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTests.cs +++ b/src/Common/test/Logging.Test/BootstrapperLoggerFactoryTest.cs @@ -9,7 +9,7 @@ namespace Steeltoe.Common.Logging.Test; -public sealed class BootstrapperLoggerFactoryTests +public sealed class BootstrapperLoggerFactoryTest { [Fact] public void BootstrapLoggerFactory_CorrectTypeResolved() diff --git a/src/Configuration/test/Encryption.Test/Decryption/AesTextDecryptorTests.cs b/src/Configuration/test/Encryption.Test/Decryption/AesTextDecryptorTest.cs similarity index 97% rename from src/Configuration/test/Encryption.Test/Decryption/AesTextDecryptorTests.cs rename to src/Configuration/test/Encryption.Test/Decryption/AesTextDecryptorTest.cs index d690a836bf..98a6506926 100644 --- a/src/Configuration/test/Encryption.Test/Decryption/AesTextDecryptorTests.cs +++ b/src/Configuration/test/Encryption.Test/Decryption/AesTextDecryptorTest.cs @@ -6,7 +6,7 @@ namespace Steeltoe.Configuration.Encryption.Test.Decryption; -public sealed class AesTextDecryptorTests +public sealed class AesTextDecryptorTest { [Theory] [MemberData(nameof(GetTestVector), 4)] diff --git a/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTests.cs b/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTest.cs similarity index 99% rename from src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTests.cs rename to src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTest.cs index 634aa7f210..b334870198 100644 --- a/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTests.cs +++ b/src/Configuration/test/SpringBoot.Test/HostedSpringBootConfigurationTest.cs @@ -14,7 +14,7 @@ namespace Steeltoe.Configuration.SpringBoot.Test; -public sealed class HostedSpringBootConfigurationTests +public sealed class HostedSpringBootConfigurationTest { [Fact] public void WebHostConfiguresIConfiguration_Spring_Application_Json() diff --git a/src/Connectors/test/Connectors.Test/ConfigurationChangeDetectionTests.cs b/src/Connectors/test/Connectors.Test/ConfigurationChangeDetectionTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/ConfigurationChangeDetectionTests.cs rename to src/Connectors/test/Connectors.Test/ConfigurationChangeDetectionTest.cs index 7fb817730f..d93b2fcd5b 100644 --- a/src/Connectors/test/Connectors.Test/ConfigurationChangeDetectionTests.cs +++ b/src/Connectors/test/Connectors.Test/ConfigurationChangeDetectionTest.cs @@ -13,7 +13,7 @@ namespace Steeltoe.Connectors.Test; -public sealed class ConfigurationChangeDetectionTests +public sealed class ConfigurationChangeDetectionTest { [Fact] public async Task Applies_local_configuration_changes_using_WebApplicationBuilder() diff --git a/src/Connectors/test/Connectors.Test/CosmosDb/CosmosDbConnectorTests.cs b/src/Connectors/test/Connectors.Test/CosmosDb/CosmosDbConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/CosmosDb/CosmosDbConnectorTests.cs rename to src/Connectors/test/Connectors.Test/CosmosDb/CosmosDbConnectorTest.cs index f0bcea7053..5bb1fdd107 100644 --- a/src/Connectors/test/Connectors.Test/CosmosDb/CosmosDbConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/CosmosDb/CosmosDbConnectorTest.cs @@ -14,7 +14,7 @@ namespace Steeltoe.Connectors.Test.CosmosDb; -public sealed class CosmosDbConnectorTests +public sealed class CosmosDbConnectorTest { private const string MultiVcapServicesJson = @"{ ""csb-azure-cosmosdb-sql"": [ diff --git a/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectionStringBuilderTests.cs b/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectionStringBuilderTest.cs similarity index 98% rename from src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectionStringBuilderTests.cs rename to src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectionStringBuilderTest.cs index b63ee27ddc..40646b0560 100644 --- a/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectionStringBuilderTests.cs +++ b/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectionStringBuilderTest.cs @@ -6,7 +6,7 @@ namespace Steeltoe.Connectors.Test.MongoDb; -public sealed class MongoDbConnectionStringBuilderTests +public sealed class MongoDbConnectionStringBuilderTest { [Fact] public void Merges_properties_with_special_characters() diff --git a/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectorTests.cs b/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectorTests.cs rename to src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectorTest.cs index 388ba55cd1..bc10ca8fda 100644 --- a/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/MongoDb/MongoDbConnectorTest.cs @@ -15,7 +15,7 @@ namespace Steeltoe.Connectors.Test.MongoDb; -public sealed class MongoDbConnectorTests +public sealed class MongoDbConnectorTest { private const string MultiVcapServicesJson = @"{ ""csb-azure-mongodb"": [ diff --git a/src/Connectors/test/Connectors.Test/MySql/MySqlConnector/MySqlConnectorTests.cs b/src/Connectors/test/Connectors.Test/MySql/MySqlConnector/MySqlConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/MySql/MySqlConnector/MySqlConnectorTests.cs rename to src/Connectors/test/Connectors.Test/MySql/MySqlConnector/MySqlConnectorTest.cs index 53b7f5e39e..13f8236cd7 100644 --- a/src/Connectors/test/Connectors.Test/MySql/MySqlConnector/MySqlConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/MySql/MySqlConnector/MySqlConnectorTest.cs @@ -16,7 +16,7 @@ namespace Steeltoe.Connectors.Test.MySql.MySqlConnector; -public sealed class MySqlConnectorTests +public sealed class MySqlConnectorTest { private const string MultiVcapServicesJson = @"{ ""p.mysql"": [ diff --git a/src/Connectors/test/Connectors.Test/MySql/Oracle/MySqlConnectorTests.cs b/src/Connectors/test/Connectors.Test/MySql/Oracle/MySqlConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/MySql/Oracle/MySqlConnectorTests.cs rename to src/Connectors/test/Connectors.Test/MySql/Oracle/MySqlConnectorTest.cs index 5261fb7787..7a9c572313 100644 --- a/src/Connectors/test/Connectors.Test/MySql/Oracle/MySqlConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/MySql/Oracle/MySqlConnectorTest.cs @@ -16,7 +16,7 @@ namespace Steeltoe.Connectors.Test.MySql.Oracle; -public sealed class MySqlConnectorTests +public sealed class MySqlConnectorTest { private const string MultiVcapServicesJson = @"{ ""p.mysql"": [ diff --git a/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs b/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs rename to src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTest.cs index 46e68f360b..00cd0ea66c 100644 --- a/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/PostgreSql/PostgreSqlConnectorTest.cs @@ -16,7 +16,7 @@ namespace Steeltoe.Connectors.Test.PostgreSql; -public sealed class PostgreSqlConnectorTests +public sealed class PostgreSqlConnectorTest { private const string MultiVcapServicesJson = @"{ ""csb-azure-postgresql"": [ diff --git a/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectionStringBuilderTests.cs b/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectionStringBuilderTest.cs similarity index 97% rename from src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectionStringBuilderTests.cs rename to src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectionStringBuilderTest.cs index 67a5e3edaa..5635815efe 100644 --- a/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectionStringBuilderTests.cs +++ b/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectionStringBuilderTest.cs @@ -6,7 +6,7 @@ namespace Steeltoe.Connectors.Test.RabbitMQ; -public sealed class RabbitMQConnectionStringBuilderTests +public sealed class RabbitMQConnectionStringBuilderTest { [Fact] public void Merges_properties_with_special_characters() diff --git a/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectorTests.cs b/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectorTests.cs rename to src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectorTest.cs index 3ad7782953..35d39642be 100644 --- a/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/RabbitMQ/RabbitMQConnectorTest.cs @@ -16,7 +16,7 @@ namespace Steeltoe.Connectors.Test.RabbitMQ; -public sealed class RabbitMQConnectorTests +public sealed class RabbitMQConnectorTest { private const string MultiVcapServicesJson = @"{ ""p.rabbitmq"": [ diff --git a/src/Connectors/test/Connectors.Test/Redis/RedisConnectionStringBuilderTests.cs b/src/Connectors/test/Connectors.Test/Redis/RedisConnectionStringBuilderTest.cs similarity index 97% rename from src/Connectors/test/Connectors.Test/Redis/RedisConnectionStringBuilderTests.cs rename to src/Connectors/test/Connectors.Test/Redis/RedisConnectionStringBuilderTest.cs index 8a347d9fea..f901399c2e 100644 --- a/src/Connectors/test/Connectors.Test/Redis/RedisConnectionStringBuilderTests.cs +++ b/src/Connectors/test/Connectors.Test/Redis/RedisConnectionStringBuilderTest.cs @@ -6,7 +6,7 @@ namespace Steeltoe.Connectors.Test.Redis; -public sealed class RedisConnectionStringBuilderTests +public sealed class RedisConnectionStringBuilderTest { [Fact] public void Can_merge_properties() diff --git a/src/Connectors/test/Connectors.Test/Redis/RedisConnectorTests.cs b/src/Connectors/test/Connectors.Test/Redis/RedisConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/Redis/RedisConnectorTests.cs rename to src/Connectors/test/Connectors.Test/Redis/RedisConnectorTest.cs index 413f5d20ba..d4064c8253 100644 --- a/src/Connectors/test/Connectors.Test/Redis/RedisConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/Redis/RedisConnectorTest.cs @@ -19,7 +19,7 @@ namespace Steeltoe.Connectors.Test.Redis; -public sealed class RedisConnectorTests +public sealed class RedisConnectorTest { private const string MultiVcapServicesJson = @"{ ""p-redis"": [ diff --git a/src/Connectors/test/Connectors.Test/SqlServer/MicrosoftData/SqlServerConnectorTests.cs b/src/Connectors/test/Connectors.Test/SqlServer/MicrosoftData/SqlServerConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/SqlServer/MicrosoftData/SqlServerConnectorTests.cs rename to src/Connectors/test/Connectors.Test/SqlServer/MicrosoftData/SqlServerConnectorTest.cs index ec58475f4f..653289d414 100644 --- a/src/Connectors/test/Connectors.Test/SqlServer/MicrosoftData/SqlServerConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/SqlServer/MicrosoftData/SqlServerConnectorTest.cs @@ -15,7 +15,7 @@ namespace Steeltoe.Connectors.Test.SqlServer.MicrosoftData; -public sealed class SqlServerConnectorTests +public sealed class SqlServerConnectorTest { private const string MultiVcapServicesJson = @"{ ""csb-azure-mssql"": [ diff --git a/src/Connectors/test/Connectors.Test/SqlServer/SystemData/SqlServerConnectorTests.cs b/src/Connectors/test/Connectors.Test/SqlServer/SystemData/SqlServerConnectorTest.cs similarity index 99% rename from src/Connectors/test/Connectors.Test/SqlServer/SystemData/SqlServerConnectorTests.cs rename to src/Connectors/test/Connectors.Test/SqlServer/SystemData/SqlServerConnectorTest.cs index c61920e141..96165d0226 100644 --- a/src/Connectors/test/Connectors.Test/SqlServer/SystemData/SqlServerConnectorTests.cs +++ b/src/Connectors/test/Connectors.Test/SqlServer/SystemData/SqlServerConnectorTest.cs @@ -15,7 +15,7 @@ namespace Steeltoe.Connectors.Test.SqlServer.SystemData; -public sealed class SqlServerConnectorTests +public sealed class SqlServerConnectorTest { private const string MultiVcapServicesJson = @"{ ""csb-azure-mssql"": [ diff --git a/src/Discovery/test/Consul.Test/Discovery/TtlSchedulerTests.cs b/src/Discovery/test/Consul.Test/Discovery/TtlSchedulerTest.cs similarity index 99% rename from src/Discovery/test/Consul.Test/Discovery/TtlSchedulerTests.cs rename to src/Discovery/test/Consul.Test/Discovery/TtlSchedulerTest.cs index 1405b7ade3..10e6a84eb5 100644 --- a/src/Discovery/test/Consul.Test/Discovery/TtlSchedulerTests.cs +++ b/src/Discovery/test/Consul.Test/Discovery/TtlSchedulerTest.cs @@ -10,7 +10,7 @@ namespace Steeltoe.Discovery.Consul.Test.Discovery; -public sealed class TtlSchedulerTests +public sealed class TtlSchedulerTest { [Fact] public void Add_Throws_Invalid_InstanceId() diff --git a/src/Discovery/test/Eureka.Test/CloudFoundryTests.cs b/src/Discovery/test/Eureka.Test/CloudFoundryTest.cs similarity index 99% rename from src/Discovery/test/Eureka.Test/CloudFoundryTests.cs rename to src/Discovery/test/Eureka.Test/CloudFoundryTest.cs index 4ca16c430d..f55eb372a2 100644 --- a/src/Discovery/test/Eureka.Test/CloudFoundryTests.cs +++ b/src/Discovery/test/Eureka.Test/CloudFoundryTest.cs @@ -14,7 +14,7 @@ namespace Steeltoe.Discovery.Eureka.Test; -public sealed class CloudFoundryTests +public sealed class CloudFoundryTest { [Fact] public void NoVCAPEnvVariables_ConfiguresEurekaDiscovery_Correctly() diff --git a/src/Management/test/Endpoint.Test/ContentNegotiation/ContentNegotiationTests.cs b/src/Management/test/Endpoint.Test/ContentNegotiation/ContentNegotiationTest.cs similarity index 99% rename from src/Management/test/Endpoint.Test/ContentNegotiation/ContentNegotiationTests.cs rename to src/Management/test/Endpoint.Test/ContentNegotiation/ContentNegotiationTest.cs index afbbee8a23..a802270b92 100644 --- a/src/Management/test/Endpoint.Test/ContentNegotiation/ContentNegotiationTests.cs +++ b/src/Management/test/Endpoint.Test/ContentNegotiation/ContentNegotiationTest.cs @@ -11,7 +11,7 @@ namespace Steeltoe.Management.Endpoint.Test.ContentNegotiation; -public sealed class ContentNegotiationTests +public sealed class ContentNegotiationTest { private static readonly Dictionary AppSettings = new() { diff --git a/src/Management/test/Endpoint.Test/DbMigrations/DbMigrationsEndpointTests.cs b/src/Management/test/Endpoint.Test/DbMigrations/DbMigrationsEndpointTest.cs similarity index 97% rename from src/Management/test/Endpoint.Test/DbMigrations/DbMigrationsEndpointTests.cs rename to src/Management/test/Endpoint.Test/DbMigrations/DbMigrationsEndpointTest.cs index 3a956619c8..6f1131af0b 100644 --- a/src/Management/test/Endpoint.Test/DbMigrations/DbMigrationsEndpointTests.cs +++ b/src/Management/test/Endpoint.Test/DbMigrations/DbMigrationsEndpointTest.cs @@ -10,11 +10,11 @@ namespace Steeltoe.Management.Endpoint.Test.DbMigrations; -public sealed class DbMigrationsEndpointTests : BaseTest +public sealed class DbMigrationsEndpointTest : BaseTest { private readonly ITestOutputHelper _output; - public DbMigrationsEndpointTests(ITestOutputHelper output) + public DbMigrationsEndpointTest(ITestOutputHelper output) { _output = output; } diff --git a/src/Management/test/Prometheus.Test/PrometheusTests.cs b/src/Management/test/Prometheus.Test/PrometheusTest.cs similarity index 95% rename from src/Management/test/Prometheus.Test/PrometheusTests.cs rename to src/Management/test/Prometheus.Test/PrometheusTest.cs index ef7045914e..f664999b16 100644 --- a/src/Management/test/Prometheus.Test/PrometheusTests.cs +++ b/src/Management/test/Prometheus.Test/PrometheusTest.cs @@ -7,7 +7,7 @@ namespace Steeltoe.Management.Prometheus.Test; -public sealed class PrometheusTests +public sealed class PrometheusTest { [Fact] public void AddPrometheusActuator_SetsUpRequiredServices() diff --git a/src/Management/test/Wavefront.Test/WavefrontMetricsTests.cs b/src/Management/test/Wavefront.Test/WavefrontMetricsTest.cs similarity index 99% rename from src/Management/test/Wavefront.Test/WavefrontMetricsTests.cs rename to src/Management/test/Wavefront.Test/WavefrontMetricsTest.cs index ffab1eab2f..73158c7c58 100644 --- a/src/Management/test/Wavefront.Test/WavefrontMetricsTests.cs +++ b/src/Management/test/Wavefront.Test/WavefrontMetricsTest.cs @@ -18,7 +18,7 @@ namespace Steeltoe.Management.Wavefront.Test; -public sealed class WavefrontMetricsTests +public sealed class WavefrontMetricsTest { [Fact] public async Task AddWavefront_WebApplicationBuilder() From 9006cce273307e3df6c820e211feb43e6231c20a Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Wed, 14 Aug 2024 17:39:52 +0200 Subject: [PATCH 26/30] Fix errors in release build --- .../SnakeCaseAllCapsEnumMemberJsonConverter.cs | 2 ++ .../UpgradableBootstrapLoggerFactory.cs | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs b/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs index 582ce49144..618148a1ee 100644 --- a/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs +++ b/src/Common/src/Common/CasingConventions/SnakeCaseAllCapsEnumMemberJsonConverter.cs @@ -20,6 +20,8 @@ public sealed class SnakeCaseAllCapsEnumMemberJsonConverter : JsonConverterFacto /// public override bool CanConvert(Type typeToConvert) { + ArgumentNullException.ThrowIfNull(typeToConvert); + return typeToConvert.IsEnum; } diff --git a/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs b/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs index 2afb3a179a..d4f29fd32d 100644 --- a/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs +++ b/src/Common/src/Logging/UpgradableBootstrapLoggerFactory.cs @@ -78,7 +78,7 @@ public void Update(ILoggerFactory loggerFactory) foreach (BootstrapLoggerInstance logger in _loggersByCategoryName.Values) { - logger.Logger = _factoryInstance.CreateLogger(logger.Name); + logger.UpdateLogger(_factoryInstance.CreateLogger(logger.Name)); } } @@ -123,29 +123,35 @@ private static void DefaultConfigure(ILoggingBuilder builder, IConfiguration con private sealed class BootstrapLoggerInstance : ILogger { - public volatile ILogger Logger; + private volatile ILogger _logger; + public string Name { get; } public BootstrapLoggerInstance(ILogger logger, string name) { + _logger = logger; Name = name; - Logger = logger; + } + + public void UpdateLogger(ILogger logger) + { + _logger = logger; } public IDisposable? BeginScope(TState state) where TState : notnull { - return Logger.BeginScope(state); + return _logger.BeginScope(state); } public bool IsEnabled(LogLevel logLevel) { - return Logger.IsEnabled(logLevel); + return _logger.IsEnabled(logLevel); } public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { - Logger.Log(logLevel, eventId, state, exception, formatter); + _logger.Log(logLevel, eventId, state, exception, formatter); } } } From 290b91b528c281341f45ad715d96ea9b8aaecfbf Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Thu, 15 Aug 2024 07:08:43 +0200 Subject: [PATCH 27/30] Empty commit to trigger cibuild From e3442103c138108a530a3aa7acbca4e7cb9dda57 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Fri, 16 Aug 2024 07:58:39 +0200 Subject: [PATCH 28/30] Review feedback: pass Options.DefaultName --- .../ConfigServerConfigurationProvider.cs | 192 +++++++++--------- .../ConfigServerHealthContributor.cs | 4 +- ...rConfigurationBuilderExtensionsCoreTest.cs | 18 +- ...erverConfigurationBuilderExtensionsTest.cs | 24 +-- .../ConfigServerConfigurationProviderTest.cs | 4 +- 5 files changed, 122 insertions(+), 120 deletions(-) diff --git a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs index 8b89cfcc0f..cc8234ea2b 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs @@ -13,6 +13,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; using Steeltoe.Common.Configuration; using Steeltoe.Common.Discovery; using Steeltoe.Common.Extensions; @@ -61,7 +62,7 @@ internal sealed class ConfigServerConfigurationProvider : ConfigurationProvider, /// /// Gets the configuration settings the provider uses when accessing the server. /// - public ConfigServerClientOptions Options { get; } + public ConfigServerClientOptions ClientOptions { get; } /// /// Initializes a new instance of the class from a . @@ -77,10 +78,10 @@ public ConfigServerConfigurationProvider(ConfigServerConfigurationSource source, { } - internal ConfigServerConfigurationProvider(ConfigServerClientOptions options, IConfiguration? configuration, HttpClientHandler? httpClientHandler, + internal ConfigServerConfigurationProvider(ConfigServerClientOptions clientOptions, IConfiguration? configuration, HttpClientHandler? httpClientHandler, ILoggerFactory loggerFactory) { - ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(clientOptions); ArgumentNullException.ThrowIfNull(loggerFactory); _loggerFactory = loggerFactory; @@ -97,7 +98,7 @@ internal ConfigServerConfigurationProvider(ConfigServerClientOptions options, IC _hasConfiguration = false; } - Options = options; + ClientOptions = clientOptions; if (httpClientHandler == null) { @@ -114,28 +115,28 @@ internal ConfigServerConfigurationProvider(ConfigServerClientOptions options, IC private void OnSettingsChanged() { - TimeSpan existingPollingInterval = Options.PollingInterval; + TimeSpan existingPollingInterval = ClientOptions.PollingInterval; if (_hasConfiguration) { - ConfigurationSettingsHelper.Initialize(ConfigurationPrefix, Options, _configuration); + ConfigurationSettingsHelper.Initialize(ConfigurationPrefix, ClientOptions, _configuration); _configuration.GetReloadToken().RegisterChangeCallback(_ => OnSettingsChanged(), null); } - if (Options.PollingInterval == TimeSpan.Zero || !Options.Enabled) + if (ClientOptions.PollingInterval == TimeSpan.Zero || !ClientOptions.Enabled) { _refreshTimer?.Dispose(); _refreshTimer = null; } - else if (Options.Enabled) + else if (ClientOptions.Enabled) { if (_refreshTimer == null) { - _refreshTimer = new Timer(_ => DoPolledLoadAsync().GetAwaiter().GetResult(), null, TimeSpan.Zero, Options.PollingInterval); + _refreshTimer = new Timer(_ => DoPolledLoadAsync().GetAwaiter().GetResult(), null, TimeSpan.Zero, ClientOptions.PollingInterval); } - else if (existingPollingInterval != Options.PollingInterval) + else if (existingPollingInterval != ClientOptions.PollingInterval) { - _refreshTimer.Change(TimeSpan.Zero, Options.PollingInterval); + _refreshTimer.Change(TimeSpan.Zero, ClientOptions.PollingInterval); } } } @@ -156,7 +157,7 @@ private async Task DoPolledLoadAsync() } /// - /// Loads configuration data from the Spring Cloud Configuration Server as specified by the . + /// Loads configuration data from the Spring Cloud Configuration Server as specified by the . /// public override void Load() { @@ -165,7 +166,7 @@ public override void Load() internal async Task LoadInternalAsync(bool updateDictionary, CancellationToken cancellationToken) { - if (!Options.Enabled) + if (!ClientOptions.Enabled) { Logger.LogInformation("Config Server client disabled, did not fetch configuration!"); return null; @@ -173,19 +174,19 @@ public override void Load() if (IsDiscoveryFirstEnabled()) { - _configServerDiscoveryService ??= new ConfigServerDiscoveryService(_configuration, Options, _loggerFactory); + _configServerDiscoveryService ??= new ConfigServerDiscoveryService(_configuration, ClientOptions, _loggerFactory); await DiscoverServerInstancesAsync(_configServerDiscoveryService, cancellationToken); } // Adds client settings (e.g. spring:cloud:config:uri, etc.) to the Data dictionary AddConfigServerClientOptions(); - string logUri = string.Join(',', Options.GetUris().Select(uri => new Uri(uri).ToMaskedString())); + string logUri = string.Join(',', ClientOptions.GetUris().Select(uri => new Uri(uri).ToMaskedString())); - if (Options is { Retry.Enabled: true, FailFast: true }) + if (ClientOptions is { Retry.Enabled: true, FailFast: true }) { int attempts = 0; - int backOff = Options.Retry.InitialInterval; + int backOff = ClientOptions.Retry.InitialInterval; do { @@ -200,11 +201,11 @@ public override void Load() Logger.LogInformation(exception, "Failed fetching configuration from server at: {Uri}.", logUri); attempts++; - if (attempts < Options.Retry.MaxAttempts) + if (attempts < ClientOptions.Retry.MaxAttempts) { Thread.CurrentThread.Join(backOff); - int nextBackOff = (int)(backOff * Options.Retry.Multiplier); - backOff = Math.Min(nextBackOff, Options.Retry.MaxInterval); + int nextBackOff = (int)(backOff * ClientOptions.Retry.Multiplier); + backOff = Math.Min(nextBackOff, ClientOptions.Retry.MaxInterval); } else { @@ -224,7 +225,7 @@ public override void Load() Exception? error = null; // Get arrays of Config Server uris to check - IList uris = Options.GetUris(); + IList uris = ClientOptions.GetUris(); try { @@ -287,7 +288,7 @@ public override void Load() Logger.LogWarning(error, "Could not locate PropertySource"); - if (Options.FailFast) + if (ClientOptions.FailFast) { throw new ConfigServerException("Could not locate PropertySource, fail fast property is set, failing", error); } @@ -303,12 +304,12 @@ private static bool AreDictionariesEqual(IDictionary internal string[] GetLabels() { - if (string.IsNullOrWhiteSpace(Options.Label)) + if (string.IsNullOrWhiteSpace(ClientOptions.Label)) { return EmptyLabels; } - return Options.Label.Split(CommaDelimiter, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + return ClientOptions.Label.Split(CommaDelimiter, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); } private async Task DiscoverServerInstancesAsync(ConfigServerDiscoveryService configServerDiscoveryService, CancellationToken cancellationToken) @@ -317,7 +318,7 @@ private async Task DiscoverServerInstancesAsync(ConfigServerDiscoveryService con if (!instances.Any()) { - if (Options.FailFast) + if (ClientOptions.FailFast) { throw new ConfigServerException("Could not locate Config Server via discovery, are you missing a Discovery service assembly?"); } @@ -325,10 +326,10 @@ private async Task DiscoverServerInstancesAsync(ConfigServerDiscoveryService con return; } - UpdateSettingsFromDiscovery(instances, Options); + UpdateSettingsFromDiscovery(instances, ClientOptions); } - internal void UpdateSettingsFromDiscovery(IEnumerable instances, ConfigServerClientOptions options) + internal void UpdateSettingsFromDiscovery(IEnumerable instances, ConfigServerClientOptions clientOptions) { var endpoints = new StringBuilder(); @@ -343,8 +344,8 @@ internal void UpdateSettingsFromDiscovery(IEnumerable instance { metaData.TryGetValue("user", out string? username); username ??= "user"; - options.Username = username; - options.Password = password; + clientOptions.Username = username; + clientOptions.Password = password; } if (metaData.TryGetValue("configPath", out string? path) && path != null) @@ -365,7 +366,7 @@ internal void UpdateSettingsFromDiscovery(IEnumerable instance if (endpoints.Length > 0) { string uris = endpoints.ToString(0, endpoints.Length - 1); - options.Uri = uris; + clientOptions.Uri = uris; } } @@ -411,26 +412,27 @@ internal async Task GetRequestMessageAsync(Uri requestUri, C } else { - if (!string.IsNullOrEmpty(Options.AccessTokenUri)) + if (!string.IsNullOrEmpty(ClientOptions.AccessTokenUri)) { - using HttpClient httpClient = CreateHttpClient(Options); - var accessTokenUri = new Uri(Options.AccessTokenUri); + using HttpClient httpClient = CreateHttpClient(ClientOptions); + var accessTokenUri = new Uri(ClientOptions.AccessTokenUri); - string accessToken = await httpClient.GetAccessTokenAsync(accessTokenUri, Options.ClientId, Options.ClientSecret, cancellationToken); + string accessToken = + await httpClient.GetAccessTokenAsync(accessTokenUri, ClientOptions.ClientId, ClientOptions.ClientSecret, cancellationToken); Logger.LogDebug("Fetched access token from '{AccessTokenUri}'.", accessTokenUri.ToMaskedString()); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } } - if (!string.IsNullOrEmpty(Options.Token) && Options.Uri != null && !Options.IsMultiServerConfiguration) + if (!string.IsNullOrEmpty(ClientOptions.Token) && ClientOptions.Uri != null && !ClientOptions.IsMultiServerConfiguration) { - if (!Options.DisableTokenRenewal) + if (!ClientOptions.DisableTokenRenewal) { RenewToken(); } - requestMessage.Headers.Add(TokenHeader, Options.Token); + requestMessage.Headers.Add(TokenHeader, ClientOptions.Token); } return requestMessage; @@ -458,41 +460,38 @@ private void AddConfigServerClientOptions(IDictionary data) { ArgumentNullException.ThrowIfNull(data); - data["spring:cloud:config:enabled"] = Options.Enabled.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:failFast"] = Options.FailFast.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:env"] = Options.Environment; - data["spring:cloud:config:label"] = Options.Label; - data["spring:cloud:config:name"] = Options.Name; - data["spring:cloud:config:password"] = Options.Password; - data["spring:cloud:config:uri"] = Options.Uri; - data["spring:cloud:config:username"] = Options.Username; - data["spring:cloud:config:token"] = Options.Token; - data["spring:cloud:config:timeout"] = Options.Timeout.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:validate_certificates"] = Options.ValidateCertificates.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:retry:enabled"] = Options.Retry.Enabled.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:retry:maxAttempts"] = Options.Retry.MaxAttempts.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:retry:initialInterval"] = Options.Retry.InitialInterval.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:retry:maxInterval"] = Options.Retry.MaxInterval.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:retry:multiplier"] = Options.Retry.Multiplier.ToString(CultureInfo.InvariantCulture); - - data["spring:cloud:config:access_token_uri"] = Options.AccessTokenUri; - data["spring:cloud:config:client_secret"] = Options.ClientSecret; - data["spring:cloud:config:client_id"] = Options.ClientId; - data["spring:cloud:config:tokenTtl"] = Options.TokenTtl.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:tokenRenewRate"] = Options.TokenRenewRate.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:disableTokenRenewal"] = Options.DisableTokenRenewal.ToString(CultureInfo.InvariantCulture); - - data["spring:cloud:config:discovery:enabled"] = Options.Discovery.Enabled.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:discovery:serviceId"] = Options.Discovery.ServiceId?.ToString(CultureInfo.InvariantCulture); - - data["spring:cloud:config:health:enabled"] = Options.Health.Enabled.ToString(CultureInfo.InvariantCulture); - data["spring:cloud:config:health:timeToLive"] = Options.Health.TimeToLive.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:enabled"] = ClientOptions.Enabled.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:failFast"] = ClientOptions.FailFast.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:env"] = ClientOptions.Environment; + data["spring:cloud:config:label"] = ClientOptions.Label; + data["spring:cloud:config:name"] = ClientOptions.Name; + data["spring:cloud:config:password"] = ClientOptions.Password; + data["spring:cloud:config:uri"] = ClientOptions.Uri; + data["spring:cloud:config:username"] = ClientOptions.Username; + data["spring:cloud:config:token"] = ClientOptions.Token; + data["spring:cloud:config:timeout"] = ClientOptions.Timeout.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:validate_certificates"] = ClientOptions.ValidateCertificates.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:retry:enabled"] = ClientOptions.Retry.Enabled.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:retry:maxAttempts"] = ClientOptions.Retry.MaxAttempts.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:retry:initialInterval"] = ClientOptions.Retry.InitialInterval.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:retry:maxInterval"] = ClientOptions.Retry.MaxInterval.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:retry:multiplier"] = ClientOptions.Retry.Multiplier.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:access_token_uri"] = ClientOptions.AccessTokenUri; + data["spring:cloud:config:client_secret"] = ClientOptions.ClientSecret; + data["spring:cloud:config:client_id"] = ClientOptions.ClientId; + data["spring:cloud:config:tokenTtl"] = ClientOptions.TokenTtl.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:tokenRenewRate"] = ClientOptions.TokenRenewRate.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:disableTokenRenewal"] = ClientOptions.DisableTokenRenewal.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:discovery:enabled"] = ClientOptions.Discovery.Enabled.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:discovery:serviceId"] = ClientOptions.Discovery.ServiceId?.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:health:enabled"] = ClientOptions.Health.Enabled.ToString(CultureInfo.InvariantCulture); + data["spring:cloud:config:health:timeToLive"] = ClientOptions.Health.TimeToLive.ToString(CultureInfo.InvariantCulture); } internal async Task RemoteLoadAsync(IEnumerable requestUris, string? label, CancellationToken cancellationToken) { // Get client if not already set - using HttpClient httpClient = CreateHttpClient(Options); + using HttpClient httpClient = CreateHttpClient(ClientOptions); Exception? error = null; @@ -568,17 +567,17 @@ internal Uri BuildConfigServerUri(string serverUri, string? label) var uriBuilder = new UriBuilder(new Uri(serverUri)); - if (!string.IsNullOrEmpty(Options.Username)) + if (!string.IsNullOrEmpty(ClientOptions.Username)) { - uriBuilder.UserName = Options.Username; + uriBuilder.UserName = ClientOptions.Username; } - if (!string.IsNullOrEmpty(Options.Password)) + if (!string.IsNullOrEmpty(ClientOptions.Password)) { - uriBuilder.Password = Options.Password; + uriBuilder.Password = ClientOptions.Password; } - string pathSuffix = $"{Options.Name}/{Options.Environment}"; + string pathSuffix = $"{ClientOptions.Name}/{ClientOptions.Environment}"; if (!string.IsNullOrWhiteSpace(label)) { @@ -641,28 +640,29 @@ private void AddPropertySource(PropertySource? source, IDictionary RefreshVaultTokenAsync(CancellationToken.None).GetAwaiter().GetResult(), null, TimeSpan.FromMilliseconds(Options.TokenRenewRate), - TimeSpan.FromMilliseconds(Options.TokenRenewRate)); + _ = new Timer(_ => RefreshVaultTokenAsync(CancellationToken.None).GetAwaiter().GetResult(), null, + TimeSpan.FromMilliseconds(ClientOptions.TokenRenewRate), TimeSpan.FromMilliseconds(ClientOptions.TokenRenewRate)); } // fire and forget internal async Task RefreshVaultTokenAsync(CancellationToken cancellationToken) { - if (string.IsNullOrEmpty(Options.Token)) + if (string.IsNullOrEmpty(ClientOptions.Token)) { return; } - string obscuredToken = $"{Options.Token[..4]}[*]{Options.Token[^4..]}"; + string obscuredToken = $"{ClientOptions.Token[..4]}[*]{ClientOptions.Token[^4..]}"; try { - using HttpClient httpClient = CreateHttpClient(Options); + using HttpClient httpClient = CreateHttpClient(ClientOptions); Uri uri = GetVaultRenewUri(); HttpRequestMessage message = await GetVaultRenewRequestMessageAsync(uri, cancellationToken); - Logger.LogInformation("Renewing Vault token {Token} for {Ttl} milliseconds at Uri {Uri}", obscuredToken, Options.TokenTtl, uri.ToMaskedString()); + Logger.LogInformation("Renewing Vault token {Token} for {Ttl} milliseconds at Uri {Uri}", obscuredToken, ClientOptions.TokenTtl, + uri.ToMaskedString()); using HttpResponseMessage response = await httpClient.SendAsync(message, cancellationToken); @@ -679,7 +679,7 @@ internal async Task RefreshVaultTokenAsync(CancellationToken cancellationToken) private Uri GetVaultRenewUri() { - string baseUri = Options.Uri!.Split(',')[0].Trim(); + string baseUri = ClientOptions.Uri!.Split(',')[0].Trim(); if (!baseUri.EndsWith('/')) { @@ -694,23 +694,23 @@ private async Task GetVaultRenewRequestMessageAsync(Uri requ var uriWithoutUserInfo = new Uri(requestUri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.UriEscaped)); var requestMessage = new HttpRequestMessage(HttpMethod.Post, uriWithoutUserInfo); - if (!string.IsNullOrEmpty(Options.AccessTokenUri)) + if (!string.IsNullOrEmpty(ClientOptions.AccessTokenUri)) { - using HttpClient httpClient = CreateHttpClient(Options); - var accessTokenUri = new Uri(Options.AccessTokenUri); + using HttpClient httpClient = CreateHttpClient(ClientOptions); + var accessTokenUri = new Uri(ClientOptions.AccessTokenUri); - string accessToken = await httpClient.GetAccessTokenAsync(accessTokenUri, Options.ClientId, Options.ClientSecret, cancellationToken); + string accessToken = await httpClient.GetAccessTokenAsync(accessTokenUri, ClientOptions.ClientId, ClientOptions.ClientSecret, cancellationToken); Logger.LogDebug("Fetched access token from '{AccessTokenUri}'.", accessTokenUri.ToMaskedString()); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } - if (!string.IsNullOrEmpty(Options.Token)) + if (!string.IsNullOrEmpty(ClientOptions.Token)) { - requestMessage.Headers.Add(VaultTokenHeader, Options.Token); + requestMessage.Headers.Add(VaultTokenHeader, ClientOptions.Token); } - int renewTtlInSeconds = Options.TokenTtl / 1000; + int renewTtlInSeconds = ClientOptions.TokenTtl / 1000; string json = $"{{\"increment\":{renewTtlInSeconds}}}"; requestMessage.Content = new StringContent(json, Encoding.UTF8, "application/json"); @@ -720,33 +720,35 @@ private async Task GetVaultRenewRequestMessageAsync(Uri requ internal bool IsDiscoveryFirstEnabled() { IConfigurationSection clientConfigSection = _configuration.GetSection(ConfigurationPrefix); - return clientConfigSection.GetValue("discovery:enabled", Options.Discovery.Enabled); + return clientConfigSection.GetValue("discovery:enabled", ClientOptions.Discovery.Enabled); } /// /// Creates an appropriately configured HttpClient that can be used in communicating with the Spring Cloud Configuration Server. /// - /// + /// /// The settings used to configure the HttpClient. /// /// /// The HttpClient used by the provider. /// - internal HttpClient CreateHttpClient(ConfigServerClientOptions options) + internal HttpClient CreateHttpClient(ConfigServerClientOptions clientOptions) { - ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(clientOptions); ObjectDisposedException.ThrowIf(_httpClientHandler == null, this); - var clientCertificateConfigurer = new ClientCertificateHttpClientHandlerConfigurer(OptionsMonitorWrapper.Create(options.ClientCertificate)); + var clientCertificateConfigurer = new ClientCertificateHttpClientHandlerConfigurer(OptionsMonitorWrapper.Create(clientOptions.ClientCertificate)); clientCertificateConfigurer.Configure("ConfigServer", _httpClientHandler); - var validateCertificatesHandler = new ValidateCertificatesHttpClientHandlerConfigurer(OptionsMonitorWrapper.Create(options)); - validateCertificatesHandler.Configure(string.Empty, _httpClientHandler); + var validateCertificatesHandler = + new ValidateCertificatesHttpClientHandlerConfigurer(OptionsMonitorWrapper.Create(clientOptions)); + + validateCertificatesHandler.Configure(Options.DefaultName, _httpClientHandler); var httpClient = new HttpClient(_httpClientHandler, false); - httpClient.ConfigureForSteeltoe(options.HttpTimeout); + httpClient.ConfigureForSteeltoe(clientOptions.HttpTimeout); - foreach ((string headerName, string headerValue) in options.Headers) + foreach ((string headerName, string headerValue) in clientOptions.Headers) { httpClient.DefaultRequestHeaders.Add(headerName, headerValue); } diff --git a/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs b/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs index e52fb354f6..af55d840d6 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerHealthContributor.cs @@ -104,11 +104,11 @@ internal bool IsCacheStale(long accessTime) internal bool IsEnabled() { - return Provider is { Options.Health.Enabled: true }; + return Provider is { ClientOptions.Health.Enabled: true }; } internal long GetTimeToLive() { - return Provider != null ? Provider.Options.Health.TimeToLive : long.MaxValue; + return Provider != null ? Provider.ClientOptions.Health.TimeToLive : long.MaxValue; } } diff --git a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs index f7270ba3ee..b27daf0e2d 100644 --- a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs +++ b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsCoreTest.cs @@ -95,7 +95,7 @@ public void AddConfigServer_JsonAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -151,7 +151,7 @@ public void AddConfigServer_ValidateCertificates_DisablesCertValidation() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.ValidateCertificates); } @@ -187,7 +187,7 @@ public void AddConfigServer_Validate_Certificates_DisablesCertValidation() Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.ValidateCertificates); } @@ -227,7 +227,7 @@ public void AddConfigServer_XmlAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -271,7 +271,7 @@ public void AddConfigServer_IniAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -314,7 +314,7 @@ public void AddConfigServer_CommandLineAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -373,7 +373,7 @@ public void AddConfigServer_HandlesPlaceHolders() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -472,7 +472,7 @@ public void AddConfigServer_WithCloudfoundryEnvironment_ConfiguresClientCorrectl Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.True(options.Enabled); Assert.False(options.FailFast); Assert.Equal("https://config-ba6b6079-163b-45d2-8932-e2eca0d1e49a.wise.com", options.Uri); @@ -578,7 +578,7 @@ public void AddConfigServer_WithCloudfoundryEnvironmentSCS3_ConfiguresClientCorr Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.True(options.Enabled); Assert.False(options.FailFast); Assert.Equal("https://config-ba6b6079-163b-45d2-8932-e2eca0d1e49a.wise.com", options.Uri); diff --git a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsTest.cs b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsTest.cs index efb5da4e34..5fa75f2e68 100644 --- a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsTest.cs +++ b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationBuilderExtensionsTest.cs @@ -238,7 +238,7 @@ public void AddConfigServer_JsonAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -294,7 +294,7 @@ public void AddConfigServer_XmlAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().FirstOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -336,7 +336,7 @@ public void AddConfigServer_IniAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -375,7 +375,7 @@ public void AddConfigServer_CommandLineAppSettingsConfiguresClient() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -433,7 +433,7 @@ public void AddConfigServer_HandlesPlaceHolders() ConfigServerConfigurationProvider? configServerProvider = configurationRoot.Providers.OfType().SingleOrDefault(); Assert.NotNull(configServerProvider); - ConfigServerClientOptions options = configServerProvider.Options; + ConfigServerClientOptions options = configServerProvider.ClientOptions; Assert.False(options.Enabled); Assert.False(options.FailFast); @@ -474,8 +474,8 @@ public void AddConfigServer_VCAP_SERVICES_Override_Defaults(string vcapServices) Assert.NotNull(configServerProvider); Assert.IsType(configServerProvider); - Assert.NotEqual("https://uri-from-settings", configServerProvider.Options.Uri); - Assert.Equal("https://uri-from-vcap-services", configServerProvider.Options.Uri); + Assert.NotEqual("https://uri-from-settings", configServerProvider.ClientOptions.Uri); + Assert.Equal("https://uri-from-vcap-services", configServerProvider.ClientOptions.Uri); } [Fact] @@ -501,11 +501,11 @@ public void AddConfigServer_PaysAttentionToSettings() ConfigServerConfigurationProvider? provider = configurationRoot.Providers.OfType().FirstOrDefault(); Assert.NotNull(provider); - Assert.Equal("testConfigLabel", provider.Options.Label); - Assert.Equal("testConfigName", provider.Options.Name); - Assert.Equal("testEnv", provider.Options.Environment); - Assert.Equal("testUser", provider.Options.Username); - Assert.Equal("testPassword", provider.Options.Password); + Assert.Equal("testConfigLabel", provider.ClientOptions.Label); + Assert.Equal("testConfigName", provider.ClientOptions.Name); + Assert.Equal("testEnv", provider.ClientOptions.Environment); + Assert.Equal("testUser", provider.ClientOptions.Username); + Assert.Equal("testPassword", provider.ClientOptions.Password); } [Fact] diff --git a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationProviderTest.cs b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationProviderTest.cs index 9b3f1579d7..da00a71295 100644 --- a/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationProviderTest.cs +++ b/src/Configuration/test/ConfigServer.Test/ConfigServerConfigurationProviderTest.cs @@ -42,7 +42,7 @@ public void DefaultConstructor_InitializedWithDefaultSettings() var options = new ConfigServerClientOptions(); using var provider = new ConfigServerConfigurationProvider(options, null, null, NullLoggerFactory.Instance); - TestHelper.VerifyDefaults(provider.Options); + TestHelper.VerifyDefaults(provider.ClientOptions); } [Fact] @@ -53,7 +53,7 @@ public void SourceConstructor_WithDefaults_InitializesWithDefaultSettings() var source = new ConfigServerConfigurationSource(options, configuration, NullLoggerFactory.Instance); using var provider = new ConfigServerConfigurationProvider(source, NullLoggerFactory.Instance); - TestHelper.VerifyDefaults(provider.Options); + TestHelper.VerifyDefaults(provider.ClientOptions); } [Fact] From 3aefd43cb62a08881c53ca9d1a550c232de01289 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Fri, 16 Aug 2024 07:59:20 +0200 Subject: [PATCH 29/30] Review feedback: rename variable --- .../CloudFoundryServiceCollectionExtensionsTest.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs b/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs index 0f433e70d5..96d35f81bc 100644 --- a/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs +++ b/src/Configuration/test/CloudFoundry.Test/CloudFoundryServiceCollectionExtensionsTest.cs @@ -37,10 +37,10 @@ public void ConfigureCloudFoundryOptions_ConfiguresCloudFoundryOptions() } """); - IConfiguration configurationRoot = new ConfigurationBuilder().AddCloudFoundry().Build(); + IConfiguration configuration = new ConfigurationBuilder().AddCloudFoundry().Build(); var services = new ServiceCollection(); - services.AddSingleton(configurationRoot); + services.AddSingleton(configuration); services.AddCloudFoundryOptions(); ServiceProvider serviceProvider = services.BuildServiceProvider(true); From 1d8325273c171f7ac04158a98e3bd83dbfa450b4 Mon Sep 17 00:00:00 2001 From: Bart Koelman <104792814+bart-vmware@users.noreply.github.com> Date: Fri, 16 Aug 2024 08:36:26 +0200 Subject: [PATCH 30/30] Review feedback: Pass logger through --- .../ConfigurationValuesHelper.cs | 30 ++- .../PropertyPlaceHolderHelper.cs | 53 +++--- .../ConfigurationValuesHelperTest.cs | 61 +++++-- .../PropertyPlaceholderHelperTest.cs | 171 +++++++++++------- .../ConfigServerConfigurationProvider.cs | 5 +- .../ConfigurationSettingsHelper.cs | 38 ++-- .../PlaceholderResolverProvider.cs | 9 +- ...tedPlaceholderEncryptionIntegrationTest.cs | 24 +-- .../ConfigurationSettingsHelperTest.cs | 5 +- ...CollectionForConfigServerExtensionsTest.cs | 14 +- .../EncryptionConfigurationExtensionsTest.cs | 28 +-- ...cryptionServiceCollectionExtensionsTest.cs | 16 +- .../PlaceholderConfigurationExtensionsTest.cs | 18 +- .../PlaceholderResolverExtensionsTest.cs | 20 +- 14 files changed, 291 insertions(+), 201 deletions(-) diff --git a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs index 2daaf2f0ad..75da81fffe 100644 --- a/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs +++ b/src/Common/src/Common/Configuration/ConfigurationValuesHelper.cs @@ -4,13 +4,23 @@ using System.Globalization; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging; namespace Steeltoe.Common.Configuration; -internal static class ConfigurationValuesHelper +internal sealed class ConfigurationValuesHelper { - public static string? GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration? resolve, string? defaultValue) + private readonly PropertyPlaceholderHelper _propertyPlaceholderHelper; + + public ConfigurationValuesHelper(ILoggerFactory loggerFactory) + { + ArgumentNullException.ThrowIfNull(loggerFactory); + + ILogger placeholderHelperLogger = loggerFactory.CreateLogger(); + _propertyPlaceholderHelper = new PropertyPlaceholderHelper(placeholderHelperLogger); + } + + public string? GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration? resolve, string? defaultValue) { // First check for key in primary string? setting = GetString(key, primary, resolve, null); @@ -49,7 +59,7 @@ internal static class ConfigurationValuesHelper /// /// The value from configuration, or the default value if not found. /// - public static string? GetSetting(string key, IConfiguration configuration, string? defaultValue, params string[] sectionPrefixes) + public string? GetSetting(string key, IConfiguration configuration, string? defaultValue, params string[] sectionPrefixes) { ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(configuration); @@ -85,7 +95,7 @@ internal static class ConfigurationValuesHelper /// /// The value from configuration, or the default value if not found. /// - public static string? GetPreferredSetting(IConfiguration configuration, string? defaultValue, params string?[] configurationKeys) + public string? GetPreferredSetting(IConfiguration configuration, string? defaultValue, params string?[] configurationKeys) { ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(configurationKeys); @@ -103,7 +113,7 @@ internal static class ConfigurationValuesHelper return defaultValue; } - public static int GetInt32(string key, IConfiguration configuration, IConfiguration? resolve, int defaultValue) + public int GetInt32(string key, IConfiguration configuration, IConfiguration? resolve, int defaultValue) { ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(configuration); @@ -118,7 +128,7 @@ public static int GetInt32(string key, IConfiguration configuration, IConfigurat return defaultValue; } - public static double GetDouble(string key, IConfiguration configuration, IConfiguration? resolve, double defaultValue) + public double GetDouble(string key, IConfiguration configuration, IConfiguration? resolve, double defaultValue) { ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(configuration); @@ -134,7 +144,7 @@ public static double GetDouble(string key, IConfiguration configuration, IConfig return defaultValue; } - public static bool GetBoolean(string key, IConfiguration configuration, IConfiguration? resolve, bool defaultValue) + public bool GetBoolean(string key, IConfiguration configuration, IConfiguration? resolve, bool defaultValue) { ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(configuration); @@ -149,7 +159,7 @@ public static bool GetBoolean(string key, IConfiguration configuration, IConfigu return defaultValue; } - public static string? GetString(string key, IConfiguration configuration, IConfiguration? resolve, string? defaultValue) + public string? GetString(string key, IConfiguration configuration, IConfiguration? resolve, string? defaultValue) { ArgumentException.ThrowIfNullOrEmpty(key); ArgumentNullException.ThrowIfNull(configuration); @@ -158,7 +168,7 @@ public static bool GetBoolean(string key, IConfiguration configuration, IConfigu if (!string.IsNullOrEmpty(value)) { - return PropertyPlaceholderHelper.ResolvePlaceholders(value, resolve, NullLogger.Instance); + return _propertyPlaceholderHelper.ResolvePlaceholders(value, resolve); } return defaultValue; diff --git a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs index 99e5060dae..5cabf206cc 100644 --- a/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs +++ b/src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs @@ -6,7 +6,6 @@ using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; namespace Steeltoe.Common.Configuration; @@ -23,12 +22,20 @@ namespace Steeltoe.Common.Configuration; /// . /// /// -internal static class PropertyPlaceholderHelper +internal sealed class PropertyPlaceholderHelper { private const string Prefix = "${"; private const string Suffix = "}"; private const string SimplePrefix = "{"; private const string Separator = "?"; + private readonly ILogger _logger; + + public PropertyPlaceholderHelper(ILogger logger) + { + ArgumentNullException.ThrowIfNull(logger); + + _logger = logger; + } /// /// Replaces all placeholders of the form: /// The configuration used for finding replacement values. /// - /// - /// Used for internal logging. Pass to disable logging. - /// /// /// The supplied value, with the placeholders replaced inline. /// - public static string? ResolvePlaceholders(string? property, IConfiguration? configuration, ILogger logger) + public string? ResolvePlaceholders(string? property, IConfiguration? configuration) { - ArgumentNullException.ThrowIfNull(logger); - - return ParseStringValue(property, configuration, false, new HashSet(), logger); + return ParseStringValue(property, configuration, false, new HashSet()); } /// @@ -64,16 +66,12 @@ internal static class PropertyPlaceholderHelper /// /// The configuration to use as both source and target for placeholder resolution. /// - /// - /// Used for internal logging. Pass to disable logging. - /// /// /// A list of keys with resolved values. Add them to your with method 'AddInMemoryCollection'. /// - public static IDictionary GetResolvedConfigurationPlaceholders(IConfiguration configuration, ILogger logger) + public IDictionary GetResolvedConfigurationPlaceholders(IConfiguration configuration) { ArgumentNullException.ThrowIfNull(configuration); - ArgumentNullException.ThrowIfNull(logger); // setup a holding tank for resolved values var resolvedValues = new Dictionary(); @@ -83,16 +81,15 @@ internal static class PropertyPlaceholderHelper foreach ((string key, string? value) in configuration.AsEnumerable().Where(pair => pair.Value != null && pair.Value.Contains(Prefix, StringComparison.Ordinal) && pair.Value.Contains(Suffix, StringComparison.Ordinal))) { - logger.LogTrace("Found a property placeholder '{Placeholder}' to resolve for key '{Key}", value, key); - resolvedValues.Add(key, ParseStringValue(value, configuration, true, visitedPlaceholders, logger)); + _logger.LogTrace("Found a property placeholder '{Placeholder}' to resolve for key '{Key}", value, key); + resolvedValues.Add(key, ParseStringValue(value, configuration, true, visitedPlaceholders)); } return resolvedValues; } [return: NotNullIfNotNull(nameof(property))] - private static string? ParseStringValue(string? property, IConfiguration? configuration, bool useEmptyStringIfNotFound, ISet visitedPlaceHolders, - ILogger logger) + private string? ParseStringValue(string? property, IConfiguration? configuration, bool useEmptyStringIfNotFound, ISet visitedPlaceHolders) { if (configuration == null) { @@ -119,7 +116,7 @@ internal static class PropertyPlaceholderHelper if (endIndex != -1) { - string placeholder = result.Substring(startIndex + Prefix.Length, endIndex); + string placeholder = Substring(result, startIndex + Prefix.Length, endIndex); string originalPlaceholder = placeholder; @@ -129,7 +126,7 @@ internal static class PropertyPlaceholderHelper } // Recursive invocation, parsing placeholders contained in the placeholder key. - placeholder = ParseStringValue(placeholder, configuration, useEmptyStringIfNotFound, visitedPlaceHolders, logger); + placeholder = ParseStringValue(placeholder, configuration, useEmptyStringIfNotFound, visitedPlaceHolders); // Handle array references foo:bar[1]:baz format -> foo:bar:1:baz string lookup = placeholder.Replace('[', ':').Replace("]", string.Empty, StringComparison.Ordinal); @@ -164,15 +161,15 @@ internal static class PropertyPlaceholderHelper if (propertyValue != null) { // Recursive invocation, parsing placeholders contained in these previously resolved placeholder value. - propertyValue = ParseStringValue(propertyValue, configuration, useEmptyStringIfNotFound, visitedPlaceHolders, logger); - result.Replace(startIndex, endIndex + Suffix.Length, propertyValue); - logger.LogDebug("Resolved placeholder '{Placeholder}'", placeholder); - startIndex = result.IndexOf(Prefix, startIndex + propertyValue.Length); + propertyValue = ParseStringValue(propertyValue, configuration, useEmptyStringIfNotFound, visitedPlaceHolders); + Replace(result, startIndex, endIndex + Suffix.Length, propertyValue); + _logger.LogDebug("Resolved placeholder '{Placeholder}'", placeholder); + startIndex = IndexOf(result, Prefix, startIndex + propertyValue.Length); } else { // Proceed with unprocessed value. - startIndex = result.IndexOf(Prefix, endIndex + Prefix.Length); + startIndex = IndexOf(result, Prefix, endIndex + Prefix.Length); } visitedPlaceHolders.Remove(originalPlaceholder); @@ -237,13 +234,13 @@ private static bool SubstringMatch(StringBuilder builder, int index, string subs return true; } - private static void Replace(this StringBuilder builder, int start, int end, string str) + private static void Replace(StringBuilder builder, int start, int end, string str) { builder.Remove(start, end - start); builder.Insert(start, str); } - private static int IndexOf(this StringBuilder builder, string str, int start) + private static int IndexOf(StringBuilder builder, string str, int start) { if (start >= builder.Length) { @@ -253,7 +250,7 @@ private static int IndexOf(this StringBuilder builder, string str, int start) return builder.ToString().IndexOf(str, start, StringComparison.Ordinal); } - private static string Substring(this StringBuilder builder, int start, int end) + private static string Substring(StringBuilder builder, int start, int end) { return builder.ToString().Substring(start, end - start); } diff --git a/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs b/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs index 8e24324a19..3a0d191e08 100644 --- a/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs +++ b/src/Common/test/Common.Test/Configuration/ConfigurationValuesHelperTest.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; using Steeltoe.Common.Configuration; namespace Steeltoe.Common.Test.Configuration; @@ -19,7 +20,9 @@ public void GetString_NoResolveFromConfig() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - string? result = ConfigurationValuesHelper.GetString("a:b", configuration, null, null); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + string? result = helper.GetString("a:b", configuration, null, null); Assert.Equal("astring", result); } @@ -33,7 +36,9 @@ public void GetInt32_ReturnsValue() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - int result = ConfigurationValuesHelper.GetInt32("a:b", configuration, null, 500); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + int result = helper.GetInt32("a:b", configuration, null, 500); Assert.Equal(100, result); } @@ -47,7 +52,9 @@ public void GetDouble_ReturnsValue() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - double result = ConfigurationValuesHelper.GetDouble("a:b", configuration, null, 500.00); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + double result = helper.GetDouble("a:b", configuration, null, 500.00); Assert.Equal(100.00, result); } @@ -61,7 +68,9 @@ public void GetBoolean_ReturnsValue() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - bool result = ConfigurationValuesHelper.GetBoolean("a:b", configuration, null, false); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + bool result = helper.GetBoolean("a:b", configuration, null, false); Assert.True(result); } @@ -75,7 +84,9 @@ public void GetInt_NotFoundReturnsDefault() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - int result = ConfigurationValuesHelper.GetInt32("a:b:c", configuration, null, 100); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + int result = helper.GetInt32("a:b:c", configuration, null, 100); Assert.Equal(100, result); } @@ -89,7 +100,9 @@ public void GetDouble_NotFoundReturnsDefault() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - double result = ConfigurationValuesHelper.GetDouble("a:b:c", configuration, null, 100.00); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + double result = helper.GetDouble("a:b:c", configuration, null, 100.00); Assert.Equal(100.00, result); } @@ -103,7 +116,9 @@ public void GetBoolean_NotFoundReturnsDefault() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - bool result = ConfigurationValuesHelper.GetBoolean("a:b:c", configuration, null, true); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + bool result = helper.GetBoolean("a:b:c", configuration, null, true); Assert.True(result); } @@ -117,7 +132,9 @@ public void GetString_NotFoundReturnsDefault() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build(); - string? result = ConfigurationValuesHelper.GetString("a:b:c", configuration, null, "foobar"); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + string? result = helper.GetString("a:b:c", configuration, null, "foobar"); Assert.Equal("foobar", result); } @@ -137,7 +154,9 @@ public void GetString_ResolvesReference() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string? result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, "foobar"); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + string? result = helper.GetString("a:b", configuration, resolve, "foobar"); Assert.Equal("astring", result); } @@ -157,7 +176,9 @@ public void GetString_ResolveNotFoundReturnsNotResolvedValue() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string? result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, null); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + string? result = helper.GetString("a:b", configuration, resolve, null); Assert.Equal("${a:b:c}", result); } @@ -177,7 +198,9 @@ public void GetString_ResolveNotFoundReturnsPlaceholderDefault() IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); IConfiguration resolve = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); - string? result = ConfigurationValuesHelper.GetString("a:b", configuration, resolve, "foobar"); + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); + + string? result = helper.GetString("a:b", configuration, resolve, "foobar"); Assert.Equal("placeholderdefault", result); } @@ -194,10 +217,12 @@ public void GetSetting_GetsFromFirst() { "a:b", "setting2" } }; - IConfiguration config1 = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); - IConfiguration config2 = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); + IConfiguration configuration1 = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); + IConfiguration configuration2 = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); + + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); - string? result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); + string? result = helper.GetSetting("a:b", configuration1, configuration2, null, "foobar"); Assert.Equal("setting1", result); } @@ -214,10 +239,12 @@ public void GetSetting_GetsFromSecond() { "a:b", "setting2" } }; - IConfiguration config1 = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); - IConfiguration config2 = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); + IConfiguration configuration1 = new ConfigurationBuilder().AddInMemoryCollection(settings1).Build(); + IConfiguration configuration2 = new ConfigurationBuilder().AddInMemoryCollection(settings2).Build(); + + var helper = new ConfigurationValuesHelper(NullLoggerFactory.Instance); - string? result = ConfigurationValuesHelper.GetSetting("a:b", config1, config2, null, "foobar"); + string? result = helper.GetSetting("a:b", configuration1, configuration2, null, "foobar"); Assert.Equal("setting2", result); } } diff --git a/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs b/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs index 58f2955258..e2c793088a 100644 --- a/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs +++ b/src/Common/test/Common.Test/Configuration/PropertyPlaceholderHelperTest.cs @@ -15,17 +15,19 @@ public sealed class PropertyPlaceholderHelperTest public void ResolvePlaceholders_ResolvesSinglePlaceholder() { const string text = "foo=${foo}"; - var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings = new Dictionary { { "foo", "bar" } }; - builder.AddInMemoryCollection(dic1); - IConfigurationRoot configurationRoot = builder.Build(); + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=bar", result); } @@ -33,17 +35,19 @@ public void ResolvePlaceholders_ResolvesSinglePlaceholder() public void ResolvePlaceholders_ResolvesSingleSpringPlaceholder() { const string text = "foo=${foo.bar}"; - var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings = new Dictionary { { "foo:bar", "bar" } }; - builder.AddInMemoryCollection(dic1); - IConfigurationRoot configurationRoot = builder.Build(); + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=bar", result); } @@ -51,17 +55,20 @@ public void ResolvePlaceholders_ResolvesSingleSpringPlaceholder() public void ResolvePlaceholders_ResolvesMultiplePlaceholders() { const string text = "foo=${foo},bar=${bar}"; - var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings = new Dictionary { { "foo", "bar" }, { "bar", "baz" } }; - builder.AddInMemoryCollection(dic1); + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build(), NullLogger.Instance); + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=bar,bar=baz", result); } @@ -69,17 +76,20 @@ public void ResolvePlaceholders_ResolvesMultiplePlaceholders() public void ResolvePlaceholders_ResolvesMultipleSpringPlaceholders() { const string text = "foo=${foo.boo},bar=${bar.far}"; - var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings = new Dictionary { { "foo:boo", "bar" }, { "bar:far", "baz" } }; - builder.AddInMemoryCollection(dic1); + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, builder.Build(), NullLogger.Instance); + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=bar,bar=baz", result); } @@ -87,18 +97,20 @@ public void ResolvePlaceholders_ResolvesMultipleSpringPlaceholders() public void ResolvePlaceholders_ResolvesMultipleRecursivePlaceholders() { const string text = "foo=${bar}"; - var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings = new Dictionary { { "bar", "${baz}" }, { "baz", "bar" } }; - builder.AddInMemoryCollection(dic1); - IConfigurationRoot configurationRoot = builder.Build(); + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=bar", result); } @@ -106,18 +118,20 @@ public void ResolvePlaceholders_ResolvesMultipleRecursivePlaceholders() public void ResolvePlaceholders_ResolvesMultipleRecursiveSpringPlaceholders() { const string text = "foo=${bar.boo}"; - var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings = new Dictionary { { "bar:boo", "${baz.faz}" }, { "baz:faz", "bar" } }; - builder.AddInMemoryCollection(dic1); - IConfigurationRoot configurationRoot = builder.Build(); + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); + + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=bar", result); } @@ -125,21 +139,20 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveSpringPlaceholders() public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() { const string text1 = "foo=${b${inner}}"; - var builder1 = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings1 = new Dictionary { { "bar", "bar" }, { "inner", "ar" } }; - builder1.AddInMemoryCollection(dic1); - IConfigurationRoot config1 = builder1.Build(); + var builder1 = new ConfigurationBuilder(); + builder1.AddInMemoryCollection(appSettings1); + IConfiguration configuration1 = builder1.Build(); const string text2 = "${top}"; - var builder2 = new ConfigurationBuilder(); - var dic2 = new Dictionary + var appSettings2 = new Dictionary { { "top", "${child}+${child}" }, { "child", "${${differentiator}.grandchild}" }, @@ -147,12 +160,16 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() { "first.grandchild", "actualValue" } }; - builder2.AddInMemoryCollection(dic2); - IConfigurationRoot config2 = builder2.Build(); + var builder2 = new ConfigurationBuilder(); + builder2.AddInMemoryCollection(appSettings2); + IConfiguration configuration2 = builder2.Build(); - string? result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1, NullLogger.Instance); + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); + + string? result1 = helper.ResolvePlaceholders(text1, configuration1); Assert.Equal("foo=bar", result1); - string? result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2, NullLogger.Instance); + + string? result2 = helper.ResolvePlaceholders(text2, configuration2); Assert.Equal("actualValue+actualValue", result2); } @@ -160,21 +177,20 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders() public void ResolvePlaceholders_ResolvesMultipleRecursiveInSpringPlaceholders() { const string text1 = "foo=${b${inner.placeholder}}"; - var builder1 = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings1 = new Dictionary { { "bar", "bar" }, { "inner:placeholder", "ar" } }; - builder1.AddInMemoryCollection(dic1); - IConfigurationRoot config1 = builder1.Build(); + var builder1 = new ConfigurationBuilder(); + builder1.AddInMemoryCollection(appSettings1); + IConfiguration configuration1 = builder1.Build(); const string text2 = "${top}"; - var builder2 = new ConfigurationBuilder(); - var dic2 = new Dictionary + var appSettings2 = new Dictionary { { "top", "${child}+${child}" }, { "child", "${${differentiator}.grandchild}" }, @@ -182,12 +198,16 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInSpringPlaceholders() { "first:grandchild", "actualValue" } }; - builder2.AddInMemoryCollection(dic2); - IConfigurationRoot config2 = builder2.Build(); + var builder2 = new ConfigurationBuilder(); + builder2.AddInMemoryCollection(appSettings2); + IConfiguration configuration2 = builder2.Build(); - string? result1 = PropertyPlaceholderHelper.ResolvePlaceholders(text1, config1, NullLogger.Instance); + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); + + string? result1 = helper.ResolvePlaceholders(text1, configuration1); Assert.Equal("foo=bar", result1); - string? result2 = PropertyPlaceholderHelper.ResolvePlaceholders(text2, config2, NullLogger.Instance); + + string? result2 = helper.ResolvePlaceholders(text2, configuration2); Assert.Equal("actualValue+actualValue", result2); } @@ -195,24 +215,26 @@ public void ResolvePlaceholders_ResolvesMultipleRecursiveInSpringPlaceholders() public void ResolvePlaceholders_UnresolvedPlaceholderIsIgnored() { const string text = "foo=${foo},bar=${bar}"; - var builder = new ConfigurationBuilder(); - var dic1 = new Dictionary + var appSettings = new Dictionary { { "foo", "bar" } }; - builder.AddInMemoryCollection(dic1); - IConfigurationRoot configurationRoot = builder.Build(); + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=bar,bar=${bar}", result); } [Fact] public void ResolvePlaceholders_ResolvesArrayRefPlaceholder() { - const string json1 = """ + const string json = """ { "vcap": { "application": { @@ -242,18 +264,20 @@ public void ResolvePlaceholders_ResolvesArrayRefPlaceholder() """; using var sandbox = new Sandbox(); - string path = sandbox.CreateFile("json", json1); + string path = sandbox.CreateFile("json", json); string directory = Path.GetDirectoryName(path)!; string fileName = Path.GetFileName(path); var builder = new ConfigurationBuilder(); builder.SetBasePath(directory); builder.AddJsonFile(fileName); - IConfigurationRoot configurationRoot = builder.Build(); + IConfiguration configuration = builder.Build(); const string text = "foo=${vcap:application:uris[1]}"; - string? result = PropertyPlaceholderHelper.ResolvePlaceholders(text, configurationRoot, NullLogger.Instance); + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); + + string? result = helper.ResolvePlaceholders(text, configuration); Assert.Equal("foo=my-app2.10.244.0.34.xip.io", result); } @@ -262,32 +286,41 @@ public void GetResolvedConfigurationPlaceholders_ReturnsValues_WhenResolved() { var builder = new ConfigurationBuilder(); - builder.AddInMemoryCollection(new Dictionary + var appSettings = new Dictionary { { "foo", "${bar}" }, { "bar", "baz" } - }); + }; + + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); - IDictionary resolved = PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(builder.Build(), NullLogger.Instance); + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - Assert.Contains(resolved, f => f.Key == "foo"); - Assert.DoesNotContain(resolved, f => f.Key == "bar"); - Assert.Equal("baz", resolved.First(k => k.Key == "foo").Value); + IDictionary resolved = helper.GetResolvedConfigurationPlaceholders(configuration); + + Assert.Contains(resolved, pair => pair.Key == "foo"); + Assert.DoesNotContain(resolved, pair => pair.Key == "bar"); + Assert.Equal("baz", resolved.First(pair => pair.Key == "foo").Value); } [Fact] public void GetResolvedConfigurationPlaceholders_ReturnsEmpty_WhenUnResolved() { - var builder = new ConfigurationBuilder(); - - builder.AddInMemoryCollection(new Dictionary + var appSettings = new Dictionary { { "foo", "${bar}" } - }); + }; + + var builder = new ConfigurationBuilder(); + builder.AddInMemoryCollection(appSettings); + IConfiguration configuration = builder.Build(); + + var helper = new PropertyPlaceholderHelper(NullLogger.Instance); - IDictionary resolved = PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(builder.Build(), NullLogger.Instance); + IDictionary resolved = helper.GetResolvedConfigurationPlaceholders(configuration); - Assert.Contains(resolved, f => f.Key == "foo"); + Assert.Contains(resolved, pair => pair.Key == "foo"); Assert.Equal(string.Empty, resolved.First(k => k.Key == "foo").Value); } } diff --git a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs index cc8234ea2b..870708e3a5 100644 --- a/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs +++ b/src/Configuration/src/ConfigServer/ConfigServerConfigurationProvider.cs @@ -45,6 +45,7 @@ internal sealed class ConfigServerConfigurationProvider : ConfigurationProvider, private readonly IConfiguration _configuration; private readonly bool _hasConfiguration; private readonly bool _ownsHttpClientHandler; + private readonly ConfigurationSettingsHelper _configurationSettingsHelper; private HttpClientHandler? _httpClientHandler; private ConfigServerDiscoveryService? _configServerDiscoveryService; @@ -87,6 +88,8 @@ internal ConfigServerConfigurationProvider(ConfigServerClientOptions clientOptio _loggerFactory = loggerFactory; Logger = _loggerFactory.CreateLogger(); + _configurationSettingsHelper = new ConfigurationSettingsHelper(loggerFactory); + if (configuration != null) { _configuration = configuration; @@ -119,7 +122,7 @@ private void OnSettingsChanged() if (_hasConfiguration) { - ConfigurationSettingsHelper.Initialize(ConfigurationPrefix, ClientOptions, _configuration); + _configurationSettingsHelper.Initialize(ConfigurationPrefix, ClientOptions, _configuration); _configuration.GetReloadToken().RegisterChangeCallback(_ => OnSettingsChanged(), null); } diff --git a/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs b/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs index 2fd54eb3c2..e5b69ea827 100644 --- a/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs +++ b/src/Configuration/src/ConfigServer/ConfigurationSettingsHelper.cs @@ -3,11 +3,12 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using Steeltoe.Common.Configuration; namespace Steeltoe.Configuration.ConfigServer; -internal static class ConfigurationSettingsHelper +internal sealed class ConfigurationSettingsHelper { private const string SpringApplicationPrefix = "spring:application"; private const string VcapApplicationPrefix = "vcap:application"; @@ -15,7 +16,16 @@ internal static class ConfigurationSettingsHelper private const string VcapServicesConfigserver30Prefix = "vcap:services:p.config-server:0"; private const string VcapServicesConfigserverAltPrefix = "vcap:services:config-server:0"; - public static void Initialize(string sectionPrefix, ConfigServerClientOptions options, IConfiguration configuration) + private readonly ConfigurationValuesHelper _configurationValuesHelper; + + public ConfigurationSettingsHelper(ILoggerFactory loggerFactory) + { + ArgumentNullException.ThrowIfNull(loggerFactory); + + _configurationValuesHelper = new ConfigurationValuesHelper(loggerFactory); + } + + public void Initialize(string sectionPrefix, ConfigServerClientOptions options, IConfiguration configuration) { ArgumentException.ThrowIfNullOrEmpty(sectionPrefix); ArgumentNullException.ThrowIfNull(options); @@ -55,42 +65,42 @@ public static void Initialize(string sectionPrefix, ConfigServerClientOptions op options.Uri = GetCloudFoundryUri(sectionPrefix, configuration, options.Uri); } - private static string? GetEnvironment(IConfigurationSection section, string? defaultValue) + private string? GetEnvironment(IConfigurationSection section, string? defaultValue) { return section.GetValue("env", string.IsNullOrEmpty(defaultValue) ? "Production" : defaultValue); } - private static bool GetCertificateValidation(IConfigurationSection section, bool defaultValue) + private bool GetCertificateValidation(IConfigurationSection section, bool defaultValue) { return section.GetValue("validateCertificates", defaultValue) && section.GetValue("validate_certificates", defaultValue); } - private static string? GetClientSecret(string sectionPrefix, IConfiguration configuration) + private string? GetClientSecret(string sectionPrefix, IConfiguration configuration) { - return ConfigurationValuesHelper.GetSetting("credentials:client_secret", configuration, null, VcapServicesConfigserverPrefix, + return _configurationValuesHelper.GetSetting("credentials:client_secret", configuration, null, VcapServicesConfigserverPrefix, VcapServicesConfigserver30Prefix, VcapServicesConfigserverAltPrefix, sectionPrefix); } - private static string? GetClientId(string sectionPrefix, IConfiguration configuration) + private string? GetClientId(string sectionPrefix, IConfiguration configuration) { - return ConfigurationValuesHelper.GetSetting("credentials:client_id", configuration, null, VcapServicesConfigserverPrefix, + return _configurationValuesHelper.GetSetting("credentials:client_id", configuration, null, VcapServicesConfigserverPrefix, VcapServicesConfigserver30Prefix, VcapServicesConfigserverAltPrefix, sectionPrefix); } - private static string? GetAccessTokenUri(string sectionPrefix, IConfiguration configuration) + private string? GetAccessTokenUri(string sectionPrefix, IConfiguration configuration) { - return ConfigurationValuesHelper.GetSetting("credentials:access_token_uri", configuration, null, VcapServicesConfigserverPrefix, + return _configurationValuesHelper.GetSetting("credentials:access_token_uri", configuration, null, VcapServicesConfigserverPrefix, VcapServicesConfigserver30Prefix, VcapServicesConfigserverAltPrefix, sectionPrefix); } - private static string? GetApplicationName(string sectionPrefix, IConfiguration configuration, string? defaultValue) + private string? GetApplicationName(string sectionPrefix, IConfiguration configuration, string? defaultValue) { - return ConfigurationValuesHelper.GetSetting("name", configuration, defaultValue, sectionPrefix, SpringApplicationPrefix, VcapApplicationPrefix); + return _configurationValuesHelper.GetSetting("name", configuration, defaultValue, sectionPrefix, SpringApplicationPrefix, VcapApplicationPrefix); } - private static string? GetCloudFoundryUri(string sectionPrefix, IConfiguration configuration, string? defaultValue) + private string? GetCloudFoundryUri(string sectionPrefix, IConfiguration configuration, string? defaultValue) { - return ConfigurationValuesHelper.GetSetting("credentials:uri", configuration, defaultValue, sectionPrefix, VcapServicesConfigserverPrefix, + return _configurationValuesHelper.GetSetting("credentials:uri", configuration, defaultValue, sectionPrefix, VcapServicesConfigserverPrefix, VcapServicesConfigserver30Prefix, VcapServicesConfigserverAltPrefix); } } diff --git a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs index da71bf5b15..4578bce416 100644 --- a/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs +++ b/src/Configuration/src/Placeholder/PlaceholderResolverProvider.cs @@ -18,6 +18,7 @@ namespace Steeltoe.Configuration.Placeholder; /// internal sealed class PlaceholderResolverProvider : IPlaceholderResolverProvider, IDisposable { + private readonly PropertyPlaceholderHelper _propertyPlaceholderHelper; private bool _isDisposed; public IList Providers { get; } = new List(); @@ -44,6 +45,9 @@ public PlaceholderResolverProvider(IConfigurationRoot root, ILoggerFactory logge ArgumentNullException.ThrowIfNull(loggerFactory); Configuration = root; + + ILogger placeholderHelperLogger = loggerFactory.CreateLogger(); + _propertyPlaceholderHelper = new PropertyPlaceholderHelper(placeholderHelperLogger); } /// @@ -62,6 +66,9 @@ public PlaceholderResolverProvider(IList providers, ILog ArgumentNullException.ThrowIfNull(loggerFactory); Providers = providers; + + ILogger placeholderHelperLogger = loggerFactory.CreateLogger(); + _propertyPlaceholderHelper = new PropertyPlaceholderHelper(placeholderHelperLogger); } /// @@ -82,7 +89,7 @@ public bool TryGet(string key, out string? value) EnsureInitialized(); string? originalValue = Configuration![key]; - value = PropertyPlaceholderHelper.ResolvePlaceholders(originalValue, Configuration, NullLogger.Instance); + value = _propertyPlaceholderHelper.ResolvePlaceholders(originalValue, Configuration); if (value != originalValue && !ResolvedKeys.Contains(key)) { diff --git a/src/Configuration/test/ConfigServer.Integration.Test/NestedPlaceholderEncryptionIntegrationTest.cs b/src/Configuration/test/ConfigServer.Integration.Test/NestedPlaceholderEncryptionIntegrationTest.cs index d136260ebd..98e6154d09 100644 --- a/src/Configuration/test/ConfigServer.Integration.Test/NestedPlaceholderEncryptionIntegrationTest.cs +++ b/src/Configuration/test/ConfigServer.Integration.Test/NestedPlaceholderEncryptionIntegrationTest.cs @@ -33,16 +33,16 @@ public void ResolveOuterEncryptionInnerPlaceholder_returnsDecryptedValuesInPlace var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); - IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(config1); + IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(configuration1); using var server = new TestServer(hostBuilder); - var config2 = server.Services.GetRequiredService(); - Assert.NotSame(config1, config2); + var configuration2 = server.Services.GetRequiredService(); + Assert.NotSame(configuration1, configuration2); - Assert.Equal("encrypt the world", config2["encrypted"]); - Assert.Equal("encrypt the world", config2["placeholder"]); + Assert.Equal("encrypt the world", configuration2["encrypted"]); + Assert.Equal("encrypt the world", configuration2["placeholder"]); } [Fact] @@ -67,15 +67,15 @@ public void ResolveOuterPlaceholderInnerEncryption_returnsDecryptedValuesInPlace var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); - IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(config1); + IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(configuration1); using var server = new TestServer(hostBuilder); - var config2 = server.Services.GetRequiredService(); - Assert.NotSame(config1, config2); + var configuration2 = server.Services.GetRequiredService(); + Assert.NotSame(configuration1, configuration2); - Assert.Equal("encrypt the world", config2["encrypted"]); - Assert.Equal("encrypt the world", config2["placeholder"]); + Assert.Equal("encrypt the world", configuration2["encrypted"]); + Assert.Equal("encrypt the world", configuration2["placeholder"]); } } diff --git a/src/Configuration/test/ConfigServer.Test/ConfigurationSettingsHelperTest.cs b/src/Configuration/test/ConfigServer.Test/ConfigurationSettingsHelperTest.cs index 66f3e721df..fc692175b6 100644 --- a/src/Configuration/test/ConfigServer.Test/ConfigurationSettingsHelperTest.cs +++ b/src/Configuration/test/ConfigServer.Test/ConfigurationSettingsHelperTest.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging.Abstractions; namespace Steeltoe.Configuration.ConfigServer.Test; @@ -15,7 +16,9 @@ public void Initialize_WithDefaultSettings() var options = new ConfigServerClientOptions(); IConfiguration configuration = new ConfigurationRoot(new List()); - ConfigurationSettingsHelper.Initialize(prefix, options, configuration); + var helper = new ConfigurationSettingsHelper(NullLoggerFactory.Instance); + helper.Initialize(prefix, options, configuration); + TestHelper.VerifyDefaults(options); } } diff --git a/src/Configuration/test/Encryption.Test/Decryption/EncryptionServiceCollectionForConfigServerExtensionsTest.cs b/src/Configuration/test/Encryption.Test/Decryption/EncryptionServiceCollectionForConfigServerExtensionsTest.cs index 3fe5297ac7..cd1cb514cb 100644 --- a/src/Configuration/test/Encryption.Test/Decryption/EncryptionServiceCollectionForConfigServerExtensionsTest.cs +++ b/src/Configuration/test/Encryption.Test/Decryption/EncryptionServiceCollectionForConfigServerExtensionsTest.cs @@ -32,16 +32,16 @@ public void ConfigureEncryptionResolver_ConfiguresIConfiguration_ReplacesExistin var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); - IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(config1); + IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(configuration1); using var server = new TestServer(hostBuilder); - var config2 = server.Services.GetRequiredService(); - Assert.NotSame(config1, config2); + var configuration2 = server.Services.GetRequiredService(); + Assert.NotSame(configuration1, configuration2); - Assert.Null(config2["nokey"]); - Assert.Equal("value1", config2["key1"]); - Assert.Equal("encrypt the world", config2["key2"]); + Assert.Null(configuration2["nokey"]); + Assert.Equal("value1", configuration2["key1"]); + Assert.Equal("encrypt the world", configuration2["key2"]); } } diff --git a/src/Configuration/test/Encryption.Test/EncryptionConfigurationExtensionsTest.cs b/src/Configuration/test/Encryption.Test/EncryptionConfigurationExtensionsTest.cs index 13d6281af2..83cae3599a 100644 --- a/src/Configuration/test/Encryption.Test/EncryptionConfigurationExtensionsTest.cs +++ b/src/Configuration/test/Encryption.Test/EncryptionConfigurationExtensionsTest.cs @@ -86,19 +86,19 @@ public void AddEncryptionResolver_WithConfiguration_ReturnsNewConfigurationWithD var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); - IConfiguration config2 = config1.AddEncryptionResolver(_decryptorMock.Object); - Assert.NotSame(config1, config2); + IConfiguration configuration2 = configuration1.AddEncryptionResolver(_decryptorMock.Object); + Assert.NotSame(configuration1, configuration2); - var root2 = (IConfigurationRoot)config2; + var root2 = (IConfigurationRoot)configuration2; Assert.Single(root2.Providers); IConfigurationProvider provider = root2.Providers.ToList()[0]; Assert.IsType(provider); - Assert.Null(config2["nokey"]); - Assert.Equal("value1", config2["key1"]); - Assert.Equal("DECRYPTED", config2["key2"]); + Assert.Null(configuration2["nokey"]); + Assert.Equal("value1", configuration2["key1"]); + Assert.Equal("DECRYPTED", configuration2["key2"]); _decryptorMock.Verify(x => x.Decrypt("something")); _decryptorMock.VerifyNoOtherCalls(); @@ -117,19 +117,19 @@ public void AddEncryptionResolver_WithConfiguration_ReturnsNewConfigurationWithW var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); - IConfiguration config2 = config1.AddEncryptionResolver(_decryptorMock.Object); - Assert.NotSame(config1, config2); + IConfiguration configuration2 = configuration1.AddEncryptionResolver(_decryptorMock.Object); + Assert.NotSame(configuration1, configuration2); - var root2 = (IConfigurationRoot)config2; + var root2 = (IConfigurationRoot)configuration2; Assert.Single(root2.Providers); IConfigurationProvider provider = root2.Providers.ToList()[0]; Assert.IsType(provider); - Assert.Null(config2["nokey"]); - Assert.Equal("value1", config2["key1"]); - Assert.Equal("DECRYPTED", config2["key2"]); + Assert.Null(configuration2["nokey"]); + Assert.Equal("value1", configuration2["key1"]); + Assert.Equal("DECRYPTED", configuration2["key2"]); _decryptorMock.Verify(x => x.Decrypt("something", "keyalias")); _decryptorMock.VerifyNoOtherCalls(); diff --git a/src/Configuration/test/Encryption.Test/EncryptionServiceCollectionExtensionsTest.cs b/src/Configuration/test/Encryption.Test/EncryptionServiceCollectionExtensionsTest.cs index 44a2b60cb3..df42e5c41c 100644 --- a/src/Configuration/test/Encryption.Test/EncryptionServiceCollectionExtensionsTest.cs +++ b/src/Configuration/test/Encryption.Test/EncryptionServiceCollectionExtensionsTest.cs @@ -23,17 +23,17 @@ public void ConfigureEncryptionResolver_ConfiguresIConfiguration_ReplacesExistin var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); - IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(config1); + IWebHostBuilder hostBuilder = new WebHostBuilder().UseStartup().UseConfiguration(configuration1); using var server = new TestServer(hostBuilder); - var config2 = server.Services.GetRequiredService(); - Assert.NotSame(config1, config2); + var configuration2 = server.Services.GetRequiredService(); + Assert.NotSame(configuration1, configuration2); - Assert.Null(config2["nokey"]); - Assert.Equal("value1", config2["key1"]); - Assert.Equal("DECRYPTED", config2["key2"]); - Assert.Equal("DECRYPTEDWITHALIAS", config2["key3"]); + Assert.Null(configuration2["nokey"]); + Assert.Equal("value1", configuration2["key1"]); + Assert.Equal("DECRYPTED", configuration2["key2"]); + Assert.Equal("DECRYPTEDWITHALIAS", configuration2["key3"]); } } diff --git a/src/Configuration/test/Placeholder.Test/PlaceholderConfigurationExtensionsTest.cs b/src/Configuration/test/Placeholder.Test/PlaceholderConfigurationExtensionsTest.cs index c99359fa43..d894626c26 100644 --- a/src/Configuration/test/Placeholder.Test/PlaceholderConfigurationExtensionsTest.cs +++ b/src/Configuration/test/Placeholder.Test/PlaceholderConfigurationExtensionsTest.cs @@ -249,21 +249,21 @@ public void AddPlaceholderResolver_WithConfiguration_ReturnsNewConfiguration() var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); - IConfiguration config2 = config1.AddPlaceholderResolver(); - Assert.NotSame(config1, config2); + IConfiguration configuration2 = configuration1.AddPlaceholderResolver(); + Assert.NotSame(configuration1, configuration2); - var root2 = (IConfigurationRoot)config2; + var root2 = (IConfigurationRoot)configuration2; Assert.Single(root2.Providers); IConfigurationProvider provider = root2.Providers.ToList()[0]; Assert.IsType(provider); - Assert.Null(config2["nokey"]); - Assert.Equal("value1", config2["key1"]); - Assert.Equal("value1", config2["key2"]); - Assert.Equal("notfound", config2["key3"]); - Assert.Equal("${nokey}", config2["key4"]); + Assert.Null(configuration2["nokey"]); + Assert.Equal("value1", configuration2["key1"]); + Assert.Equal("value1", configuration2["key2"]); + Assert.Equal("notfound", configuration2["key3"]); + Assert.Equal("${nokey}", configuration2["key4"]); } [Fact] diff --git a/src/Configuration/test/Placeholder.Test/PlaceholderResolverExtensionsTest.cs b/src/Configuration/test/Placeholder.Test/PlaceholderResolverExtensionsTest.cs index 794722175f..ff99058097 100644 --- a/src/Configuration/test/Placeholder.Test/PlaceholderResolverExtensionsTest.cs +++ b/src/Configuration/test/Placeholder.Test/PlaceholderResolverExtensionsTest.cs @@ -27,22 +27,22 @@ public void ConfigurePlaceholderResolver_ConfiguresIConfiguration_ReplacesExisti var builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(settings); - IConfigurationRoot config1 = builder.Build(); + IConfigurationRoot configuration1 = builder.Build(); IWebHostBuilder hostBuilder = new WebHostBuilder(); hostBuilder.UseStartup(); - hostBuilder.UseConfiguration(config1); + hostBuilder.UseConfiguration(configuration1); hostBuilder.ConfigureServices((context, services) => services.ConfigurePlaceholderResolver(context.Configuration)); using var server = new TestServer(hostBuilder); - var config2 = server.Services.GetRequiredService(); - Assert.NotSame(config1, config2); - - Assert.Null(config2["nokey"]); - Assert.Equal("value1", config2["key1"]); - Assert.Equal("value1", config2["key2"]); - Assert.Equal("notfound", config2["key3"]); - Assert.Equal("${nokey}", config2["key4"]); + var configuration2 = server.Services.GetRequiredService(); + Assert.NotSame(configuration1, configuration2); + + Assert.Null(configuration2["nokey"]); + Assert.Equal("value1", configuration2["key1"]); + Assert.Equal("value1", configuration2["key2"]); + Assert.Equal("notfound", configuration2["key3"]); + Assert.Equal("${nokey}", configuration2["key4"]); } [Fact]