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