From 5c23d8148aed68fd8d9bd305dc2b67116cb6573b Mon Sep 17 00:00:00 2001 From: Khanbala Rashidov <50279392+KhanbalaRashidov@users.noreply.github.com> Date: Tue, 2 Jul 2024 15:02:26 +0400 Subject: [PATCH 1/5] Code refactoring and implement primary constructor --- .../Model/BrowserLinkOutgoingPeerResolver.cs | 5 +-- .../AspireTablesExtensions.cs | 12 ++----- .../Aspire.Azure.Data.Tables/AssemblyInfo.cs | 5 +-- .../EventProcessorClientComponent.cs | 17 +++------- .../PartitionReceiverClientComponent.cs | 15 +++------ .../AspireServiceBusExtensions.cs | 27 +++++++--------- .../AspireWebPubSubExtensions.cs | 31 +++++++------------ .../AssemblyInfo.cs | 6 +--- .../Common/ConfigurationSchemaAttributes.cs | 24 ++++---------- .../Common/HealthChecksExtensions.cs | 4 +-- 10 files changed, 45 insertions(+), 101 deletions(-) diff --git a/src/Aspire.Dashboard/Model/BrowserLinkOutgoingPeerResolver.cs b/src/Aspire.Dashboard/Model/BrowserLinkOutgoingPeerResolver.cs index 56d9404a9b..775a9e6d4b 100644 --- a/src/Aspire.Dashboard/Model/BrowserLinkOutgoingPeerResolver.cs +++ b/src/Aspire.Dashboard/Model/BrowserLinkOutgoingPeerResolver.cs @@ -8,10 +8,7 @@ namespace Aspire.Dashboard.Model; public sealed class BrowserLinkOutgoingPeerResolver : IOutgoingPeerResolver { - public IDisposable OnPeerChanges(Func callback) - { - return new NullSubscription(); - } + public IDisposable OnPeerChanges(Func callback)=> new NullSubscription(); private sealed class NullSubscription : IDisposable { diff --git a/src/Components/Aspire.Azure.Data.Tables/AspireTablesExtensions.cs b/src/Components/Aspire.Azure.Data.Tables/AspireTablesExtensions.cs index 464f499903..b92f90b567 100644 --- a/src/Components/Aspire.Azure.Data.Tables/AspireTablesExtensions.cs +++ b/src/Components/Aspire.Azure.Data.Tables/AspireTablesExtensions.cs @@ -36,9 +36,7 @@ public static void AddAzureTableClient( string connectionName, Action? configureSettings = null, Action>? configureClientBuilder = null) - { - new TableServiceComponent().AddClient(builder, DefaultConfigSectionName, configureSettings, configureClientBuilder, connectionName, serviceKey: null); - } + => new TableServiceComponent().AddClient(builder, DefaultConfigSectionName, configureSettings, configureClientBuilder, connectionName, serviceKey: null); /// /// Registers as a singleton for given in the services provided by the . @@ -83,17 +81,13 @@ protected override IAzureClientBuilder A }, requiresCredential: false); } - protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration) - { + protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration) => #pragma warning disable IDE0200 // Remove unnecessary lambda expression - needed so the ConfigBinder Source Generator works clientBuilder.ConfigureOptions(options => configuration.Bind(options)); #pragma warning restore IDE0200 - } - protected override void BindSettingsToConfiguration(AzureDataTablesSettings settings, IConfiguration configuration) - { + protected override void BindSettingsToConfiguration(AzureDataTablesSettings settings, IConfiguration configuration) => configuration.Bind(settings); - } protected override IHealthCheck CreateHealthCheck(TableServiceClient client, AzureDataTablesSettings settings) => new AzureTableServiceHealthCheck(client, new AzureTableServiceHealthCheckOptions()); diff --git a/src/Components/Aspire.Azure.Data.Tables/AssemblyInfo.cs b/src/Components/Aspire.Azure.Data.Tables/AssemblyInfo.cs index 3cb76e2da4..6c8f6b79ec 100644 --- a/src/Components/Aspire.Azure.Data.Tables/AssemblyInfo.cs +++ b/src/Components/Aspire.Azure.Data.Tables/AssemblyInfo.cs @@ -8,7 +8,4 @@ [assembly: ConfigurationSchema("Aspire:Azure:Data:Tables", typeof(AzureDataTablesSettings))] [assembly: ConfigurationSchema("Aspire:Azure:Data:Tables:ClientOptions", typeof(TableClientOptions), exclusionPaths: ["Default"])] -[assembly: LoggingCategories( - "Azure", - "Azure.Core", - "Azure.Identity")] +[assembly: LoggingCategories("Azure", "Azure.Core", "Azure.Identity")] diff --git a/src/Components/Aspire.Azure.Messaging.EventHubs/EventProcessorClientComponent.cs b/src/Components/Aspire.Azure.Messaging.EventHubs/EventProcessorClientComponent.cs index cf62ce7886..d623be8d31 100644 --- a/src/Components/Aspire.Azure.Messaging.EventHubs/EventProcessorClientComponent.cs +++ b/src/Components/Aspire.Azure.Messaging.EventHubs/EventProcessorClientComponent.cs @@ -19,24 +19,18 @@ internal sealed class EventProcessorClientComponent() // cannot be in base class as source generator chokes on generic placeholders protected override void BindClientOptionsToConfiguration( IAzureClientBuilder clientBuilder, - IConfiguration configuration) - { + IConfiguration configuration) => #pragma warning disable IDE0200 // Remove unnecessary lambda expression - needed so the ConfigBinder Source Generator works - clientBuilder.ConfigureOptions(options => configuration.Bind(options)); + clientBuilder.ConfigureOptions(options => configuration.Bind(options)); #pragma warning restore IDE0200 - } protected override void BindSettingsToConfiguration(AzureMessagingEventHubsProcessorSettings settings, - IConfiguration config) - { - config.Bind(settings); - } + IConfiguration config) => config.Bind(settings); protected override IAzureClientBuilder AddClient( AzureClientFactoryBuilder azureFactoryBuilder, AzureMessagingEventHubsProcessorSettings settings, - string connectionName, string configurationSectionName) - { - return azureFactoryBuilder.AddClient( + string connectionName, string configurationSectionName) => + azureFactoryBuilder.AddClient( (options, cred, provider) => { EnsureConnectionStringOrNamespaceProvided(settings, connectionName, configurationSectionName); @@ -71,7 +65,6 @@ protected override IAzureClientBuilder { // cannot be in base class as source generator chokes on generic placeholders - protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration) - { + protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration) => #pragma warning disable IDE0200 // Remove unnecessary lambda expression - needed so the ConfigBinder Source Generator works clientBuilder.ConfigureOptions(options => configuration.Bind(options)); #pragma warning restore IDE0200 - } - protected override void BindSettingsToConfiguration(AzureMessagingEventHubsPartitionReceiverSettings settings, IConfiguration config) - { + protected override void BindSettingsToConfiguration(AzureMessagingEventHubsPartitionReceiverSettings settings, IConfiguration config) => config.Bind(settings); - } + protected override IAzureClientBuilder AddClient( AzureClientFactoryBuilder azureFactoryBuilder, AzureMessagingEventHubsPartitionReceiverSettings settings, - string connectionName, string configurationSectionName) - { - return ((IAzureClientFactoryBuilderWithCredential)azureFactoryBuilder).RegisterClientFactory((options, cred) => + string connectionName, string configurationSectionName) => + ((IAzureClientFactoryBuilderWithCredential)azureFactoryBuilder).RegisterClientFactory((options, cred) => { EnsureConnectionStringOrNamespaceProvided(settings, connectionName, configurationSectionName); @@ -54,5 +50,4 @@ protected override IAzureClientBuilder? configureSettings = null, - Action>? configureClientBuilder = null) - { - new MessageBusComponent().AddClient(builder, DefaultConfigSectionName, configureSettings, configureClientBuilder, connectionName, serviceKey: null); - } + Action>? configureClientBuilder = null)=> + new MessageBusComponent().AddClient(builder, DefaultConfigSectionName, configureSettings, configureClientBuilder, connectionName, serviceKey: null); /// /// Registers as a singleton for given in the services provided by the . @@ -66,9 +64,9 @@ private sealed class MessageBusComponent : AzureComponent AddClient( AzureClientFactoryBuilder azureFactoryBuilder, AzureMessagingServiceBusSettings settings, - string connectionName, string configurationSectionName) - { - return ((IAzureClientFactoryBuilderWithCredential)azureFactoryBuilder).RegisterClientFactory((options, cred) => + string connectionName, string configurationSectionName)=> + + ((IAzureClientFactoryBuilderWithCredential)azureFactoryBuilder).RegisterClientFactory((options, cred) => { var connectionString = settings.ConnectionString; if (string.IsNullOrEmpty(connectionString) && string.IsNullOrEmpty(settings.FullyQualifiedNamespace)) @@ -80,7 +78,6 @@ protected override IAzureClientBuilder !string.IsNullOrEmpty(settings.HealthCheckQueueName) @@ -97,17 +94,15 @@ protected override IHealthCheck CreateHealthCheck(ServiceBusClient client, Azure Credential = settings.Credential }); - protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration) - { -#pragma warning disable IDE0200 // Remove unnecessary lambda expression - needed so the ConfigBinder Source Generator works + protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration)=> + #pragma warning disable IDE0200 // Remove unnecessary lambda expression - needed so the ConfigBinder Source Generator works clientBuilder.ConfigureOptions(options => configuration.Bind(options)); -#pragma warning restore IDE0200 - } + #pragma warning restore IDE0200 + - protected override void BindSettingsToConfiguration(AzureMessagingServiceBusSettings settings, IConfiguration config) - { + protected override void BindSettingsToConfiguration(AzureMessagingServiceBusSettings settings, IConfiguration config)=> config.Bind(settings); - } + protected override bool GetHealthCheckEnabled(AzureMessagingServiceBusSettings settings) => !string.IsNullOrEmpty(settings.HealthCheckQueueName) || !string.IsNullOrEmpty(settings.HealthCheckTopicName); diff --git a/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs b/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs index 75855affea..dfec23d608 100644 --- a/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs +++ b/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs @@ -34,10 +34,8 @@ public static void AddAzureWebPubSubServiceClient( this IHostApplicationBuilder builder, string connectionName, Action? configureSettings = null, - Action>? configureClientBuilder = null) - { - new WebPubSubComponent().AddClient(builder, DefaultConfigSectionName, configureSettings, configureClientBuilder, connectionName, serviceKey: null); - } + Action>? configureClientBuilder = null) => + new WebPubSubComponent().AddClient(builder, DefaultConfigSectionName, configureSettings, configureClientBuilder, connectionName, serviceKey: null); /// /// Registers as a singleton for given and in the services provided by the . @@ -74,9 +72,8 @@ public static void AddKeyedAzureWebPubSubServiceClient( private sealed class WebPubSubComponent : AzureComponent { protected override IAzureClientBuilder AddClient - (AzureClientFactoryBuilder azureFactoryBuilder, AzureMessagingWebPubSubSettings settings, string connectionName, string configurationSectionName) - { - return ((IAzureClientFactoryBuilderWithCredential)azureFactoryBuilder).RegisterClientFactory((options, cred) => + (AzureClientFactoryBuilder azureFactoryBuilder, AzureMessagingWebPubSubSettings settings, string connectionName, string configurationSectionName) => + ((IAzureClientFactoryBuilderWithCredential)azureFactoryBuilder).RegisterClientFactory((options, cred) => { var connectionString = settings.ConnectionString; if (string.IsNullOrEmpty(connectionString) && settings.Endpoint == null) @@ -97,22 +94,19 @@ protected override IAzureClientBuilder new HealthCheck(client); - protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration) - { + protected override void BindClientOptionsToConfiguration(IAzureClientBuilder clientBuilder, IConfiguration configuration) => #pragma warning disable IDE0200 // Remove unnecessary lambda expression - needed so the ConfigBinder Source Generator works clientBuilder.ConfigureOptions(options => configuration.Bind(options)); #pragma warning restore IDE0200 - } - protected override void BindSettingsToConfiguration(AzureMessagingWebPubSubSettings settings, IConfiguration config) - { + + protected override void BindSettingsToConfiguration(AzureMessagingWebPubSubSettings settings, IConfiguration config) => config.Bind(settings); - } + protected override TokenCredential? GetTokenCredential(AzureMessagingWebPubSubSettings settings) => settings.Credential; @@ -124,14 +118,11 @@ protected override bool GetHealthCheckEnabled(AzureMessagingWebPubSubSettings se => !settings.DisableHealthChecks; } - private sealed class HealthCheck : IHealthCheck + private sealed class HealthCheck(WebPubSubServiceClient client) : IHealthCheck { - private readonly WebPubSubServiceClient _client; + private readonly WebPubSubServiceClient _client = client; + - public HealthCheck(WebPubSubServiceClient client) - { - _client = client; - } public async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { diff --git a/src/Components/Aspire.Azure.Messaging.WebPubSub/AssemblyInfo.cs b/src/Components/Aspire.Azure.Messaging.WebPubSub/AssemblyInfo.cs index e0b6570ac2..2666a8da7b 100644 --- a/src/Components/Aspire.Azure.Messaging.WebPubSub/AssemblyInfo.cs +++ b/src/Components/Aspire.Azure.Messaging.WebPubSub/AssemblyInfo.cs @@ -8,8 +8,4 @@ [assembly: ConfigurationSchema("Aspire:Azure:Messaging:WebPubSub", typeof(AzureMessagingWebPubSubSettings))] [assembly: ConfigurationSchema("Aspire:Azure:Messaging:WebPubSub:ClientOptions", typeof(WebPubSubServiceClientOptions), exclusionPaths: ["Default"])] -[assembly: LoggingCategories( - "Azure", - "Azure.Core", - "Azure.Identity", - "Azure.Messaging.WebPubSub")] +[assembly: LoggingCategories( "Azure", "Azure.Core", "Azure.Identity", "Azure.Messaging.WebPubSub")] diff --git a/src/Components/Common/ConfigurationSchemaAttributes.cs b/src/Components/Common/ConfigurationSchemaAttributes.cs index 5b15afdd46..00317b582d 100644 --- a/src/Components/Common/ConfigurationSchemaAttributes.cs +++ b/src/Components/Common/ConfigurationSchemaAttributes.cs @@ -7,44 +7,32 @@ namespace Aspire; /// Attribute used to automatically generate a JSON schema for a component's configuration. /// [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] -internal sealed class ConfigurationSchemaAttribute : Attribute +internal sealed class ConfigurationSchemaAttribute(string path, Type type, string[]? exclusionPaths = null) : Attribute { - public ConfigurationSchemaAttribute(string path, Type type, string[]? exclusionPaths = null) - { - Path = path; - Type = type; - ExclusionPaths = exclusionPaths; - } - /// /// The path corresponding to which config section binds to. /// - public string Path { get; } + public string Path { get; } = path; /// /// The type that is bound to the configuration. This type will be walked and generate a JSON schema for all the properties. /// - public Type Type { get; } + public Type Type { get; } = type; /// /// (optional) The config sections to exclude from the ConfigurationSchema. This is useful if there are properties you don't want to publicize in the config schema. /// - public string[]? ExclusionPaths { get; } + public string[]? ExclusionPaths { get; } = exclusionPaths; } /// /// Provides information to describe the logging categories produced by a component. /// [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] -internal sealed class LoggingCategoriesAttribute : Attribute +internal sealed class LoggingCategoriesAttribute(params string[] categories) : Attribute { - public LoggingCategoriesAttribute(params string[] categories) - { - Categories = categories; - } - /// /// The list of log categories produced by the component. These categories will show up under the Logging:LogLevel section in appsettings.json. /// - public string[] Categories { get; set; } + public string[] Categories { get; set; } = categories; } diff --git a/src/Components/Common/HealthChecksExtensions.cs b/src/Components/Common/HealthChecksExtensions.cs index 29e4762df2..7a02322627 100644 --- a/src/Components/Common/HealthChecksExtensions.cs +++ b/src/Components/Common/HealthChecksExtensions.cs @@ -12,10 +12,8 @@ internal static class HealthChecksExtensions /// /// Adds a HealthCheckRegistration if one hasn't already been added to the builder. /// - public static void TryAddHealthCheck(this IHostApplicationBuilder builder, HealthCheckRegistration healthCheckRegistration) - { + public static void TryAddHealthCheck(this IHostApplicationBuilder builder, HealthCheckRegistration healthCheckRegistration)=> builder.TryAddHealthCheck(healthCheckRegistration.Name, hcBuilder => hcBuilder.Add(healthCheckRegistration)); - } /// /// Invokes the action if the given hasn't already been added to the builder. From 9f30b01273d9c506953d3d05d8fb838a412b45db Mon Sep 17 00:00:00 2001 From: Khanbala Rashidov <50279392+KhanbalaRashidov@users.noreply.github.com> Date: Tue, 2 Jul 2024 15:21:08 +0400 Subject: [PATCH 2/5] Refactor Aspire.Dashboard --- .../DashboardWebApplication.cs | 28 ++++--------- .../Model/BrowserSecurityHeadersMiddleware.cs | 16 ++----- .../Model/BrowserTimeProvider.cs | 14 ++----- .../Model/ResourceOutgoingPeerResolver.cs | 6 +-- .../Model/ResourceTypeDetails.cs | 24 ++++------- .../Model/ResourceViewModel.cs | 6 +-- .../Model/ResourceViewModelExtensions.cs | 42 +++++++------------ .../Model/StructuredLogsViewModel.cs | 14 ++----- src/Aspire.Dashboard/Model/TracesViewModel.cs | 14 ++----- .../Model/ValidateTokenMiddleware.cs | 15 ++----- .../Otlp/Grpc/OtlpGrpcLogsService.cs | 15 ++----- .../Otlp/Grpc/OtlpGrpcMetricsService.cs | 15 ++----- .../Otlp/Grpc/OtlpGrpcTraceService.cs | 11 ++--- .../Otlp/Model/ColorGenerator.cs | 25 +++++------ .../Otlp/Model/MetricValues/MetricValue.cs | 25 +++-------- .../Model/MetricValues/MetricValueBase.cs | 5 +-- .../Otlp/Model/OtlpApplication.cs | 15 +++---- .../Otlp/Model/OtlpHelpers.cs | 10 +---- .../Otlp/Model/OtlpInstrument.cs | 6 +-- src/Aspire.Dashboard/Otlp/Model/OtlpMeter.cs | 15 ++----- src/Aspire.Dashboard/Otlp/Model/OtlpSpan.cs | 24 ++++------- src/Aspire.Dashboard/Otlp/Model/OtlpTrace.cs | 29 ++++--------- .../Otlp/Model/OtlpTraceCollection.cs | 10 +---- src/Aspire.Dashboard/Otlp/Model/OtlpUnits.cs | 12 ++---- src/Aspire.Dashboard/Otlp/OtlpLogsService.cs | 12 ++---- .../Otlp/OtlpMetricsService.cs | 15 ++----- src/Aspire.Dashboard/Otlp/OtlpTraceService.cs | 12 ++---- .../Otlp/Storage/TelemetryRepository.cs | 30 +++++-------- .../ResourceService/DashboardClient.cs | 5 +-- .../ResourceService/Partials.cs | 33 +++++---------- src/Aspire.Dashboard/ShortcutManager.cs | 15 ++----- .../Utils/CancellationSeries.cs | 5 +-- src/Aspire.Dashboard/Utils/DashboardUrls.cs | 10 +---- src/Shared/CircularBuffer.cs | 5 +-- src/Shared/IConfigurationExtensions.cs | 6 +-- src/Shared/TaskHelpers.cs | 11 ++--- src/Shared/TokenGenerator.cs | 7 ++-- 37 files changed, 161 insertions(+), 401 deletions(-) diff --git a/src/Aspire.Dashboard/DashboardWebApplication.cs b/src/Aspire.Dashboard/DashboardWebApplication.cs index f4b97e9785..ee48ebcad7 100644 --- a/src/Aspire.Dashboard/DashboardWebApplication.cs +++ b/src/Aspire.Dashboard/DashboardWebApplication.cs @@ -47,20 +47,14 @@ public sealed class DashboardWebApplication : IAsyncDisposable private Func? _otlpServiceGrpcEndPointAccessor; private Func? _otlpServiceHttpEndPointAccessor; - public Func FrontendEndPointAccessor - { - get => _frontendEndPointAccessor ?? throw new InvalidOperationException("WebApplication not started yet."); - } + public Func FrontendEndPointAccessor => + _frontendEndPointAccessor ?? throw new InvalidOperationException("WebApplication not started yet."); - public Func OtlpServiceGrpcEndPointAccessor - { - get => _otlpServiceGrpcEndPointAccessor ?? throw new InvalidOperationException("WebApplication not started yet."); - } + public Func OtlpServiceGrpcEndPointAccessor => + _otlpServiceGrpcEndPointAccessor ?? throw new InvalidOperationException("WebApplication not started yet."); - public Func OtlpServiceHttpEndPointAccessor - { - get => _otlpServiceHttpEndPointAccessor ?? throw new InvalidOperationException("WebApplication not started yet."); - } + public Func OtlpServiceHttpEndPointAccessor => + _otlpServiceHttpEndPointAccessor ?? throw new InvalidOperationException("WebApplication not started yet."); public IOptionsMonitor DashboardOptionsMonitor => _dashboardOptionsMonitor; @@ -317,10 +311,7 @@ await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.Si } } - private ILogger GetLogger() - { - return _app.Services.GetRequiredService().CreateLogger(); - } + private ILogger GetLogger() => _app.Services.GetRequiredService().CreateLogger(); private static void WriteValidationFailures(ILogger logger, IReadOnlyList validationFailures) { @@ -688,10 +679,7 @@ public Task StopAsync(CancellationToken cancellationToken = default) return _app.StopAsync(cancellationToken); } - public ValueTask DisposeAsync() - { - return _app.DisposeAsync(); - } + public ValueTask DisposeAsync() => _app.DisposeAsync(); private static bool IsHttpsOrNull(Uri? uri) => uri == null || string.Equals(uri.Scheme, "https", StringComparison.Ordinal); diff --git a/src/Aspire.Dashboard/Model/BrowserSecurityHeadersMiddleware.cs b/src/Aspire.Dashboard/Model/BrowserSecurityHeadersMiddleware.cs index be64506435..fde7a68f34 100644 --- a/src/Aspire.Dashboard/Model/BrowserSecurityHeadersMiddleware.cs +++ b/src/Aspire.Dashboard/Model/BrowserSecurityHeadersMiddleware.cs @@ -11,19 +11,11 @@ namespace Aspire.Dashboard.Model; /// - Referrer-Policy /// - X-Content-Type-Options /// -internal sealed class BrowserSecurityHeadersMiddleware +internal sealed class BrowserSecurityHeadersMiddleware(RequestDelegate next, IHostEnvironment environment) { - private readonly RequestDelegate _next; - private readonly string _cspContentHttp; - private readonly string _cspContentHttps; - - public BrowserSecurityHeadersMiddleware(RequestDelegate next, IHostEnvironment environment) - { - _next = next; - - _cspContentHttp = GenerateCspContent(environment, isHttps: false); - _cspContentHttps = GenerateCspContent(environment, isHttps: true); - } + private readonly RequestDelegate _next = next; + private readonly string _cspContentHttp = GenerateCspContent(environment, isHttps: false); + private readonly string _cspContentHttps = GenerateCspContent(environment, isHttps: true); private static string GenerateCspContent(IHostEnvironment environment, bool isHttps) { diff --git a/src/Aspire.Dashboard/Model/BrowserTimeProvider.cs b/src/Aspire.Dashboard/Model/BrowserTimeProvider.cs index 99559346f1..ee4883e00b 100644 --- a/src/Aspire.Dashboard/Model/BrowserTimeProvider.cs +++ b/src/Aspire.Dashboard/Model/BrowserTimeProvider.cs @@ -10,20 +10,12 @@ namespace Aspire.Dashboard.Model; /// - BrowserTimeProvider must be scoped to the user's session. /// - The built-in TimeProvider registration must be singleton for the system time (used by auth). /// -public class BrowserTimeProvider : TimeProvider +public class BrowserTimeProvider(ILoggerFactory loggerFactory) : TimeProvider { - private readonly ILogger _logger; + private readonly ILogger _logger = loggerFactory.CreateLogger(typeof(BrowserTimeProvider)); private TimeZoneInfo? _browserLocalTimeZone; - public BrowserTimeProvider(ILoggerFactory loggerFactory) - { - _logger = loggerFactory.CreateLogger(typeof(BrowserTimeProvider)); - } - - public override TimeZoneInfo LocalTimeZone - { - get => _browserLocalTimeZone ?? base.LocalTimeZone; - } + public override TimeZoneInfo LocalTimeZone => _browserLocalTimeZone ?? base.LocalTimeZone; public void SetBrowserTimeZone(string timeZone) { diff --git a/src/Aspire.Dashboard/Model/ResourceOutgoingPeerResolver.cs b/src/Aspire.Dashboard/Model/ResourceOutgoingPeerResolver.cs index febe05790d..0bee85dfda 100644 --- a/src/Aspire.Dashboard/Model/ResourceOutgoingPeerResolver.cs +++ b/src/Aspire.Dashboard/Model/ResourceOutgoingPeerResolver.cs @@ -59,10 +59,8 @@ public ResourceOutgoingPeerResolver(IDashboardClient resourceService) }); } - public bool TryResolvePeerName(KeyValuePair[] attributes, [NotNullWhen(true)] out string? name) - { - return TryResolvePeerNameCore(_resourceByName, attributes, out name); - } + public bool TryResolvePeerName(KeyValuePair[] attributes, [NotNullWhen(true)] out string? name) => + TryResolvePeerNameCore(_resourceByName, attributes, out name); internal static bool TryResolvePeerNameCore(IDictionary resources, KeyValuePair[] attributes, out string? name) { diff --git a/src/Aspire.Dashboard/Model/ResourceTypeDetails.cs b/src/Aspire.Dashboard/Model/ResourceTypeDetails.cs index b17ccddb42..0848e6edd2 100644 --- a/src/Aspire.Dashboard/Model/ResourceTypeDetails.cs +++ b/src/Aspire.Dashboard/Model/ResourceTypeDetails.cs @@ -20,23 +20,15 @@ private ResourceTypeDetails(OtlpApplicationType type, string? instanceId, string public string? InstanceId { get; } public string? ReplicaSetName { get; } - public static ResourceTypeDetails CreateReplicaSet(string replicaSetName) - { - return new ResourceTypeDetails(OtlpApplicationType.ReplicaSet, instanceId: null, replicaSetName); - } + public static ResourceTypeDetails CreateReplicaSet(string replicaSetName) => + new ResourceTypeDetails(OtlpApplicationType.ReplicaSet, instanceId: null, replicaSetName); - public static ResourceTypeDetails CreateSingleton(string instanceId) - { - return new ResourceTypeDetails(OtlpApplicationType.Singleton, instanceId, replicaSetName: null); - } + public static ResourceTypeDetails CreateSingleton(string instanceId) => + new ResourceTypeDetails(OtlpApplicationType.Singleton, instanceId, replicaSetName: null); - public static ResourceTypeDetails CreateReplicaInstance(string instanceId, string replicaSetName) - { - return new ResourceTypeDetails(OtlpApplicationType.ReplicaInstance, instanceId, replicaSetName); - } + public static ResourceTypeDetails CreateReplicaInstance(string instanceId, string replicaSetName) => + new ResourceTypeDetails(OtlpApplicationType.ReplicaInstance, instanceId, replicaSetName); - public override string ToString() - { - return $"Type = {Type}, InstanceId = {InstanceId}, ReplicaSetName = {ReplicaSetName}"; - } + public override string ToString() => + $"Type = {Type}, InstanceId = {InstanceId}, ReplicaSetName = {ReplicaSetName}"; } diff --git a/src/Aspire.Dashboard/Model/ResourceViewModel.cs b/src/Aspire.Dashboard/Model/ResourceViewModel.cs index 09519d6a14..8e9b838814 100644 --- a/src/Aspire.Dashboard/Model/ResourceViewModel.cs +++ b/src/Aspire.Dashboard/Model/ResourceViewModel.cs @@ -26,11 +26,9 @@ public sealed class ResourceViewModel public required ImmutableArray Commands { get; init; } public KnownResourceState? KnownState { get; init; } - internal bool MatchesFilter(string filter) - { + internal bool MatchesFilter(string filter) => // TODO let ResourceType define the additional data values we include in searches - return Name.Contains(filter, StringComparisons.UserTextSearch); - } + Name.Contains(filter, StringComparisons.UserTextSearch); public static string GetResourceName(ResourceViewModel resource, ConcurrentDictionary allResources) { diff --git a/src/Aspire.Dashboard/Model/ResourceViewModelExtensions.cs b/src/Aspire.Dashboard/Model/ResourceViewModelExtensions.cs index ab45312110..a17fc71457 100644 --- a/src/Aspire.Dashboard/Model/ResourceViewModelExtensions.cs +++ b/src/Aspire.Dashboard/Model/ResourceViewModelExtensions.cs @@ -9,15 +9,11 @@ namespace Aspire.Dashboard.Model; internal static class ResourceViewModelExtensions { - public static bool IsContainer(this ResourceViewModel resource) - { - return StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Container); - } + public static bool IsContainer(this ResourceViewModel resource) => + StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Container); - public static bool IsProject(this ResourceViewModel resource) - { - return StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Project); - } + public static bool IsProject(this ResourceViewModel resource) => + StringComparers.ResourceType.Equals(resource.ResourceType, KnownResourceTypes.Project); public static bool IsExecutable(this ResourceViewModel resource, bool allowSubtypes) { @@ -34,30 +30,20 @@ public static bool IsExecutable(this ResourceViewModel resource, bool allowSubty return false; } - public static bool TryGetExitCode(this ResourceViewModel resource, out int exitCode) - { - return resource.TryGetCustomDataInt(KnownProperties.Resource.ExitCode, out exitCode); - } + public static bool TryGetExitCode(this ResourceViewModel resource, out int exitCode) => + resource.TryGetCustomDataInt(KnownProperties.Resource.ExitCode, out exitCode); - public static bool TryGetContainerImage(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? containerImage) - { - return resource.TryGetCustomDataString(KnownProperties.Container.Image, out containerImage); - } + public static bool TryGetContainerImage(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? containerImage) => + resource.TryGetCustomDataString(KnownProperties.Container.Image, out containerImage); - public static bool TryGetProjectPath(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? projectPath) - { - return resource.TryGetCustomDataString(KnownProperties.Project.Path, out projectPath); - } + public static bool TryGetProjectPath(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? projectPath) => + resource.TryGetCustomDataString(KnownProperties.Project.Path, out projectPath); - public static bool TryGetExecutablePath(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? executablePath) - { - return resource.TryGetCustomDataString(KnownProperties.Executable.Path, out executablePath); - } + public static bool TryGetExecutablePath(this ResourceViewModel resource, [NotNullWhen(returnValue: true)] out string? executablePath) => + resource.TryGetCustomDataString(KnownProperties.Executable.Path, out executablePath); - public static bool TryGetExecutableArguments(this ResourceViewModel resource, out ImmutableArray arguments) - { - return resource.TryGetCustomDataStringArray(KnownProperties.Executable.Args, out arguments); - } + public static bool TryGetExecutableArguments(this ResourceViewModel resource, out ImmutableArray arguments) => + resource.TryGetCustomDataStringArray(KnownProperties.Executable.Args, out arguments); private static bool TryGetCustomDataString(this ResourceViewModel resource, string key, [NotNullWhen(returnValue: true)] out string? s) { diff --git a/src/Aspire.Dashboard/Model/StructuredLogsViewModel.cs b/src/Aspire.Dashboard/Model/StructuredLogsViewModel.cs index b8023a0e80..73619209b9 100644 --- a/src/Aspire.Dashboard/Model/StructuredLogsViewModel.cs +++ b/src/Aspire.Dashboard/Model/StructuredLogsViewModel.cs @@ -7,9 +7,9 @@ namespace Aspire.Dashboard.Model; -public class StructuredLogsViewModel +public class StructuredLogsViewModel(TelemetryRepository telemetryRepository) { - private readonly TelemetryRepository _telemetryRepository; + private readonly TelemetryRepository _telemetryRepository = telemetryRepository; private readonly List _filters = new(); private PagedResult? _logs; @@ -19,11 +19,6 @@ public class StructuredLogsViewModel private int? _logsCount; private LogLevel? _logLevel; - public StructuredLogsViewModel(TelemetryRepository telemetryRepository) - { - _telemetryRepository = telemetryRepository; - } - public string? ApplicationServiceId { get => _applicationServiceId; set => SetValue(ref _applicationServiceId, value); } public string FilterText { get => _filterText; set => SetValue(ref _filterText, value); } public IReadOnlyList Filters => _filters; @@ -97,8 +92,5 @@ public PagedResult GetLogs() return logs; } - public void ClearData() - { - _logs = null; - } + public void ClearData() => _logs = null; } diff --git a/src/Aspire.Dashboard/Model/TracesViewModel.cs b/src/Aspire.Dashboard/Model/TracesViewModel.cs index 0a2d07b161..4960e1b213 100644 --- a/src/Aspire.Dashboard/Model/TracesViewModel.cs +++ b/src/Aspire.Dashboard/Model/TracesViewModel.cs @@ -6,9 +6,9 @@ namespace Aspire.Dashboard.Model; -public class TracesViewModel +public class TracesViewModel(TelemetryRepository telemetryRepository) { - private readonly TelemetryRepository _telemetryRepository; + private readonly TelemetryRepository _telemetryRepository = telemetryRepository; private PagedResult? _traces; private string? _applicationServiceId; @@ -16,11 +16,6 @@ public class TracesViewModel private int _startIndex; private int? _count; - public TracesViewModel(TelemetryRepository telemetryRepository) - { - _telemetryRepository = telemetryRepository; - } - public string? ApplicationServiceId { get => _applicationServiceId; set => SetValue(ref _applicationServiceId, value); } public string FilterText { get => _filterText; set => SetValue(ref _filterText, value); } public int StartIndex { get => _startIndex; set => SetValue(ref _startIndex, value); } @@ -58,9 +53,6 @@ public PagedResult GetTraces() return traces; } - public void ClearData() - { - _traces = null; - } + public void ClearData() => _traces = null; } diff --git a/src/Aspire.Dashboard/Model/ValidateTokenMiddleware.cs b/src/Aspire.Dashboard/Model/ValidateTokenMiddleware.cs index 70a49ab972..7f11e18905 100644 --- a/src/Aspire.Dashboard/Model/ValidateTokenMiddleware.cs +++ b/src/Aspire.Dashboard/Model/ValidateTokenMiddleware.cs @@ -11,18 +11,11 @@ namespace Aspire.Dashboard.Model; -internal sealed class ValidateTokenMiddleware +internal sealed class ValidateTokenMiddleware(RequestDelegate next, IOptionsMonitor options, ILogger logger) { - private readonly RequestDelegate _next; - private readonly IOptionsMonitor _options; - private readonly ILogger _logger; - - public ValidateTokenMiddleware(RequestDelegate next, IOptionsMonitor options, ILogger logger) - { - _next = next; - _options = options; - _logger = logger; - } + private readonly RequestDelegate _next = next; + private readonly IOptionsMonitor _options = options; + private readonly ILogger _logger = logger; public async Task InvokeAsync(HttpContext context) { diff --git a/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcLogsService.cs b/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcLogsService.cs index 477215fa59..ffcb05e2fb 100644 --- a/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcLogsService.cs +++ b/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcLogsService.cs @@ -11,17 +11,10 @@ namespace Aspire.Dashboard.Otlp.Grpc; [Authorize(Policy = OtlpAuthorization.PolicyName)] [SkipStatusCodePages] -public class OtlpGrpcLogsService : LogsService.LogsServiceBase +public class OtlpGrpcLogsService(OtlpLogsService logsService) : LogsService.LogsServiceBase { - private readonly OtlpLogsService _logsService; + private readonly OtlpLogsService _logsService = logsService; - public OtlpGrpcLogsService(OtlpLogsService logsService) - { - _logsService = logsService; - } - - public override Task Export(ExportLogsServiceRequest request, ServerCallContext context) - { - return Task.FromResult(_logsService.Export(request)); - } + public override Task Export(ExportLogsServiceRequest request, ServerCallContext context) => + Task.FromResult(_logsService.Export(request)); } diff --git a/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcMetricsService.cs b/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcMetricsService.cs index 85023989f6..3caaa49f50 100644 --- a/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcMetricsService.cs +++ b/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcMetricsService.cs @@ -11,17 +11,10 @@ namespace Aspire.Dashboard.Otlp.Grpc; [Authorize(Policy = OtlpAuthorization.PolicyName)] [SkipStatusCodePages] -public class OtlpGrpcMetricsService : MetricsService.MetricsServiceBase +public class OtlpGrpcMetricsService(OtlpMetricsService metricsService) : MetricsService.MetricsServiceBase { - private readonly OtlpMetricsService _metricsService; + private readonly OtlpMetricsService _metricsService = metricsService; - public OtlpGrpcMetricsService(OtlpMetricsService metricsService) - { - _metricsService = metricsService; - } - - public override Task Export(ExportMetricsServiceRequest request, ServerCallContext context) - { - return Task.FromResult(_metricsService.Export(request)); - } + public override Task Export(ExportMetricsServiceRequest request, ServerCallContext context) => + Task.FromResult(_metricsService.Export(request)); } diff --git a/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcTraceService.cs b/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcTraceService.cs index 5bbb39cd84..60660c6639 100644 --- a/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcTraceService.cs +++ b/src/Aspire.Dashboard/Otlp/Grpc/OtlpGrpcTraceService.cs @@ -15,13 +15,8 @@ public class OtlpGrpcTraceService : TraceService.TraceServiceBase { private readonly OtlpTraceService _traceService; - public OtlpGrpcTraceService(OtlpTraceService traceService) - { - _traceService = traceService; - } + public OtlpGrpcTraceService(OtlpTraceService traceService) => _traceService = traceService; - public override Task Export(ExportTraceServiceRequest request, ServerCallContext context) - { - return Task.FromResult(_traceService.Export(request)); - } + public override Task Export(ExportTraceServiceRequest request, ServerCallContext context) => + Task.FromResult(_traceService.Export(request)); } diff --git a/src/Aspire.Dashboard/Otlp/Model/ColorGenerator.cs b/src/Aspire.Dashboard/Otlp/Model/ColorGenerator.cs index 1560023b12..613683c147 100644 --- a/src/Aspire.Dashboard/Otlp/Model/ColorGenerator.cs +++ b/src/Aspire.Dashboard/Otlp/Model/ColorGenerator.cs @@ -62,20 +62,17 @@ private static (int Red, int Green, int Blue) GetHexRgb(string s) return (r, g, b); } - private int GetColorIndex(string key) - { - return _colorIndexByKey.GetOrAdd(key, k => - { - // GetOrAdd is run outside of the lock. - // Use lazy to ensure that the index is only calculated once for an app. - return new Lazy(() => - { - var i = _currentIndex; - _currentIndex = ++_currentIndex % _colors.Count; - return i; - }); - }).Value; - } + private int GetColorIndex(string key) => _colorIndexByKey.GetOrAdd(key, k => + { + // GetOrAdd is run outside of the lock. + // Use lazy to ensure that the index is only calculated once for an app. + return new Lazy(() => + { + var i = _currentIndex; + _currentIndex = ++_currentIndex % _colors.Count; + return i; + }); + }).Value; public string GetColorHexByKey(string key) { diff --git a/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValue.cs b/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValue.cs index 3936c6c9bf..bb84a5d16a 100644 --- a/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValue.cs +++ b/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValue.cs @@ -6,21 +6,13 @@ namespace Aspire.Dashboard.Otlp.Model.MetricValues; [DebuggerDisplay("Start = {Start}, End = {End}, Value = {Value}")] -public class MetricValue : MetricValueBase where T : struct +public class MetricValue(T value, DateTime start, DateTime end) : MetricValueBase(start, end) where T : struct { - public readonly T Value; - - public MetricValue(T value, DateTime start, DateTime end) : base(start, end) - { - Value = value; - } + public readonly T Value = value; public override string? ToString() => Value.ToString(); - protected override MetricValueBase Clone() - { - return new MetricValue(Value, Start, End); - } + protected override MetricValueBase Clone() => new MetricValue(Value, Start, End); internal override bool TryCompare(MetricValueBase obj, out int comparisonResult) { @@ -34,16 +26,11 @@ internal override bool TryCompare(MetricValueBase obj, out int comparisonResult) return false; } - public override bool Equals(object? obj) - { - return obj is MetricValue other + public override bool Equals(object? obj) => + obj is MetricValue other && Start.Equals(other.Start) && Count == other.Count && Equals(Value, other.Value); - } - public override int GetHashCode() - { - return HashCode.Combine(Start, End, Count, Value); - } + public override int GetHashCode() => HashCode.Combine(Start, End, Count, Value); } diff --git a/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValueBase.cs b/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValueBase.cs index c33afedc06..3f36cf82b7 100644 --- a/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValueBase.cs +++ b/src/Aspire.Dashboard/Otlp/Model/MetricValues/MetricValueBase.cs @@ -18,10 +18,7 @@ protected MetricValueBase(DateTime start, DateTime end) End = end; } - internal static MetricValueBase Clone(MetricValueBase item) - { - return item.Clone(); - } + internal static MetricValueBase Clone(MetricValueBase item) => item.Clone(); internal abstract bool TryCompare(MetricValueBase other, out int comparisonResult); diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpApplication.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpApplication.cs index 707ef1f7a1..c23032433f 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpApplication.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpApplication.cs @@ -123,16 +123,13 @@ public void AddMetrics(AddContext context, RepeatedField scopeMetr } } - private static OtlpInstrumentType MapMetricType(Metric.DataOneofCase data) + private static OtlpInstrumentType MapMetricType(Metric.DataOneofCase data) => data switch { - return data switch - { - Metric.DataOneofCase.Gauge => OtlpInstrumentType.Gauge, - Metric.DataOneofCase.Sum => OtlpInstrumentType.Sum, - Metric.DataOneofCase.Histogram => OtlpInstrumentType.Histogram, - _ => OtlpInstrumentType.Unsupported - }; - } + Metric.DataOneofCase.Gauge => OtlpInstrumentType.Gauge, + Metric.DataOneofCase.Sum => OtlpInstrumentType.Sum, + Metric.DataOneofCase.Histogram => OtlpInstrumentType.Histogram, + _ => OtlpInstrumentType.Unsupported + }; private OtlpMeter GetMeter(InstrumentationScope scope) { diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpHelpers.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpHelpers.cs index 43fc56b6a2..95eeb20c00 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpHelpers.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpHelpers.cs @@ -61,15 +61,9 @@ public static string ToHexString(ReadOnlyMemory bytes) }); } - public static string TruncateString(string value, int maxLength) - { - return value.Length > maxLength ? value[..maxLength] : value; - } + public static string TruncateString(string value, int maxLength) => value.Length > maxLength ? value[..maxLength] : value; - public static string ToHexString(this ByteString bytes) - { - return ToHexString(bytes.Memory); - } + public static string ToHexString(this ByteString bytes) => ToHexString(bytes.Memory); public static string GetString(this AnyValue value) => value.ValueCase switch diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpInstrument.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpInstrument.cs index 2c1697d304..99d29d8d62 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpInstrument.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpInstrument.cs @@ -155,9 +155,7 @@ private sealed class KeyValuePairComparer : IComparer x, KeyValuePair y) - { - return string.Compare(x.Key, y.Key, StringComparison.Ordinal); - } + public int Compare(KeyValuePair x, KeyValuePair y) => + string.Compare(x.Key, y.Key, StringComparison.Ordinal); } } diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpMeter.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpMeter.cs index 2df83c20ef..bcb113b860 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpMeter.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpMeter.cs @@ -8,17 +8,10 @@ namespace Aspire.Dashboard.Otlp.Model; [DebuggerDisplay("MeterName = {MeterName}")] -public class OtlpMeter +public class OtlpMeter(InstrumentationScope scope, TelemetryLimitOptions options) { - public string MeterName { get; init; } - public string Version { get; init; } + public string MeterName { get; init; } = scope.Name; + public string Version { get; init; } = scope.Version; - public ReadOnlyMemory> Attributes { get; } - - public OtlpMeter(InstrumentationScope scope, TelemetryLimitOptions options) - { - MeterName = scope.Name; - Version = scope.Version; - Attributes = scope.Attributes.ToKeyValuePairs(options); - } + public ReadOnlyMemory> Attributes { get; } = scope.Attributes.ToKeyValuePairs(options); } diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpSpan.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpSpan.cs index 5015162f02..7c09dbb205 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpSpan.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpSpan.cs @@ -9,7 +9,7 @@ namespace Aspire.Dashboard.Otlp.Model; /// Represents a Span within an Operation (Trace) /// [DebuggerDisplay("{DebuggerToString(),nq}")] -public class OtlpSpan +public class OtlpSpan(OtlpApplication application, OtlpTrace trace) { public const string PeerServiceAttributeKey = "peer.service"; public const string UrlFullAttributeKey = "url.full"; @@ -20,8 +20,8 @@ public class OtlpSpan public const string SpanKindAttributeKey = "span.kind"; public string TraceId => Trace.TraceId; - public OtlpTrace Trace { get; } - public OtlpApplication Source { get; } + public OtlpTrace Trace { get; } = trace; + public OtlpApplication Source { get; } = application; public required string SpanId { get; init; } public required string? ParentSpanId { get; init; } @@ -42,15 +42,8 @@ public class OtlpSpan public IEnumerable GetChildSpans() => Trace.Spans.Where(s => s.ParentSpanId == SpanId); public OtlpSpan? GetParentSpan() => string.IsNullOrEmpty(ParentSpanId) ? null : Trace.Spans.Where(s => s.SpanId == ParentSpanId).FirstOrDefault(); - public OtlpSpan(OtlpApplication application, OtlpTrace trace) - { - Source = application; - Trace = trace; - } - - public static OtlpSpan Clone(OtlpSpan item, OtlpTrace trace) - { - return new OtlpSpan(item.Source, trace) + public static OtlpSpan Clone(OtlpSpan item, OtlpTrace trace) => + new OtlpSpan(item.Source, trace) { SpanId = item.SpanId, ParentSpanId = item.ParentSpanId, @@ -64,7 +57,6 @@ public static OtlpSpan Clone(OtlpSpan item, OtlpTrace trace) Attributes = item.Attributes, Events = item.Events }; - } public Dictionary AllProperties() { @@ -93,8 +85,6 @@ public Dictionary AllProperties() return props; } - private string DebuggerToString() - { - return $@"SpanId = {SpanId}, StartTime = {StartTime.ToLocalTime():h:mm:ss.fff tt}, ParentSpanId = {ParentSpanId}, TraceId = {Trace.TraceId}"; - } + private string DebuggerToString() => + $@"SpanId = {SpanId}, StartTime = {StartTime.ToLocalTime():h:mm:ss.fff tt}, ParentSpanId = {ParentSpanId}, TraceId = {Trace.TraceId}"; } diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpTrace.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpTrace.cs index 8076d1ca25..37ad3541ec 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpTrace.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpTrace.cs @@ -6,14 +6,14 @@ namespace Aspire.Dashboard.Otlp.Model; [DebuggerDisplay("{DebuggerToString(),nq}")] -public class OtlpTrace +public class OtlpTrace(ReadOnlyMemory traceId, OtlpScope traceScope) { private OtlpSpan? _rootSpan; - public ReadOnlyMemory Key { get; } - public string TraceId { get; } + public ReadOnlyMemory Key { get; } = traceId; + public string TraceId { get; } = OtlpHelpers.ToHexString(traceId); - public string FullName { get; private set; } + public string FullName { get; private set; } = string.Empty; public OtlpSpan FirstSpan => Spans[0]; // There should always be at least one span in a trace. public OtlpSpan? RootSpan => _rootSpan; public TimeSpan Duration @@ -35,7 +35,7 @@ public TimeSpan Duration public List Spans { get; } = new List(); - public OtlpScope TraceScope { get; } + public OtlpScope TraceScope { get; } = traceScope; public int CalculateDepth(OtlpSpan span) { @@ -93,14 +93,6 @@ private void AssertSpanOrder() } } - public OtlpTrace(ReadOnlyMemory traceId, OtlpScope traceScope) - { - Key = traceId; - TraceId = OtlpHelpers.ToHexString(traceId); - TraceScope = traceScope; - FullName = string.Empty; - } - public static OtlpTrace Clone(OtlpTrace trace) { var newTrace = new OtlpTrace(trace.Key, trace.TraceScope); @@ -112,18 +104,13 @@ public static OtlpTrace Clone(OtlpTrace trace) return newTrace; } - private string DebuggerToString() - { - return $@"TraceId = ""{TraceId}"", Spans = {Spans.Count}, StartDate = {FirstSpan.StartTime.ToLocalTime():yyyy:MM:dd}, StartTime = {FirstSpan.StartTime.ToLocalTime():h:mm:ss.fff tt}, Duration = {Duration}"; - } + private string DebuggerToString() => + $@"TraceId = ""{TraceId}"", Spans = {Spans.Count}, StartDate = {FirstSpan.StartTime.ToLocalTime():yyyy:MM:dd}, StartTime = {FirstSpan.StartTime.ToLocalTime():h:mm:ss.fff tt}, Duration = {Duration}"; private sealed class SpanStartDateComparer : IComparer { public static readonly SpanStartDateComparer Instance = new SpanStartDateComparer(); - public int Compare(OtlpSpan? x, OtlpSpan? y) - { - return x!.StartTime.CompareTo(y!.StartTime); - } + public int Compare(OtlpSpan? x, OtlpSpan? y) => x!.StartTime.CompareTo(y!.StartTime); } } diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpTraceCollection.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpTraceCollection.cs index 0c214e8aa7..7db7c73119 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpTraceCollection.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpTraceCollection.cs @@ -12,19 +12,13 @@ public OtlpTraceCollection() : base(MemoryComparable.Instance, dictionaryCreatio } - protected override ReadOnlyMemory GetKeyForItem(OtlpTrace item) - { - return item.Key; - } + protected override ReadOnlyMemory GetKeyForItem(OtlpTrace item) => item.Key; private sealed class MemoryComparable : IEqualityComparer> { public static readonly MemoryComparable Instance = new(); - public bool Equals(ReadOnlyMemory x, ReadOnlyMemory y) - { - return x.Span.SequenceEqual(y.Span); - } + public bool Equals(ReadOnlyMemory x, ReadOnlyMemory y) => x.Span.SequenceEqual(y.Span); public int GetHashCode(ReadOnlyMemory obj) { diff --git a/src/Aspire.Dashboard/Otlp/Model/OtlpUnits.cs b/src/Aspire.Dashboard/Otlp/Model/OtlpUnits.cs index 7b16e6550a..b11367c18f 100644 --- a/src/Aspire.Dashboard/Otlp/Model/OtlpUnits.cs +++ b/src/Aspire.Dashboard/Otlp/Model/OtlpUnits.cs @@ -99,9 +99,8 @@ public static string RemoveAnnotations(string unit) // OTLP metrics use the c/s notation as specified at https://ucum.org/ucum.html // (See also https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/README.md#instrument-units) // OpenMetrics specification for units: https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#units-and-base-units - public static string MapUnit(ReadOnlySpan unit) - { - return unit switch + public static string MapUnit(ReadOnlySpan unit) => + unit switch { // Time "d" => "days", @@ -144,13 +143,11 @@ public static string MapUnit(ReadOnlySpan unit) "$" => "dollars", _ => unit.ToString(), }; - } // The map that translates the "per" unit // Example: s => per second (singular) - public static string MapPerUnit(ReadOnlySpan perUnit) - { - return perUnit switch + public static string MapPerUnit(ReadOnlySpan perUnit) => + perUnit switch { "s" => "second", "m" => "minute", @@ -161,5 +158,4 @@ public static string MapPerUnit(ReadOnlySpan perUnit) "y" => "year", _ => perUnit.ToString(), }; - } } diff --git a/src/Aspire.Dashboard/Otlp/OtlpLogsService.cs b/src/Aspire.Dashboard/Otlp/OtlpLogsService.cs index bd609c8720..9254756fce 100644 --- a/src/Aspire.Dashboard/Otlp/OtlpLogsService.cs +++ b/src/Aspire.Dashboard/Otlp/OtlpLogsService.cs @@ -7,16 +7,10 @@ namespace Aspire.Dashboard.Otlp; -public sealed class OtlpLogsService +public sealed class OtlpLogsService(ILogger logger, TelemetryRepository telemetryRepository) { - private readonly ILogger _logger; - private readonly TelemetryRepository _telemetryRepository; - - public OtlpLogsService(ILogger logger, TelemetryRepository telemetryRepository) - { - _logger = logger; - _telemetryRepository = telemetryRepository; - } + private readonly ILogger _logger = logger; + private readonly TelemetryRepository _telemetryRepository = telemetryRepository; public ExportLogsServiceResponse Export(ExportLogsServiceRequest request) { diff --git a/src/Aspire.Dashboard/Otlp/OtlpMetricsService.cs b/src/Aspire.Dashboard/Otlp/OtlpMetricsService.cs index 36967534a4..68e6653668 100644 --- a/src/Aspire.Dashboard/Otlp/OtlpMetricsService.cs +++ b/src/Aspire.Dashboard/Otlp/OtlpMetricsService.cs @@ -7,23 +7,14 @@ namespace Aspire.Dashboard.Otlp; -public sealed class OtlpMetricsService +public sealed class OtlpMetricsService(ILogger logger, TelemetryRepository telemetryRepository) { - private readonly ILogger _logger; - private readonly TelemetryRepository _telemetryRepository; - - public OtlpMetricsService(ILogger logger, TelemetryRepository telemetryRepository) - { - _logger = logger; - _telemetryRepository = telemetryRepository; - } - public ExportMetricsServiceResponse Export(ExportMetricsServiceRequest request) { var addContext = new AddContext(); - _telemetryRepository.AddMetrics(addContext, request.ResourceMetrics); + telemetryRepository.AddMetrics(addContext, request.ResourceMetrics); - _logger.LogDebug("Processed metrics export. Failure count: {FailureCount}", addContext.FailureCount); + logger.LogDebug("Processed metrics export. Failure count: {FailureCount}", addContext.FailureCount); return new ExportMetricsServiceResponse { diff --git a/src/Aspire.Dashboard/Otlp/OtlpTraceService.cs b/src/Aspire.Dashboard/Otlp/OtlpTraceService.cs index d15f4ebf91..6a4835a1ba 100644 --- a/src/Aspire.Dashboard/Otlp/OtlpTraceService.cs +++ b/src/Aspire.Dashboard/Otlp/OtlpTraceService.cs @@ -7,16 +7,10 @@ namespace Aspire.Dashboard.Otlp; -public sealed class OtlpTraceService +public sealed class OtlpTraceService(ILogger logger, TelemetryRepository telemetryRepository) { - private readonly ILogger _logger; - private readonly TelemetryRepository _telemetryRepository; - - public OtlpTraceService(ILogger logger, TelemetryRepository telemetryRepository) - { - _logger = logger; - _telemetryRepository = telemetryRepository; - } + private readonly ILogger _logger = logger; + private readonly TelemetryRepository _telemetryRepository = telemetryRepository; public ExportTraceServiceResponse Export(ExportTraceServiceRequest request) { diff --git a/src/Aspire.Dashboard/Otlp/Storage/TelemetryRepository.cs b/src/Aspire.Dashboard/Otlp/Storage/TelemetryRepository.cs index 922d458242..f4eed8249b 100644 --- a/src/Aspire.Dashboard/Otlp/Storage/TelemetryRepository.cs +++ b/src/Aspire.Dashboard/Otlp/Storage/TelemetryRepository.cs @@ -178,25 +178,17 @@ public OtlpApplication GetOrAddApplication(Resource resource) } } - public Subscription OnNewApplications(Func callback) - { - return AddSubscription(nameof(OnNewApplications), string.Empty, SubscriptionType.Read, callback, _applicationSubscriptions); - } + public Subscription OnNewApplications(Func callback) => + AddSubscription(nameof(OnNewApplications), string.Empty, SubscriptionType.Read, callback, _applicationSubscriptions); - public Subscription OnNewLogs(string? applicationId, SubscriptionType subscriptionType, Func callback) - { - return AddSubscription(nameof(OnNewLogs), applicationId, subscriptionType, callback, _logSubscriptions); - } + public Subscription OnNewLogs(string? applicationId, SubscriptionType subscriptionType, Func callback) => + AddSubscription(nameof(OnNewLogs), applicationId, subscriptionType, callback, _logSubscriptions); - public Subscription OnNewMetrics(string? applicationId, SubscriptionType subscriptionType, Func callback) - { - return AddSubscription(nameof(OnNewMetrics), applicationId, subscriptionType, callback, _metricsSubscriptions); - } + public Subscription OnNewMetrics(string? applicationId, SubscriptionType subscriptionType, Func callback) => + AddSubscription(nameof(OnNewMetrics), applicationId, subscriptionType, callback, _metricsSubscriptions); - public Subscription OnNewTraces(string? applicationId, SubscriptionType subscriptionType, Func callback) - { - return AddSubscription(nameof(OnNewTraces), applicationId, subscriptionType, callback, _tracesSubscriptions); - } + public Subscription OnNewTraces(string? applicationId, SubscriptionType subscriptionType, Func callback) => + AddSubscription(nameof(OnNewTraces), applicationId, subscriptionType, callback, _tracesSubscriptions); private Subscription AddSubscription(string name, string? applicationId, SubscriptionType subscriptionType, Func callback, List subscriptions) { @@ -511,9 +503,8 @@ private static OtlpSpanStatusCode ConvertStatus(Status? status) }; } - internal static OtlpSpanKind ConvertSpanKind(SpanKind? kind) - { - return kind switch + internal static OtlpSpanKind ConvertSpanKind(SpanKind? kind) => + kind switch { // Unspecified to Internal is intentional. // "Implementations MAY assume SpanKind to be INTERNAL when receiving UNSPECIFIED." @@ -525,7 +516,6 @@ internal static OtlpSpanKind ConvertSpanKind(SpanKind? kind) SpanKind.Consumer => OtlpSpanKind.Consumer, _ => OtlpSpanKind.Unspecified }; - } internal void AddTracesCore(AddContext context, OtlpApplication application, RepeatedField scopeSpans) { diff --git a/src/Aspire.Dashboard/ResourceService/DashboardClient.cs b/src/Aspire.Dashboard/ResourceService/DashboardClient.cs index 9584a327ce..492076063a 100644 --- a/src/Aspire.Dashboard/ResourceService/DashboardClient.cs +++ b/src/Aspire.Dashboard/ResourceService/DashboardClient.cs @@ -391,12 +391,9 @@ Task IDashboardClient.WhenConnected } } - string IDashboardClient.ApplicationName - { - get => _applicationName + string IDashboardClient.ApplicationName => _applicationName ?? _dashboardOptions.ApplicationName ?? "Aspire"; - } async Task IDashboardClient.SubscribeResourcesAsync(CancellationToken cancellationToken) { diff --git a/src/Aspire.Dashboard/ResourceService/Partials.cs b/src/Aspire.Dashboard/ResourceService/Partials.cs index 570a7f8c10..742a0e6875 100644 --- a/src/Aspire.Dashboard/ResourceService/Partials.cs +++ b/src/Aspire.Dashboard/ResourceService/Partials.cs @@ -31,29 +31,21 @@ public ResourceViewModel ToViewModel() Commands = GetCommands() }; - ImmutableArray GetEnvironment() - { - return Environment + ImmutableArray GetEnvironment() => Environment .Select(e => new EnvironmentVariableViewModel(e.Name, e.Value, e.IsFromSpec)) .ToImmutableArray(); - } - ImmutableArray GetUrls() - { + ImmutableArray GetUrls() => // Filter out bad urls - return (from u in Urls - let parsedUri = Uri.TryCreate(u.FullUrl, UriKind.Absolute, out var uri) ? uri : null - where parsedUri != null - select new UrlViewModel(u.Name, parsedUri, u.IsInternal)) + (from u in Urls + let parsedUri = Uri.TryCreate(u.FullUrl, UriKind.Absolute, out var uri) ? uri : null + where parsedUri != null + select new UrlViewModel(u.Name, parsedUri, u.IsInternal)) .ToImmutableArray(); - } - ImmutableArray GetCommands() - { - return Commands + ImmutableArray GetCommands() => Commands .Select(c => new CommandViewModel(c.CommandType, c.DisplayName, c.ConfirmationMessage, c.Parameter)) .ToImmutableArray(); - } T ValidateNotNull(T value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class { @@ -69,12 +61,9 @@ T ValidateNotNull(T value, [CallerArgumentExpression(nameof(value))] string? partial class ResourceCommandResponse { - public ResourceCommandResponseViewModel ToViewModel() + public ResourceCommandResponseViewModel ToViewModel() => new ResourceCommandResponseViewModel() { - return new ResourceCommandResponseViewModel() - { - ErrorMessage = ErrorMessage, - Kind = (Dashboard.Model.ResourceCommandResponseKind)Kind - }; - } + ErrorMessage = ErrorMessage, + Kind = (Dashboard.Model.ResourceCommandResponseKind)Kind + }; } diff --git a/src/Aspire.Dashboard/ShortcutManager.cs b/src/Aspire.Dashboard/ShortcutManager.cs index 61ef641dbe..22e40a68b4 100644 --- a/src/Aspire.Dashboard/ShortcutManager.cs +++ b/src/Aspire.Dashboard/ShortcutManager.cs @@ -12,15 +12,9 @@ public sealed class ShortcutManager(ILoggerFactory loggerFactory) : IDisposable private readonly ConcurrentDictionary _keydownListenerComponents = []; private readonly ILogger _logger = loggerFactory.CreateLogger(); - public void AddGlobalKeydownListener(IGlobalKeydownListener listener) - { - _keydownListenerComponents[listener] = listener; - } + public void AddGlobalKeydownListener(IGlobalKeydownListener listener) => _keydownListenerComponents[listener] = listener; - public void RemoveGlobalKeydownListener(IGlobalKeydownListener listener) - { - _keydownListenerComponents.Remove(listener, out _); - } + public void RemoveGlobalKeydownListener(IGlobalKeydownListener listener) => _keydownListenerComponents.Remove(listener, out _); [JSInvokable] public Task OnGlobalKeyDown(AspireKeyboardShortcut shortcut) @@ -33,8 +27,5 @@ public Task OnGlobalKeyDown(AspireKeyboardShortcut shortcut) return Task.WhenAll(componentsSubscribedToShortcut.Select(component => component.OnPageKeyDownAsync(shortcut))); } - public void Dispose() - { - _keydownListenerComponents.Clear(); - } + public void Dispose() => _keydownListenerComponents.Clear(); } diff --git a/src/Aspire.Dashboard/Utils/CancellationSeries.cs b/src/Aspire.Dashboard/Utils/CancellationSeries.cs index 89dc164e14..65ea3ab4bc 100644 --- a/src/Aspire.Dashboard/Utils/CancellationSeries.cs +++ b/src/Aspire.Dashboard/Utils/CancellationSeries.cs @@ -50,10 +50,7 @@ public async Task NextAsync() /// at which point there's something to cancel. /// /// - public Task ClearAsync() - { - return Next(null); - } + public Task ClearAsync() => Next(null); private async Task Next(CancellationTokenSource? next) { diff --git a/src/Aspire.Dashboard/Utils/DashboardUrls.cs b/src/Aspire.Dashboard/Utils/DashboardUrls.cs index b51655dca8..224eb4136d 100644 --- a/src/Aspire.Dashboard/Utils/DashboardUrls.cs +++ b/src/Aspire.Dashboard/Utils/DashboardUrls.cs @@ -13,10 +13,7 @@ internal static class DashboardUrls public const string StructuredLogsBasePath = "structuredlogs"; public const string TracesBasePath = "traces"; - public static string ResourcesUrl() - { - return "/"; - } + public static string ResourcesUrl() => "/"; public static string ConsoleLogsUrl(string? resource = null) { @@ -96,10 +93,7 @@ public static string TracesUrl(string? resource = null) return url; } - public static string TraceDetailUrl(string traceId) - { - return $"/{TracesBasePath}/detail/{Uri.EscapeDataString(traceId)}"; - } + public static string TraceDetailUrl(string traceId) => $"/{TracesBasePath}/detail/{Uri.EscapeDataString(traceId)}"; public static string LoginUrl(string? returnUrl = null, string? token = null) { diff --git a/src/Shared/CircularBuffer.cs b/src/Shared/CircularBuffer.cs index ce731bb5a3..65cb59e12f 100644 --- a/src/Shared/CircularBuffer.cs +++ b/src/Shared/CircularBuffer.cs @@ -244,10 +244,7 @@ public IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - private int InternalIndex(int index) - { - return (_start + index) % _buffer.Count; - } + private int InternalIndex(int index) => (_start + index) % _buffer.Count; private void Increment(ref int index) { diff --git a/src/Shared/IConfigurationExtensions.cs b/src/Shared/IConfigurationExtensions.cs index f4eb22f68f..6e32767f70 100644 --- a/src/Shared/IConfigurationExtensions.cs +++ b/src/Shared/IConfigurationExtensions.cs @@ -47,10 +47,8 @@ internal static class IConfigurationExtensions /// The configuration key. /// A default value, for when the configuration value is unspecified or white space. /// - public static bool GetBool(this IConfiguration configuration, string key, bool defaultValue) - { - return configuration.GetBool(key) ?? defaultValue; - } + public static bool GetBool(this IConfiguration configuration, string key, bool defaultValue) => + configuration.GetBool(key) ?? defaultValue; /// /// Parses a configuration value into a object. diff --git a/src/Shared/TaskHelpers.cs b/src/Shared/TaskHelpers.cs index ee0be71ce6..e5daca05d5 100644 --- a/src/Shared/TaskHelpers.cs +++ b/src/Shared/TaskHelpers.cs @@ -7,15 +7,10 @@ namespace Aspire.Dashboard.Utils; internal static class TaskHelpers { - public static Task WaitIgnoreCancelAsync(Task? task) - { - return WaitIgnoreCancelCoreAsync(task, logger: null, logMessage: null); - } + public static Task WaitIgnoreCancelAsync(Task? task) => WaitIgnoreCancelCoreAsync(task, logger: null, logMessage: null); - public static Task WaitIgnoreCancelAsync(Task? task, ILogger logger, string logMessage) - { - return WaitIgnoreCancelCoreAsync(task, logger, logMessage); - } + public static Task WaitIgnoreCancelAsync(Task? task, ILogger logger, string logMessage) => + WaitIgnoreCancelCoreAsync(task, logger, logMessage); private static async Task WaitIgnoreCancelCoreAsync(Task? task, ILogger? logger = null, string? logMessage = null) { diff --git a/src/Shared/TokenGenerator.cs b/src/Shared/TokenGenerator.cs index 474680f506..6b3585aa41 100644 --- a/src/Shared/TokenGenerator.cs +++ b/src/Shared/TokenGenerator.cs @@ -22,10 +22,9 @@ public static string GenerateToken() return tokenHex; } - private static byte[] GenerateEntropyToken(int size) - { + private static byte[] GenerateEntropyToken(int size) => #if NET6_0_OR_GREATER - return RandomNumberGenerator.GetBytes(size); + RandomNumberGenerator.GetBytes(size); #else using (var rng = new RNGCryptoServiceProvider()) { @@ -34,5 +33,5 @@ private static byte[] GenerateEntropyToken(int size) return token; } #endif - } + } From 0ce45e64483d47b517c975de10486461d1320f11 Mon Sep 17 00:00:00 2001 From: Khanbala Rashidov <50279392+KhanbalaRashidov@users.noreply.github.com> Date: Tue, 2 Jul 2024 15:58:48 +0400 Subject: [PATCH 3/5] Refactoring Aspire.Hosting --- .../ApplicationModel/HostUrl.cs | 5 +- .../ApplicationModel/ReferenceExpression.cs | 35 +++--------- .../ApplicationModel/Resource.cs | 5 +- .../ApplicationModel/ResourceExtensions.cs | 24 +++----- .../ApplicationModel/ResourceLoggerService.cs | 9 +-- .../ResourceNotificationService.cs | 10 +--- .../ContainerResourceBuilderExtensions.cs | 32 ++++------- .../ContainerResourceExtensions.cs | 5 +- .../ConsoleLogsConfigurationExtensions.cs | 7 +-- .../Dashboard/DashboardServiceData.cs | 5 +- .../Dashboard/ResourceServiceOptions.cs | 6 +- src/Aspire.Hosting/Dcp/ApplicationExecutor.cs | 26 ++------- src/Aspire.Hosting/Dcp/DcpHostService.cs | 49 ++++++---------- src/Aspire.Hosting/Dcp/DcpKubernetesClient.cs | 20 ++----- src/Aspire.Hosting/Dcp/DcpOptions.cs | 6 +- .../Dcp/HostDashboardEndpointProvider.cs | 9 +-- .../Dcp/Model/ExecutableReplicaSet.cs | 6 +- src/Aspire.Hosting/Dcp/Model/ModelCommon.cs | 11 +--- src/Aspire.Hosting/Dcp/Model/Schema.cs | 10 +--- .../Dcp/Process/ProcessResult.cs | 9 +-- src/Aspire.Hosting/Dcp/Process/ProcessSpec.cs | 9 +-- src/Aspire.Hosting/DistributedApplication.cs | 20 ++----- .../DistributedApplicationBuilder.cs | 10 +--- .../DistributedApplicationLifecycle.cs | 20 ++----- .../DistributedApplicationOptions.cs | 11 +--- .../ExecutableResourceBuilderExtensions.cs | 6 +- .../ExecutableResourceExtensions.cs | 6 +- .../IDistributedApplicationLifecycleHook.cs | 15 +---- ...ifecycleHookServiceCollectionExtensions.cs | 16 ++---- .../ParameterResourceBuilderExtensions.cs | 6 +- .../ProjectResourceBuilderExtensions.cs | 36 +++++------- .../Publishing/PortAllocator.cs | 5 +- .../ResourceBuilderExtensions.cs | 57 +++++++------------ 33 files changed, 145 insertions(+), 361 deletions(-) diff --git a/src/Aspire.Hosting/ApplicationModel/HostUrl.cs b/src/Aspire.Hosting/ApplicationModel/HostUrl.cs index 0abe5a1a6b..dd9740610a 100644 --- a/src/Aspire.Hosting/ApplicationModel/HostUrl.cs +++ b/src/Aspire.Hosting/ApplicationModel/HostUrl.cs @@ -13,8 +13,5 @@ public record HostUrl(string Url) : IValueProvider, IManifestExpressionProvider string IManifestExpressionProvider.ValueExpression => Url; // Returns the url - ValueTask IValueProvider.GetValueAsync(System.Threading.CancellationToken cancellationToken) - { - return new(Url); - } + ValueTask IValueProvider.GetValueAsync(System.Threading.CancellationToken cancellationToken) => new(Url); } diff --git a/src/Aspire.Hosting/ApplicationModel/ReferenceExpression.cs b/src/Aspire.Hosting/ApplicationModel/ReferenceExpression.cs index dcf032ddef..cf039f9f2c 100644 --- a/src/Aspire.Hosting/ApplicationModel/ReferenceExpression.cs +++ b/src/Aspire.Hosting/ApplicationModel/ReferenceExpression.cs @@ -101,19 +101,13 @@ public ref struct ExpressionInterpolatedStringHandler(int literalLength, int for /// Appends a literal value to the expression. /// /// The literal string value to be appended to the interpolated string. - public readonly void AppendLiteral(string value) - { - _builder.Append(value); - } + public readonly void AppendLiteral(string value) => _builder.Append(value); /// /// Appends a formatted value to the expression. /// /// The formatted string to be appended to the interpolated string. - public readonly void AppendFormatted(string? value) - { - _builder.Append(value); - } + public readonly void AppendFormatted(string? value) => _builder.Append(value); /// /// Appends a formatted value to the expression. The value must implement and . @@ -160,19 +154,13 @@ public void Append([InterpolatedStringHandlerArgument("")] in ReferenceExpressio /// Appends a literal value to the expression. /// /// The literal string value to be appended to the interpolated string. - public void AppendLiteral(string value) - { - _builder.Append(value); - } + public void AppendLiteral(string value) => _builder.Append(value); /// /// Appends a formatted value to the expression. /// /// The formatted string to be appended to the interpolated string. - public void AppendFormatted(string? value) - { - _builder.Append(value); - } + public void AppendFormatted(string? value) => _builder.Append(value); /// /// Appends a formatted value to the expression. The value must implement and . @@ -210,28 +198,19 @@ public ref struct ReferenceExpressionBuilderInterpolatedStringHandler(int litera /// Appends a literal value to the expression. /// /// The literal string value to be appended to the interpolated string. - public readonly void AppendLiteral(string value) - { - builder.AppendLiteral(value); - } + public readonly void AppendLiteral(string value) => builder.AppendLiteral(value); /// /// Appends a formatted value to the expression. /// /// The formatted string to be appended to the interpolated string. - public readonly void AppendFormatted(string? value) - { - builder.AppendFormatted(value); - } + public readonly void AppendFormatted(string? value) => builder.AppendFormatted(value); /// /// Appends a formatted value to the expression. The value must implement and . /// /// An instance of an object which implements and . /// - public void AppendFormatted(T valueProvider) where T : IValueProvider, IManifestExpressionProvider - { - builder.AppendFormatted(valueProvider); - } + public readonly void AppendFormatted(T valueProvider) where T : IValueProvider, IManifestExpressionProvider => builder.AppendFormatted(valueProvider); } } diff --git a/src/Aspire.Hosting/ApplicationModel/Resource.cs b/src/Aspire.Hosting/ApplicationModel/Resource.cs index d01176cae8..dfbfe05ce7 100644 --- a/src/Aspire.Hosting/ApplicationModel/Resource.cs +++ b/src/Aspire.Hosting/ApplicationModel/Resource.cs @@ -32,8 +32,5 @@ protected Resource(string name) Name = name; } - private string DebuggerToString() - { - return $@"Type = {GetType().Name}, Name = ""{Name}"", Annotations = {Annotations.Count}"; - } + private string DebuggerToString() => $@"Type = {GetType().Name}, Name = ""{Name}"", Annotations = {Annotations.Count}"; } diff --git a/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs b/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs index 2ec34b5063..6615fc542f 100644 --- a/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs +++ b/src/Aspire.Hosting/ApplicationModel/ResourceExtensions.cs @@ -60,10 +60,8 @@ public static bool TryGetAnnotationsOfType(this IResource resource, [NotNullW /// The resource to get the environment variables from. /// The environment variables retrieved from the resource, if any. /// True if the environment variables were successfully retrieved, false otherwise. - public static bool TryGetEnvironmentVariables(this IResource resource, [NotNullWhen(true)] out IEnumerable? environmentVariables) - { - return TryGetAnnotationsOfType(resource, out environmentVariables); - } + public static bool TryGetEnvironmentVariables(this IResource resource, [NotNullWhen(true)] out IEnumerable? environmentVariables) => + TryGetAnnotationsOfType(resource, out environmentVariables); /// /// Attempts to get the container mounts for the specified resource. @@ -71,10 +69,8 @@ public static bool TryGetEnvironmentVariables(this IResource resource, [NotNullW /// The resource to get the volume mounts for. /// When this method returns, contains the volume mounts for the specified resource, if found; otherwise, null. /// true if the volume mounts were successfully retrieved; otherwise, false. - public static bool TryGetContainerMounts(this IResource resource, [NotNullWhen(true)] out IEnumerable? volumeMounts) - { - return TryGetAnnotationsOfType(resource, out volumeMounts); - } + public static bool TryGetContainerMounts(this IResource resource, [NotNullWhen(true)] out IEnumerable? volumeMounts) => + TryGetAnnotationsOfType(resource, out volumeMounts); /// /// Attempts to retrieve the endpoints for the given resource. @@ -82,10 +78,8 @@ public static bool TryGetContainerMounts(this IResource resource, [NotNullWhen(t /// The resource to retrieve the endpoints for. /// The endpoints for the given resource, if found. /// True if the endpoints were found, false otherwise. - public static bool TryGetEndpoints(this IResource resource, [NotNullWhen(true)] out IEnumerable? endpoints) - { - return TryGetAnnotationsOfType(resource, out endpoints); - } + public static bool TryGetEndpoints(this IResource resource, [NotNullWhen(true)] out IEnumerable? endpoints) => + TryGetAnnotationsOfType(resource, out endpoints); /// /// Gets the endpoints for the specified resource. @@ -109,10 +103,8 @@ public static IEnumerable GetEndpoints(this IResourceWithEndp /// The name of the endpoint. /// An object representing the endpoint reference /// for the specified endpoint. - public static EndpointReference GetEndpoint(this IResourceWithEndpoints resource, string endpointName) - { - return new EndpointReference(resource, endpointName); - } + public static EndpointReference GetEndpoint(this IResourceWithEndpoints resource, string endpointName) => + new EndpointReference(resource, endpointName); /// /// Attempts to get the container image name from the given resource. diff --git a/src/Aspire.Hosting/ApplicationModel/ResourceLoggerService.cs b/src/Aspire.Hosting/ApplicationModel/ResourceLoggerService.cs index 4a065cd1cb..11e083cb6b 100644 --- a/src/Aspire.Hosting/ApplicationModel/ResourceLoggerService.cs +++ b/src/Aspire.Hosting/ApplicationModel/ResourceLoggerService.cs @@ -181,10 +181,7 @@ private sealed class ResourceLoggerState /// /// Creates a new . /// - public ResourceLoggerState() - { - _logger = new ResourceLogger(this); - } + public ResourceLoggerState() => _logger = new ResourceLogger(this); private Action? _onSubscribersChanged; public event Action OnSubscribersChanged @@ -313,11 +310,9 @@ private event Action OnNewLog /// /// Close the log stream for the resource. Future subscribers will not receive any updates and will complete immediately. /// - public void Complete() - { + public void Complete() => // REVIEW: Do we clean up the backlog? _logStreamCts.Cancel(); - } public void ClearBacklog() { diff --git a/src/Aspire.Hosting/ApplicationModel/ResourceNotificationService.cs b/src/Aspire.Hosting/ApplicationModel/ResourceNotificationService.cs index 7f87edb878..a942caf2cd 100644 --- a/src/Aspire.Hosting/ApplicationModel/ResourceNotificationService.cs +++ b/src/Aspire.Hosting/ApplicationModel/ResourceNotificationService.cs @@ -34,10 +34,8 @@ public class ResourceNotificationService Use the constructor that accepts an {nameof(ILogger)}<{nameof(ResourceNotificationService)}> and {nameof(IHostApplicationLifetime)}. This constructor will be removed in the next major version of Aspire. """)] - public ResourceNotificationService(ILogger logger) - { + public ResourceNotificationService(ILogger logger) => _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } /// /// Creates a new instance of . @@ -198,10 +196,8 @@ public Task PublishUpdateAsync(IResource resource, string resourceId, Func /// The resource to update /// A factory that creates the new state based on the previous state. - public Task PublishUpdateAsync(IResource resource, Func stateFactory) - { - return PublishUpdateAsync(resource, resource.Name, stateFactory); - } + public Task PublishUpdateAsync(IResource resource, Func stateFactory) => + PublishUpdateAsync(resource, resource.Name, stateFactory); private static CustomResourceSnapshot GetCurrentSnapshot(IResource resource, ResourceNotificationState notificationState) { diff --git a/src/Aspire.Hosting/ContainerResourceBuilderExtensions.cs b/src/Aspire.Hosting/ContainerResourceBuilderExtensions.cs index 003ee86f0f..63a12f7075 100644 --- a/src/Aspire.Hosting/ContainerResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting/ContainerResourceBuilderExtensions.cs @@ -18,10 +18,8 @@ public static class ContainerResourceBuilderExtensions /// The name of the resource. /// The container image name. The tag is assumed to be "latest". /// The for chaining. - public static IResourceBuilder AddContainer(this IDistributedApplicationBuilder builder, string name, string image) - { - return builder.AddContainer(name, image, "latest"); - } + public static IResourceBuilder AddContainer(this IDistributedApplicationBuilder builder, string name, string image) => + builder.AddContainer(name, image, "latest"); /// /// Adds a container resource to the application. @@ -181,10 +179,8 @@ public static IResourceBuilder WithImageSHA256(this IResourceBuilder bu /// Builder for the container resource. /// The arguments to be passed to the container runtime run command when the container resource is started. /// The . - public static IResourceBuilder WithContainerRuntimeArgs(this IResourceBuilder builder, params string[] args) where T : ContainerResource - { - return builder.WithContainerRuntimeArgs(context => context.Args.AddRange(args)); - } + public static IResourceBuilder WithContainerRuntimeArgs(this IResourceBuilder builder, params string[] args) where T : ContainerResource => + builder.WithContainerRuntimeArgs(context => context.Args.AddRange(args)); /// /// Adds a callback to be executed with a list of arguments to add to the container runtime run command when a container resource is started. @@ -197,13 +193,11 @@ public static IResourceBuilder WithContainerRuntimeArgs(this IResourceBuil /// A callback that allows for deferred execution for computing arguments. This runs after resources have been allocation by the orchestrator and allows access to other resources to resolve computed data, e.g. connection strings, ports. /// The . public static IResourceBuilder WithContainerRuntimeArgs(this IResourceBuilder builder, Action callback) where T : ContainerResource - { - return builder.WithContainerRuntimeArgs(context => + => builder.WithContainerRuntimeArgs(context => { callback(context); return Task.CompletedTask; }); - } /// /// Adds a callback to be executed with a list of arguments to add to the container runtime run command when a container resource is started. @@ -221,20 +215,16 @@ public static IResourceBuilder WithContainerRuntimeArgs(this IResourceBuil return builder.WithAnnotation(annotation); } - private static IResourceBuilder ThrowResourceIsNotContainer(IResourceBuilder builder) where T : ContainerResource - { + private static IResourceBuilder ThrowResourceIsNotContainer(IResourceBuilder builder) where T : ContainerResource => throw new InvalidOperationException($"The resource '{builder.Resource.Name}' does not have a container image specified. Use WithImage to specify the container image and tag."); - } /// /// Changes the resource to be published as a container in the manifest. /// /// Resource builder. /// A reference to the . - public static IResourceBuilder PublishAsContainer(this IResourceBuilder builder) where T : ContainerResource - { - return builder.WithManifestPublishingCallback(context => context.WriteContainerAsync(builder.Resource)); - } + public static IResourceBuilder PublishAsContainer(this IResourceBuilder builder) where T : ContainerResource => + builder.WithManifestPublishingCallback(context => context.WriteContainerAsync(builder.Resource)); /// /// Causes .NET Aspire to build the specified container image from a Dockerfile. @@ -328,11 +318,9 @@ public static IResourceBuilder WithDockerfile(this IResourceBuilder bui /// builder.Build().Run(); /// /// - public static IResourceBuilder AddDockerfile(this IDistributedApplicationBuilder builder, string name, string contextPath, string? dockerfilePath = null, string? stage = null) - { - return builder.AddContainer(name, "placeholder") // Image name will be replaced by WithDockerfile. + public static IResourceBuilder AddDockerfile(this IDistributedApplicationBuilder builder, string name, string contextPath, string? dockerfilePath = null, string? stage = null) => + builder.AddContainer(name, "placeholder") // Image name will be replaced by WithDockerfile. .WithDockerfile(contextPath, dockerfilePath, stage); - } /// /// Adds a build argument when the container is build from a Dockerfile. diff --git a/src/Aspire.Hosting/ContainerResourceExtensions.cs b/src/Aspire.Hosting/ContainerResourceExtensions.cs index 5c520aea8b..21eb694b19 100644 --- a/src/Aspire.Hosting/ContainerResourceExtensions.cs +++ b/src/Aspire.Hosting/ContainerResourceExtensions.cs @@ -31,8 +31,5 @@ public static IEnumerable GetContainerResources(this DistributedAppli /// /// The resource to check. /// true if the specified resource is a container resource; otherwise, false. - public static bool IsContainer(this IResource resource) - { - return resource.Annotations.OfType().Any(); - } + public static bool IsContainer(this IResource resource) => resource.Annotations.OfType().Any(); } diff --git a/src/Aspire.Hosting/Dashboard/ConsoleLogsConfigurationExtensions.cs b/src/Aspire.Hosting/Dashboard/ConsoleLogsConfigurationExtensions.cs index be04615ff0..2d6a76c5fa 100644 --- a/src/Aspire.Hosting/Dashboard/ConsoleLogsConfigurationExtensions.cs +++ b/src/Aspire.Hosting/Dashboard/ConsoleLogsConfigurationExtensions.cs @@ -7,9 +7,8 @@ namespace Aspire.Hosting.Dashboard; internal static class ConsoleLogsConfigurationExtensions { - internal static IResourceBuilder ConfigureConsoleLogs(this IResourceBuilder builder) where T : IResourceWithEnvironment - { - return builder.WithEnvironment((context) => + internal static IResourceBuilder ConfigureConsoleLogs(this IResourceBuilder builder) where T : IResourceWithEnvironment => + builder.WithEnvironment((context) => { if (context.ExecutionContext.IsPublishMode) { @@ -22,5 +21,5 @@ internal static IResourceBuilder ConfigureConsoleLogs(this IResourceBuilde context.EnvironmentVariables["LOGGING__CONSOLE__FORMATTERNAME"] = "simple"; context.EnvironmentVariables["LOGGING__CONSOLE__FORMATTEROPTIONS__TIMESTAMPFORMAT"] = $"{KnownFormats.ConsoleLogsTimestampFormat} "; }); - } + } diff --git a/src/Aspire.Hosting/Dashboard/DashboardServiceData.cs b/src/Aspire.Hosting/Dashboard/DashboardServiceData.cs index 96776ba402..07ad3ecd26 100644 --- a/src/Aspire.Hosting/Dashboard/DashboardServiceData.cs +++ b/src/Aspire.Hosting/Dashboard/DashboardServiceData.cs @@ -77,10 +77,7 @@ public async ValueTask DisposeAsync() _cts.Dispose(); } - internal ResourceSnapshotSubscription SubscribeResources() - { - return _resourcePublisher.Subscribe(); - } + internal ResourceSnapshotSubscription SubscribeResources() => _resourcePublisher.Subscribe(); internal IAsyncEnumerable>? SubscribeConsoleLogs(string resourceName) { diff --git a/src/Aspire.Hosting/Dashboard/ResourceServiceOptions.cs b/src/Aspire.Hosting/Dashboard/ResourceServiceOptions.cs index fcf487c019..20f3d46f5c 100644 --- a/src/Aspire.Hosting/Dashboard/ResourceServiceOptions.cs +++ b/src/Aspire.Hosting/Dashboard/ResourceServiceOptions.cs @@ -33,10 +33,8 @@ public string? ApiKey } } - internal byte[] GetApiKeyBytes() - { - return _apiKeyBytes ?? throw new InvalidOperationException($"AppHost:ResourceService:ApiKey is not specified in configuration."); - } + internal byte[] GetApiKeyBytes() => + _apiKeyBytes ?? throw new InvalidOperationException($"AppHost:ResourceService:ApiKey is not specified in configuration."); } internal sealed class ValidateResourceServiceOptions : IValidateOptions diff --git a/src/Aspire.Hosting/Dcp/ApplicationExecutor.cs b/src/Aspire.Hosting/Dcp/ApplicationExecutor.cs index 767e855645..55704a8607 100644 --- a/src/Aspire.Hosting/Dcp/ApplicationExecutor.cs +++ b/src/Aspire.Hosting/Dcp/ApplicationExecutor.cs @@ -24,18 +24,12 @@ namespace Aspire.Hosting.Dcp; -internal class AppResource +internal class AppResource(IResource modelResource, CustomResource dcpResource) { - public IResource ModelResource { get; } - public CustomResource DcpResource { get; } + public IResource ModelResource { get; } = modelResource; + public CustomResource DcpResource { get; } = dcpResource; public virtual List ServicesProduced { get; } = []; public virtual List ServicesConsumed { get; } = []; - - public AppResource(IResource modelResource, CustomResource dcpResource) - { - ModelResource = modelResource; - DcpResource = dcpResource; - } } internal sealed class ServiceAppResource : AppResource @@ -43,19 +37,11 @@ internal sealed class ServiceAppResource : AppResource public Service Service => (Service)DcpResource; public EndpointAnnotation EndpointAnnotation { get; } - public override List ServicesProduced - { - get { throw new InvalidOperationException("Service resources do not produce any services"); } - } - public override List ServicesConsumed - { - get { throw new InvalidOperationException("Service resources do not consume any services"); } - } + public override List ServicesProduced => throw new InvalidOperationException("Service resources do not produce any services"); + public override List ServicesConsumed => throw new InvalidOperationException("Service resources do not consume any services"); - public ServiceAppResource(IResource modelResource, Service service, EndpointAnnotation sba) : base(modelResource, service) - { + public ServiceAppResource(IResource modelResource, Service service, EndpointAnnotation sba) : base(modelResource, service) => EndpointAnnotation = sba; - } } internal sealed class ApplicationExecutor(ILogger logger, diff --git a/src/Aspire.Hosting/Dcp/DcpHostService.cs b/src/Aspire.Hosting/Dcp/DcpHostService.cs index 3578c44e82..ca085cbbe7 100644 --- a/src/Aspire.Hosting/Dcp/DcpHostService.cs +++ b/src/Aspire.Hosting/Dcp/DcpHostService.cs @@ -14,16 +14,22 @@ namespace Aspire.Hosting.Dcp; -internal sealed class DcpHostService : IHostedLifecycleService, IAsyncDisposable +internal sealed class DcpHostService( + ILoggerFactory loggerFactory, + IOptions dcpOptions, + DistributedApplicationExecutionContext executionContext, + ApplicationExecutor appExecutor, + IDcpDependencyCheckService dependencyCheckService, + Locations locations) : IHostedLifecycleService, IAsyncDisposable { private const int LoggingSocketConnectionBacklog = 3; - private readonly ApplicationExecutor _appExecutor; - private readonly ILoggerFactory _loggerFactory; - private readonly ILogger _logger; - private readonly DcpOptions _dcpOptions; - private readonly DistributedApplicationExecutionContext _executionContext; - private readonly IDcpDependencyCheckService _dependencyCheckService; - private readonly Locations _locations; + private readonly ApplicationExecutor _appExecutor = appExecutor; + private readonly ILoggerFactory _loggerFactory = loggerFactory; + private readonly ILogger _logger = loggerFactory.CreateLogger(); + private readonly DcpOptions _dcpOptions = dcpOptions.Value; + private readonly DistributedApplicationExecutionContext _executionContext = executionContext; + private readonly IDcpDependencyCheckService _dependencyCheckService = dependencyCheckService; + private readonly Locations _locations = locations; private readonly CancellationTokenSource _shutdownCts = new(); private Task? _logProcessorTask; private IAsyncDisposable? _dcpRunDisposable; @@ -37,23 +43,6 @@ internal sealed class DcpHostService : IHostedLifecycleService, IAsyncDisposable "DOTNET_ENVIRONMENT" }; - public DcpHostService( - ILoggerFactory loggerFactory, - IOptions dcpOptions, - DistributedApplicationExecutionContext executionContext, - ApplicationExecutor appExecutor, - IDcpDependencyCheckService dependencyCheckService, - Locations locations) - { - _loggerFactory = loggerFactory; - _logger = loggerFactory.CreateLogger(); - _dcpOptions = dcpOptions.Value; - _executionContext = executionContext; - _appExecutor = appExecutor; - _dependencyCheckService = dependencyCheckService; - _locations = locations; - } - private bool IsSupported => !_executionContext.IsPublishMode; public async Task StartAsync(CancellationToken cancellationToken = default) @@ -354,13 +343,7 @@ public Task StartingAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public Task StoppedAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask; - public Task StoppingAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task StoppingAsync(CancellationToken cancellationToken) => Task.CompletedTask; } diff --git a/src/Aspire.Hosting/Dcp/DcpKubernetesClient.cs b/src/Aspire.Hosting/Dcp/DcpKubernetesClient.cs index 2f4ac5e5f7..3db0ed32ca 100644 --- a/src/Aspire.Hosting/Dcp/DcpKubernetesClient.cs +++ b/src/Aspire.Hosting/Dcp/DcpKubernetesClient.cs @@ -9,11 +9,8 @@ namespace Aspire.Hosting.Dcp; // We need to create a custom Kubernetes client to support reading arbitrary subresources from a Kubernetes resource as a stream. // k8s.Kubernetes does not support this operation natively, and required machinery (SendRequest() in particular) is protected. -internal sealed class DcpKubernetesClient : k8s.Kubernetes +internal sealed class DcpKubernetesClient(KubernetesClientConfiguration config, params DelegatingHandler[] handlers) : k8s.Kubernetes(config, handlers) { - public DcpKubernetesClient(KubernetesClientConfiguration config, params DelegatingHandler[] handlers) : base(config, handlers) - { - } /// /// Asynchronously reads a sub-resource from a Kubernetes resource as a stream. @@ -83,20 +80,11 @@ private sealed class QueryBuilder { private readonly List _parameters = new List(); - public void Append(string key, int val) - { - _parameters.Add($"{key}={val}"); - } + public void Append(string key, int val) => _parameters.Add($"{key}={val}"); - public void Append(string key, bool? val) - { - _parameters.Add($"{key}={(val == true ? "true" : "false")}"); - } + public void Append(string key, bool? val) => _parameters.Add($"{key}={(val == true ? "true" : "false")}"); - public void Append(string key, string val) - { - _parameters.Add($"{key}={Uri.EscapeDataString(val)}"); - } + public void Append(string key, string val) => _parameters.Add($"{key}={Uri.EscapeDataString(val)}"); public override string ToString() { diff --git a/src/Aspire.Hosting/Dcp/DcpOptions.cs b/src/Aspire.Hosting/Dcp/DcpOptions.cs index 24968aa22d..4d29fba8e1 100644 --- a/src/Aspire.Hosting/Dcp/DcpOptions.cs +++ b/src/Aspire.Hosting/Dcp/DcpOptions.cs @@ -164,8 +164,6 @@ public void Configure(DcpOptions options) options.ServiceStartupWatchTimeout = configuration.GetValue("DOTNET_ASPIRE_SERVICE_STARTUP_WATCH_TIMEOUT", options.ServiceStartupWatchTimeout); } - private static string? GetMetadataValue(IEnumerable? assemblyMetadata, string key) - { - return assemblyMetadata?.FirstOrDefault(m => string.Equals(m.Key, key, StringComparison.OrdinalIgnoreCase))?.Value; - } + private static string? GetMetadataValue(IEnumerable? assemblyMetadata, string key) => + assemblyMetadata?.FirstOrDefault(m => string.Equals(m.Key, key, StringComparison.OrdinalIgnoreCase))?.Value; } diff --git a/src/Aspire.Hosting/Dcp/HostDashboardEndpointProvider.cs b/src/Aspire.Hosting/Dcp/HostDashboardEndpointProvider.cs index 12a310e521..cf363e4906 100644 --- a/src/Aspire.Hosting/Dcp/HostDashboardEndpointProvider.cs +++ b/src/Aspire.Hosting/Dcp/HostDashboardEndpointProvider.cs @@ -5,14 +5,9 @@ namespace Aspire.Hosting.Dcp; -internal sealed class HostDashboardEndpointProvider : IDashboardEndpointProvider +internal sealed class HostDashboardEndpointProvider(DashboardServiceHost dashboardServiceHost) : IDashboardEndpointProvider { - private readonly DashboardServiceHost _dashboardServiceHost; - - public HostDashboardEndpointProvider(DashboardServiceHost dashboardServiceHost) - { - _dashboardServiceHost = dashboardServiceHost; - } + private readonly DashboardServiceHost _dashboardServiceHost = dashboardServiceHost; public async Task GetResourceServiceUriAsync(CancellationToken cancellationToken = default) { diff --git a/src/Aspire.Hosting/Dcp/Model/ExecutableReplicaSet.cs b/src/Aspire.Hosting/Dcp/Model/ExecutableReplicaSet.cs index 0fcdf1f9a7..7703b170cf 100644 --- a/src/Aspire.Hosting/Dcp/Model/ExecutableReplicaSet.cs +++ b/src/Aspire.Hosting/Dcp/Model/ExecutableReplicaSet.cs @@ -41,10 +41,8 @@ public void AnnotateAsObjectList(string annotationName, TValue value) CustomResource.AnnotateAsObjectList(Annotations, annotationName, value); } - public bool TryGetAnnotationAsObjectList(string annotationName, [NotNullWhen(true)] out List? list) - { - return CustomResource.TryGetAnnotationAsObjectList(Annotations, annotationName, out list); - } + public bool TryGetAnnotationAsObjectList(string annotationName, [NotNullWhen(true)] out List? list) => + CustomResource.TryGetAnnotationAsObjectList(Annotations, annotationName, out list); } internal sealed class ExecutableReplicaSetSpec diff --git a/src/Aspire.Hosting/Dcp/Model/ModelCommon.cs b/src/Aspire.Hosting/Dcp/Model/ModelCommon.cs index 9c70e624eb..fd2d5bf7a4 100644 --- a/src/Aspire.Hosting/Dcp/Model/ModelCommon.cs +++ b/src/Aspire.Hosting/Dcp/Model/ModelCommon.cs @@ -52,10 +52,8 @@ public void AnnotateAsObjectList(string annotationName, TValue value) AnnotateAsObjectList(Metadata.Annotations, annotationName, value); } - public bool TryGetAnnotationAsObjectList(string annotationName, [NotNullWhen(true)] out List? list) - { - return TryGetAnnotationAsObjectList(Metadata.Annotations, annotationName, out list); - } + public bool TryGetAnnotationAsObjectList(string annotationName, [NotNullWhen(true)] out List? list) => + TryGetAnnotationAsObjectList(Metadata.Annotations, annotationName, out list); internal static bool TryGetAnnotationAsObjectList(IDictionary? annotations, string annotationName, [NotNullWhen(true)] out List? list) { @@ -196,10 +194,7 @@ public override bool Equals(object? obj) return true; } - public override int GetHashCode() - { - return HashCode.Combine(ServiceName, Address, Port); - } + public override int GetHashCode() => HashCode.Combine(ServiceName, Address, Port); } internal sealed record NamespacedName(string Name, string? Namespace); diff --git a/src/Aspire.Hosting/Dcp/Model/Schema.cs b/src/Aspire.Hosting/Dcp/Model/Schema.cs index d20e70246c..96503e96c6 100644 --- a/src/Aspire.Hosting/Dcp/Model/Schema.cs +++ b/src/Aspire.Hosting/Dcp/Model/Schema.cs @@ -7,13 +7,9 @@ internal sealed class Schema { private readonly Dictionary _byType = new(); - public void Add(string kind, string resource) where T : CustomResource - { + public void Add(string kind, string resource) where T : CustomResource => _byType.Add(typeof(T), (kind, resource)); - } - public bool TryGet(out (string Kind, string Resource) kindWithResource) where T : CustomResource - { - return _byType.TryGetValue(typeof(T), out kindWithResource); - } + public bool TryGet(out (string Kind, string Resource) kindWithResource) where T : CustomResource => + _byType.TryGetValue(typeof(T), out kindWithResource); } diff --git a/src/Aspire.Hosting/Dcp/Process/ProcessResult.cs b/src/Aspire.Hosting/Dcp/Process/ProcessResult.cs index 708e303157..2001ce9f3a 100644 --- a/src/Aspire.Hosting/Dcp/Process/ProcessResult.cs +++ b/src/Aspire.Hosting/Dcp/Process/ProcessResult.cs @@ -3,12 +3,7 @@ namespace Aspire.Hosting.Dcp.Process; -internal sealed class ProcessResult +internal sealed class ProcessResult(int exitCode) { - public ProcessResult(int exitCode) - { - ExitCode = exitCode; - } - - public int ExitCode { get; } + public int ExitCode { get; } = exitCode; } diff --git a/src/Aspire.Hosting/Dcp/Process/ProcessSpec.cs b/src/Aspire.Hosting/Dcp/Process/ProcessSpec.cs index c89cf5c123..c4c1f35cbd 100644 --- a/src/Aspire.Hosting/Dcp/Process/ProcessSpec.cs +++ b/src/Aspire.Hosting/Dcp/Process/ProcessSpec.cs @@ -3,9 +3,9 @@ namespace Aspire.Hosting.Dcp.Process; -internal sealed class ProcessSpec +internal sealed class ProcessSpec(string executablePath) { - public string ExecutablePath { get; } + public string ExecutablePath { get; } = executablePath; public string? WorkingDirectory { get; init; } public IDictionary EnvironmentVariables { get; init; } = new Dictionary(); public bool InheritEnv { get; init; } = true; @@ -16,9 +16,4 @@ internal sealed class ProcessSpec public Action? OnStop { get; init; } public bool KillEntireProcessTree { get; init; } = true; public bool ThrowOnNonZeroReturnCode { get; init; } = true; - - public ProcessSpec(string executablePath) - { - ExecutablePath = executablePath; - } } diff --git a/src/Aspire.Hosting/DistributedApplication.cs b/src/Aspire.Hosting/DistributedApplication.cs index faad429a74..4d5a937a0e 100644 --- a/src/Aspire.Hosting/DistributedApplication.cs +++ b/src/Aspire.Hosting/DistributedApplication.cs @@ -229,10 +229,7 @@ public static IDistributedApplicationBuilder CreateBuilder(DistributedApplicatio /// on how to use .NET Aspire APIs for functional an integrating testing. /// /// - public virtual void Dispose() - { - _host.Dispose(); - } + public virtual void Dispose() => _host.Dispose(); /// /// Asynchronously disposes the distributed application by disposing the . @@ -261,10 +258,7 @@ public virtual void Dispose() /// on how to use .NET Aspire APIs for functional an integrating testing. /// /// - public virtual ValueTask DisposeAsync() - { - return ((IAsyncDisposable)_host).DisposeAsync(); - } + public virtual ValueTask DisposeAsync() => ((IAsyncDisposable)_host).DisposeAsync(); /// public virtual async Task StartAsync(CancellationToken cancellationToken = default) @@ -274,10 +268,7 @@ public virtual async Task StartAsync(CancellationToken cancellationToken = defau } /// - public virtual async Task StopAsync(CancellationToken cancellationToken = default) - { - await _host.StopAsync(cancellationToken).ConfigureAwait(false); - } + public virtual async Task StopAsync(CancellationToken cancellationToken = default) => await _host.StopAsync(cancellationToken).ConfigureAwait(false); /// /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is @@ -333,10 +324,7 @@ public virtual async Task RunAsync(CancellationToken cancellationToken = default /// in refer to . /// /// - public void Run() - { - RunAsync().Wait(); - } + public void Run() => RunAsync().Wait(); // Internal for testing internal async Task ExecuteBeforeStartHooksAsync(CancellationToken cancellationToken) diff --git a/src/Aspire.Hosting/DistributedApplicationBuilder.cs b/src/Aspire.Hosting/DistributedApplicationBuilder.cs index 6090ae49d4..5074d4351f 100644 --- a/src/Aspire.Hosting/DistributedApplicationBuilder.cs +++ b/src/Aspire.Hosting/DistributedApplicationBuilder.cs @@ -77,10 +77,8 @@ public class DistributedApplicationBuilder : IDistributedApplicationBuilder /// This constructor is public to allow for some testing around extensibility scenarios. /// /// - public DistributedApplicationBuilder(string[] args) : this(new DistributedApplicationOptions { Args = args }) - { + public DistributedApplicationBuilder(string[] args) : this(new DistributedApplicationOptions { Args = args }) => ArgumentNullException.ThrowIfNull(args); - } /// /// Initializes a new instance of the class with the specified options. @@ -241,10 +239,8 @@ private void MapTransportOptionsFromCustomKeys(TransportOptions options) } } - private static bool IsDashboardUnsecured(IConfiguration configuration) - { - return configuration.GetBool(KnownConfigNames.DashboardUnsecuredAllowAnonymous) ?? false; - } + private static bool IsDashboardUnsecured(IConfiguration configuration) => + configuration.GetBool(KnownConfigNames.DashboardUnsecuredAllowAnonymous) ?? false; private void ConfigurePublishingOptions(DistributedApplicationOptions options) { diff --git a/src/Aspire.Hosting/DistributedApplicationLifecycle.cs b/src/Aspire.Hosting/DistributedApplicationLifecycle.cs index 4ab3c63b26..803767d626 100644 --- a/src/Aspire.Hosting/DistributedApplicationLifecycle.cs +++ b/src/Aspire.Hosting/DistributedApplicationLifecycle.cs @@ -13,10 +13,7 @@ internal sealed class DistributedApplicationLifecycle( IConfiguration configuration, DistributedApplicationExecutionContext executionContext) : IHostedLifecycleService { - public Task StartAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; public Task StartedAsync(CancellationToken cancellationToken) { @@ -46,18 +43,9 @@ public Task StartingAsync(CancellationToken cancellationToken) return Task.CompletedTask; } - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; - public Task StoppedAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask; - public Task StoppingAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } + public Task StoppingAsync(CancellationToken cancellationToken) => Task.CompletedTask; } diff --git a/src/Aspire.Hosting/DistributedApplicationOptions.cs b/src/Aspire.Hosting/DistributedApplicationOptions.cs index b1c2c20266..6d73ba58bc 100644 --- a/src/Aspire.Hosting/DistributedApplicationOptions.cs +++ b/src/Aspire.Hosting/DistributedApplicationOptions.cs @@ -93,13 +93,8 @@ internal string? ProjectDirectory return appHostAssembly; } - private string? ResolveConfiguration() - { - return Assembly?.GetCustomAttribute()?.Configuration; - } + private string? ResolveConfiguration() => Assembly?.GetCustomAttribute()?.Configuration; - private static string? GetMetadataValue(IEnumerable? assemblyMetadata, string key) - { - return assemblyMetadata?.FirstOrDefault(m => string.Equals(m.Key, key, StringComparison.OrdinalIgnoreCase))?.Value; - } + private static string? GetMetadataValue(IEnumerable? assemblyMetadata, string key) => + assemblyMetadata?.FirstOrDefault(m => string.Equals(m.Key, key, StringComparison.OrdinalIgnoreCase))?.Value; } diff --git a/src/Aspire.Hosting/ExecutableResourceBuilderExtensions.cs b/src/Aspire.Hosting/ExecutableResourceBuilderExtensions.cs index b273a9b1b9..ac48c614bf 100644 --- a/src/Aspire.Hosting/ExecutableResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting/ExecutableResourceBuilderExtensions.cs @@ -45,10 +45,8 @@ public static IResourceBuilder AddExecutable(this IDistribut /// Resource builder /// The optional build arguments, used with docker build --build-args. /// A reference to the . - public static IResourceBuilder PublishAsDockerFile(this IResourceBuilder builder, IEnumerable? buildArgs = null) where T : ExecutableResource - { - return builder.WithManifestPublishingCallback(context => WriteExecutableAsDockerfileResourceAsync(context, builder.Resource, buildArgs)); - } + public static IResourceBuilder PublishAsDockerFile(this IResourceBuilder builder, IEnumerable? buildArgs = null) where T : ExecutableResource => + builder.WithManifestPublishingCallback(context => WriteExecutableAsDockerfileResourceAsync(context, builder.Resource, buildArgs)); private static async Task WriteExecutableAsDockerfileResourceAsync(ManifestPublishingContext context, ExecutableResource executable, IEnumerable? buildArgs = null) { diff --git a/src/Aspire.Hosting/ExecutableResourceExtensions.cs b/src/Aspire.Hosting/ExecutableResourceExtensions.cs index 5b7604a1ad..c3358789ff 100644 --- a/src/Aspire.Hosting/ExecutableResourceExtensions.cs +++ b/src/Aspire.Hosting/ExecutableResourceExtensions.cs @@ -15,8 +15,6 @@ public static class ExecutableResourceExtensions /// /// The distributed application model to retrieve executable resources from. /// An enumerable collection of executable resources. - public static IEnumerable GetExecutableResources(this DistributedApplicationModel model) - { - return model.Resources.OfType(); - } + public static IEnumerable GetExecutableResources(this DistributedApplicationModel model) => + model.Resources.OfType(); } diff --git a/src/Aspire.Hosting/Lifecycle/IDistributedApplicationLifecycleHook.cs b/src/Aspire.Hosting/Lifecycle/IDistributedApplicationLifecycleHook.cs index 3e0726a491..025970863e 100644 --- a/src/Aspire.Hosting/Lifecycle/IDistributedApplicationLifecycleHook.cs +++ b/src/Aspire.Hosting/Lifecycle/IDistributedApplicationLifecycleHook.cs @@ -16,10 +16,7 @@ public interface IDistributedApplicationLifecycleHook /// The distributed application model. /// A . /// A representing the asynchronous operation. - Task BeforeStartAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + Task BeforeStartAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default) => Task.CompletedTask; /// /// Executes after the orchestrator allocates endpoints for resources in the application model. @@ -27,10 +24,7 @@ Task BeforeStartAsync(DistributedApplicationModel appModel, CancellationToken ca /// The distributed application model. /// A . /// A representing the asynchronous operation. - Task AfterEndpointsAllocatedAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + Task AfterEndpointsAllocatedAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default) => Task.CompletedTask; /// /// Executes after the orchestrator has created the resources in the application model. @@ -41,8 +35,5 @@ Task AfterEndpointsAllocatedAsync(DistributedApplicationModel appModel, Cancella /// The for the distributed application. /// A . /// A representing the asynchronous operation. - Task AfterResourcesCreatedAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default) - { - return Task.CompletedTask; - } + Task AfterResourcesCreatedAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default) => Task.CompletedTask; } diff --git a/src/Aspire.Hosting/Lifecycle/LifecycleHookServiceCollectionExtensions.cs b/src/Aspire.Hosting/Lifecycle/LifecycleHookServiceCollectionExtensions.cs index 0168460467..a871ca63e5 100644 --- a/src/Aspire.Hosting/Lifecycle/LifecycleHookServiceCollectionExtensions.cs +++ b/src/Aspire.Hosting/Lifecycle/LifecycleHookServiceCollectionExtensions.cs @@ -16,20 +16,16 @@ public static class LifecycleHookServiceCollectionExtensions /// /// The type of the distributed application lifecycle hook to add. /// The to add the distributed application lifecycle hook to. - public static void AddLifecycleHook(this IServiceCollection services) where T : class, IDistributedApplicationLifecycleHook - { + public static void AddLifecycleHook(this IServiceCollection services) where T : class, IDistributedApplicationLifecycleHook => services.AddSingleton(); - } /// /// Attempts to add a distributed application lifecycle hook to the service collection. /// /// The type of the distributed application lifecycle hook to add. /// The to add the distributed application lifecycle hook to. - public static void TryAddLifecycleHook(this IServiceCollection services) where T : class, IDistributedApplicationLifecycleHook - { + public static void TryAddLifecycleHook(this IServiceCollection services) where T : class, IDistributedApplicationLifecycleHook => services.TryAddEnumerable(ServiceDescriptor.Singleton()); - } /// /// Adds a distributed application lifecycle hook to the service collection. @@ -37,10 +33,8 @@ public static void TryAddLifecycleHook(this IServiceCollection services) wher /// The type of the distributed application lifecycle hook. /// The service collection to add the hook to. /// A factory function that creates the hook implementation. - public static void AddLifecycleHook(this IServiceCollection services, Func implementationFactory) where T : class, IDistributedApplicationLifecycleHook - { + public static void AddLifecycleHook(this IServiceCollection services, Func implementationFactory) where T : class, IDistributedApplicationLifecycleHook => services.AddSingleton(implementationFactory); - } /// /// Attempts to add a distributed application lifecycle hook to the service collection. @@ -48,8 +42,6 @@ public static void AddLifecycleHook(this IServiceCollection services, FuncThe type of the distributed application lifecycle hook. /// The service collection to add the hook to. /// A factory function that creates the hook implementation. - public static void TryAddLifecycleHook(this IServiceCollection services, Func implementationFactory) where T : class, IDistributedApplicationLifecycleHook - { + public static void TryAddLifecycleHook(this IServiceCollection services, Func implementationFactory) where T : class, IDistributedApplicationLifecycleHook => services.TryAddEnumerable(ServiceDescriptor.Singleton(implementationFactory)); - } } diff --git a/src/Aspire.Hosting/ParameterResourceBuilderExtensions.cs b/src/Aspire.Hosting/ParameterResourceBuilderExtensions.cs index b9190f57be..3377b8e4c4 100644 --- a/src/Aspire.Hosting/ParameterResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting/ParameterResourceBuilderExtensions.cs @@ -22,10 +22,8 @@ public static class ParameterResourceBuilderExtensions /// Optional flag indicating whether the parameter should be regarded as secret. /// Resource builder for the parameter. /// - public static IResourceBuilder AddParameter(this IDistributedApplicationBuilder builder, string name, bool secret = false) - { - return builder.AddParameter(name, parameterDefault => GetParameterValue(builder.Configuration, name, parameterDefault), secret: secret); - } + public static IResourceBuilder AddParameter(this IDistributedApplicationBuilder builder, string name, bool secret = false) => + builder.AddParameter(name, parameterDefault => GetParameterValue(builder.Configuration, name, parameterDefault), secret: secret); private static string GetParameterValue(IConfiguration configuration, string name, ParameterDefault? parameterDefault) { diff --git a/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs b/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs index 5eaf1c6ddb..e450ae29a6 100644 --- a/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs @@ -58,10 +58,8 @@ public static class ProjectResourceBuilderExtensions /// builder.Build().Run(); /// /// - public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name) where TProject : IProjectMetadata, new() - { - return builder.AddProject(name, _ => { }); - } + public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name) where TProject : IProjectMetadata, new() => + builder.AddProject(name, _ => { }); /// /// Adds a .NET project to the application model. @@ -88,10 +86,8 @@ public static class ProjectResourceBuilderExtensions /// builder.Build().Run(); /// /// - public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name, string projectPath) - { - return builder.AddProject(name, projectPath, _ => { }); - } + public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name, string projectPath) => + builder.AddProject(name, projectPath, _ => { }); /// /// Adds a .NET project to the application model. By default, this will exist in a Projects namespace. e.g. Projects.MyProject. @@ -131,14 +127,12 @@ public static IResourceBuilder AddProject(this IDistributedAppl /// builder.Build().Run(); /// /// - public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name, string? launchProfileName) where TProject : IProjectMetadata, new() - { - return builder.AddProject(name, options => - { - options.ExcludeLaunchProfile = launchProfileName is null; - options.LaunchProfileName = launchProfileName; - }); - } + public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name, string? launchProfileName) where TProject : IProjectMetadata, new() => + builder.AddProject(name, options => + { + options.ExcludeLaunchProfile = launchProfileName is null; + options.LaunchProfileName = launchProfileName; + }); /// /// Adds a .NET project to the application model. @@ -166,14 +160,13 @@ public static IResourceBuilder AddProject(this IDistributedAppl /// builder.Build().Run(); /// /// - public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name, string projectPath, string? launchProfileName) - { - return builder.AddProject(name, projectPath, options => + public static IResourceBuilder AddProject(this IDistributedApplicationBuilder builder, string name, string projectPath, string? launchProfileName) => + builder.AddProject(name, projectPath, options => { options.ExcludeLaunchProfile = launchProfileName is null; options.LaunchProfileName = launchProfileName; }); - } + /// /// Adds a .NET project to the application model. @@ -335,7 +328,8 @@ private static IResourceBuilder WithProjectDefaults(this IResou // Helper to change the transport to http2 if needed var isHttp2ConfiguredInKestrelEndpointDefaults = config["Kestrel:EndpointDefaults:Protocols"] == nameof(HttpProtocols.Http2); - var adjustTransport = (EndpointAnnotation e, string? bindingLevelProtocols = null) => { + var adjustTransport = (EndpointAnnotation e, string? bindingLevelProtocols = null) => + { if (bindingLevelProtocols != null) { // If the Kestrel endpoint has an explicit protocol, use that and ignore any EndpointDefaults diff --git a/src/Aspire.Hosting/Publishing/PortAllocator.cs b/src/Aspire.Hosting/Publishing/PortAllocator.cs index 40f36fbebb..9ddf910077 100644 --- a/src/Aspire.Hosting/Publishing/PortAllocator.cs +++ b/src/Aspire.Hosting/Publishing/PortAllocator.cs @@ -22,8 +22,5 @@ public int AllocatePort() } } - public void AddUsedPort(int port) - { - _usedPorts.Add(port); - } + public void AddUsedPort(int port) => _usedPorts.Add(port); } diff --git a/src/Aspire.Hosting/ResourceBuilderExtensions.cs b/src/Aspire.Hosting/ResourceBuilderExtensions.cs index 1dd8905f07..983b7ab728 100644 --- a/src/Aspire.Hosting/ResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting/ResourceBuilderExtensions.cs @@ -22,10 +22,8 @@ public static class ResourceBuilderExtensions /// The name of the environment variable. /// The value of the environment variable. /// A resource configured with the specified environment variable. - public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, string? value) where T : IResourceWithEnvironment - { - return builder.WithAnnotation(new EnvironmentAnnotation(name, value ?? string.Empty)); - } + public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, string? value) where T : IResourceWithEnvironment => + builder.WithAnnotation(new EnvironmentAnnotation(name, value ?? string.Empty)); /// /// Adds an environment variable to the resource. @@ -71,10 +69,8 @@ public static IResourceBuilder WithEnvironment(this IResourceBuilder bu /// The name of the environment variable. /// A callback that allows for deferred execution of a specific environment variable. This runs after resources have been allocated by the orchestrator and allows access to other resources to resolve computed data, e.g. connection strings, ports. /// A resource configured with the specified environment variable. - public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, Func callback) where T : IResourceWithEnvironment - { - return builder.WithAnnotation(new EnvironmentCallbackAnnotation(name, callback)); - } + public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, Func callback) where T : IResourceWithEnvironment => + builder.WithAnnotation(new EnvironmentCallbackAnnotation(name, callback)); /// /// Allows for the population of environment variables on a resource. @@ -83,10 +79,8 @@ public static IResourceBuilder WithEnvironment(this IResourceBuilder bu /// The resource builder. /// A callback that allows for deferred execution for computing many environment variables. This runs after resources have been allocated by the orchestrator and allows access to other resources to resolve computed data, e.g. connection strings, ports. /// A resource configured with the environment variable callback. - public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, Action callback) where T : IResourceWithEnvironment - { - return builder.WithAnnotation(new EnvironmentCallbackAnnotation(callback)); - } + public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, Action callback) where T : IResourceWithEnvironment => + builder.WithAnnotation(new EnvironmentCallbackAnnotation(callback)); /// /// Allows for the population of environment variables on a resource. @@ -95,10 +89,8 @@ public static IResourceBuilder WithEnvironment(this IResourceBuilder bu /// The resource builder. /// A callback that allows for deferred execution for computing many environment variables. This runs after resources have been allocated by the orchestrator and allows access to other resources to resolve computed data, e.g. connection strings, ports. /// A resource configured with the environment variable callback. - public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, Func callback) where T : IResourceWithEnvironment - { - return builder.WithAnnotation(new EnvironmentCallbackAnnotation(callback)); - } + public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, Func callback) where T : IResourceWithEnvironment => + builder.WithAnnotation(new EnvironmentCallbackAnnotation(callback)); /// /// Adds an environment variable to the resource with the endpoint for . @@ -108,13 +100,11 @@ public static IResourceBuilder WithEnvironment(this IResourceBuilder bu /// The name of the environment variable. /// The endpoint from which to extract the url. /// A resource configured with the environment variable callback. - public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, EndpointReference endpointReference) where T : IResourceWithEnvironment - { - return builder.WithEnvironment(context => + public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, EndpointReference endpointReference) where T : IResourceWithEnvironment => + builder.WithEnvironment(context => { context.EnvironmentVariables[name] = endpointReference; }); - } /// /// Adds an environment variable to the resource with the value from . @@ -124,13 +114,12 @@ public static IResourceBuilder WithEnvironment(this IResourceBuilder bu /// Name of environment variable /// Resource builder for the parameter resource. /// A resource configured with the environment variable callback. - public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, IResourceBuilder parameter) where T : IResourceWithEnvironment - { - return builder.WithEnvironment(context => + public static IResourceBuilder WithEnvironment(this IResourceBuilder builder, string name, IResourceBuilder parameter) where T : IResourceWithEnvironment => + builder.WithEnvironment(context => { context.EnvironmentVariables[name] = parameter.Resource; }); - } + /// /// Adds an environment variable to the resource with the connection string from the referenced resource. @@ -144,13 +133,13 @@ public static IResourceBuilder WithEnvironment( this IResourceBuilder builder, string envVarName, IResourceBuilder resource) - where T : IResourceWithEnvironment - { - return builder.WithEnvironment(context => + where T : IResourceWithEnvironment => + + builder.WithEnvironment(context => { context.EnvironmentVariables[envVarName] = new ConnectionStringReference(resource.Resource, optional: false); }); - } + /// /// Adds the arguments to be passed to a container resource when the container is started. @@ -159,10 +148,7 @@ public static IResourceBuilder WithEnvironment( /// The resource builder. /// The arguments to be passed to the container when it is started. /// The . - public static IResourceBuilder WithArgs(this IResourceBuilder builder, params string[] args) where T : IResourceWithArgs - { - return builder.WithArgs(context => context.Args.AddRange(args)); - } + public static IResourceBuilder WithArgs(this IResourceBuilder builder, params string[] args) where T : IResourceWithArgs => builder.WithArgs(context => context.Args.AddRange(args)); /// /// Adds a callback to be executed with a list of command-line arguments when a container resource is started. @@ -171,14 +157,13 @@ public static IResourceBuilder WithArgs(this IResourceBuilder builder, /// The resource builder. /// A callback that allows for deferred execution for computing arguments. This runs after resources have been allocated by the orchestrator and allows access to other resources to resolve computed data, e.g. connection strings, ports. /// The . - public static IResourceBuilder WithArgs(this IResourceBuilder builder, Action callback) where T : IResourceWithArgs - { - return builder.WithArgs(context => + public static IResourceBuilder WithArgs(this IResourceBuilder builder, Action callback) where T : IResourceWithArgs=> + builder.WithArgs(context => { callback(context); return Task.CompletedTask; }); - } + /// /// Adds a callback to be executed with a list of command-line arguments when a container resource is started. From 3e71f097b997241672e9ec40703fafd58db89c25 Mon Sep 17 00:00:00 2001 From: Khanbala Rashidov <50279392+KhanbalaRashidov@users.noreply.github.com> Date: Tue, 2 Jul 2024 15:59:54 +0400 Subject: [PATCH 4/5] Fixed --- .../AspireWebPubSubExtensions.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs b/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs index dfec23d608..70cd7ae24f 100644 --- a/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs +++ b/src/Components/Aspire.Azure.Messaging.WebPubSub/AspireWebPubSubExtensions.cs @@ -103,11 +103,9 @@ protected override void BindClientOptionsToConfiguration(IAzureClientBuilder configuration.Bind(options)); #pragma warning restore IDE0200 - protected override void BindSettingsToConfiguration(AzureMessagingWebPubSubSettings settings, IConfiguration config) => config.Bind(settings); - protected override TokenCredential? GetTokenCredential(AzureMessagingWebPubSubSettings settings) => settings.Credential; @@ -122,8 +120,6 @@ private sealed class HealthCheck(WebPubSubServiceClient client) : IHealthCheck { private readonly WebPubSubServiceClient _client = client; - - public async Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { try From 9287bd2bada37651d8fed8f8c5b7807b8f31c119 Mon Sep 17 00:00:00 2001 From: Khanbala Rashidov <50279392+KhanbalaRashidov@users.noreply.github.com> Date: Tue, 2 Jul 2024 16:11:49 +0400 Subject: [PATCH 5/5] Fixed --- src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs | 1 - src/Aspire.Hosting/ResourceBuilderExtensions.cs | 2 -- 2 files changed, 3 deletions(-) diff --git a/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs b/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs index e450ae29a6..8775e5516a 100644 --- a/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting/ProjectResourceBuilderExtensions.cs @@ -167,7 +167,6 @@ public static IResourceBuilder AddProject(this IDistributedAppl options.LaunchProfileName = launchProfileName; }); - /// /// Adds a .NET project to the application model. /// diff --git a/src/Aspire.Hosting/ResourceBuilderExtensions.cs b/src/Aspire.Hosting/ResourceBuilderExtensions.cs index 983b7ab728..2f222a6532 100644 --- a/src/Aspire.Hosting/ResourceBuilderExtensions.cs +++ b/src/Aspire.Hosting/ResourceBuilderExtensions.cs @@ -120,7 +120,6 @@ public static IResourceBuilder WithEnvironment(this IResourceBuilder bu context.EnvironmentVariables[name] = parameter.Resource; }); - /// /// Adds an environment variable to the resource with the connection string from the referenced resource. /// @@ -140,7 +139,6 @@ public static IResourceBuilder WithEnvironment( context.EnvironmentVariables[envVarName] = new ConnectionStringReference(resource.Resource, optional: false); }); - /// /// Adds the arguments to be passed to a container resource when the container is started. ///