diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreInstrumentation.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreInstrumentation.cs index 7043817037..d7d02ecdc3 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreInstrumentation.cs @@ -10,14 +10,14 @@ namespace OpenTelemetry.Instrumentation.AspNetCore; /// internal sealed class AspNetCoreInstrumentation : IDisposable { - private static readonly HashSet DiagnosticSourceEvents = new() - { + private static readonly HashSet DiagnosticSourceEvents = + [ "Microsoft.AspNetCore.Hosting.HttpRequestIn", "Microsoft.AspNetCore.Hosting.HttpRequestIn.Start", "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop", "Microsoft.AspNetCore.Diagnostics.UnhandledException", - "Microsoft.AspNetCore.Hosting.UnhandledException", - }; + "Microsoft.AspNetCore.Hosting.UnhandledException" + ]; private readonly Func isEnabled = (eventName, _, _) => DiagnosticSourceEvents.Contains(eventName); diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreMetrics.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreMetrics.cs index 75676510f4..877f5ece38 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreMetrics.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/AspNetCoreMetrics.cs @@ -11,14 +11,14 @@ namespace OpenTelemetry.Instrumentation.AspNetCore; /// internal sealed class AspNetCoreMetrics : IDisposable { - private static readonly HashSet DiagnosticSourceEvents = new() - { + private static readonly HashSet DiagnosticSourceEvents = + [ "Microsoft.AspNetCore.Hosting.HttpRequestIn", "Microsoft.AspNetCore.Hosting.HttpRequestIn.Start", "Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop", "Microsoft.AspNetCore.Diagnostics.UnhandledException", - "Microsoft.AspNetCore.Hosting.UnhandledException", - }; + "Microsoft.AspNetCore.Hosting.UnhandledException" + ]; private readonly Func isEnabled = (eventName, _, _) => DiagnosticSourceEvents.Contains(eventName); diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs index 7f0aa51634..26eafb164d 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInListener.cs @@ -43,7 +43,7 @@ internal class HttpInListener : ListenerHandler return value; } - return Enumerable.Empty(); + return []; }; private static readonly PropertyFetcher ExceptionPropertyFetcher = new("Exception"); @@ -82,6 +82,8 @@ public override void OnEventWritten(string name, object? payload) this.OnException(activity, payload); } + break; + default: break; } } @@ -98,8 +100,7 @@ public void OnStartActivity(Activity activity, object? payload) // By this time, samplers have already run and // activity.IsAllDataRequested populated accordingly. - var context = payload as HttpContext; - if (context == null) + if (payload is not HttpContext context) { AspNetCoreInstrumentationEventSource.Log.NullPayload(nameof(HttpInListener), nameof(this.OnStartActivity), activity.OperationName); return; @@ -309,7 +310,7 @@ public void OnException(Activity activity, object? payload) if (activity.IsAllDataRequested) { // We need to use reflection here as the payload type is not a defined public type. - if (!TryFetchException(payload, out Exception? exc)) + if (!TryFetchException(payload, out var exc)) { AspNetCoreInstrumentationEventSource.Log.NullPayload(nameof(HttpInListener), nameof(this.OnException), activity.OperationName); return; @@ -341,7 +342,9 @@ public void OnException(Activity activity, object? payload) [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The event source guarantees that top level properties are preserved")] #endif static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception? exc) - => ExceptionPropertyFetcher.TryFetch(payload, out exc) && exc != null; + { + return ExceptionPropertyFetcher.TryFetch(payload, out exc) && exc != null; + } } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -370,7 +373,7 @@ private static void AddGrpcAttributes(Activity activity, string grpcMethod, Http activity.SetTag(SemanticConventions.AttributeClientPort, context.Connection.RemotePort); - bool validConversion = GrpcTagHelper.TryGetGrpcStatusCodeFromActivity(activity, out int status); + var validConversion = GrpcTagHelper.TryGetGrpcStatusCodeFromActivity(activity, out var status); if (validConversion) { activity.SetStatus(GrpcTagHelper.ResolveSpanStatusForGrpcStatusCode(status)); diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInMetricsListener.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInMetricsListener.cs index 08ab129cab..c9040d0248 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInMetricsListener.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/HttpInMetricsListener.cs @@ -43,7 +43,7 @@ internal HttpInMetricsListener(string name) public static void OnExceptionEventWritten(string name, object? payload) { // We need to use reflection here as the payload type is not a defined public type. - if (!TryFetchException(payload, out Exception? exc) || !TryFetchHttpContext(payload, out HttpContext? ctx)) + if (!TryFetchException(payload, out var exc) || !TryFetchHttpContext(payload, out var ctx)) { AspNetCoreInstrumentationEventSource.Log.NullPayload(nameof(HttpInMetricsListener), nameof(OnExceptionEventWritten), HttpServerRequestDurationMetricName); return; @@ -58,18 +58,21 @@ public static void OnExceptionEventWritten(string name, object? payload) [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The ASP.NET Core framework guarantees that top level properties are preserved")] #endif static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception? exc) - => ExceptionPropertyFetcher.TryFetch(payload, out exc) && exc != null; + { + return ExceptionPropertyFetcher.TryFetch(payload, out exc) && exc != null; + } #if NET [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The ASP.NET Core framework guarantees that top level properties are preserved")] #endif static bool TryFetchHttpContext(object? payload, [NotNullWhen(true)] out HttpContext? ctx) - => HttpContextPropertyFetcher.TryFetch(payload, out ctx) && ctx != null; + { + return HttpContextPropertyFetcher.TryFetch(payload, out ctx) && ctx != null; + } } public static void OnStopEventWritten(string name, object? payload) { - var context = payload as HttpContext; - if (context == null) + if (payload is not HttpContext context) { AspNetCoreInstrumentationEventSource.Log.NullPayload(nameof(HttpInMetricsListener), nameof(OnStopEventWritten), HttpServerRequestDurationMetricName); return; @@ -121,6 +124,8 @@ public override void OnEventWritten(string name, object? payload) OnStopEventWritten(name, payload); } + break; + default: break; } } diff --git a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/TelemetryHelper.cs b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/TelemetryHelper.cs index ad51848e85..ab3e8a4627 100644 --- a/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/TelemetryHelper.cs +++ b/src/OpenTelemetry.Instrumentation.AspNetCore/Implementation/TelemetryHelper.cs @@ -12,12 +12,7 @@ internal static class TelemetryHelper public static object GetBoxedStatusCode(int statusCode) { - if (statusCode >= 100 && statusCode < 600) - { - return BoxedStatusCodes[statusCode - 100]; - } - - return statusCode; + return statusCode is >= 100 and < 600 ? BoxedStatusCodes[statusCode - 100] : statusCode; } private static object[] InitializeBoxedStatusCodes() diff --git a/src/Shared/DiagnosticSourceSubscriber.cs b/src/Shared/DiagnosticSourceSubscriber.cs index e01d14c3ad..3318216db0 100644 --- a/src/Shared/DiagnosticSourceSubscriber.cs +++ b/src/Shared/DiagnosticSourceSubscriber.cs @@ -34,7 +34,7 @@ public DiagnosticSourceSubscriber( { Guard.ThrowIfNull(handlerFactory); - this.listenerSubscriptions = new List(); + this.listenerSubscriptions = []; this.handlerFactory = handlerFactory; this.diagnosticSourceFilter = diagnosticSourceFilter; this.isEnabledFilter = isEnabledFilter; @@ -43,10 +43,7 @@ public DiagnosticSourceSubscriber( public void Subscribe() { - if (this.allSourcesSubscription == null) - { - this.allSourcesSubscription = DiagnosticListener.AllListeners.Subscribe(this); - } + this.allSourcesSubscription ??= DiagnosticListener.AllListeners.Subscribe(this); } public void OnNext(DiagnosticListener value) diff --git a/src/Shared/RedactionHelper.cs b/src/Shared/RedactionHelper.cs index cc6e34c7ea..045d99cad2 100644 --- a/src/Shared/RedactionHelper.cs +++ b/src/Shared/RedactionHelper.cs @@ -13,8 +13,8 @@ internal sealed class RedactionHelper public static string? GetRedactedQueryString(string query) { - int length = query.Length; - int index = 0; + var length = query.Length; + var index = 0; // Preallocate some size to avoid re-sizing multiple times. // Since the size will increase, allocating twice as much. diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationBenchmarks.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationBenchmarks.cs index f0caa4f9ec..3981971027 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationBenchmarks.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationBenchmarks.cs @@ -65,7 +65,9 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Benchmark.Instrumentation; +#pragma warning disable CA1515 public class AspNetCoreInstrumentationBenchmarks +#pragma warning restore CA1515 { private HttpClient? httpClient; private WebApplication? app; @@ -73,7 +75,9 @@ public class AspNetCoreInstrumentationBenchmarks private MeterProvider? meterProvider; [Flags] +#pragma warning disable CA1515 public enum EnableInstrumentationOption +#pragma warning restore CA1515 { /// /// Instrumentation is not enabled for any signal. diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationNewBenchmarks.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationNewBenchmarks.cs index 14d777d5c3..3a13e17507 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationNewBenchmarks.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Benchmarks/Instrumentation/AspNetCoreInstrumentationNewBenchmarks.cs @@ -67,7 +67,9 @@ */ namespace OpenTelemetry.Instrumentation.AspNetCore.Benchmarks.Instrumentation; +#pragma warning disable CA1515 public class AspNetCoreInstrumentationNewBenchmarks +#pragma warning restore CA1515 { private HttpClient? httpClient; private WebApplication? app; @@ -75,7 +77,9 @@ public class AspNetCoreInstrumentationNewBenchmarks private MeterProvider? meterProvider; [Flags] +#pragma warning disable CA1515 public enum EnableInstrumentationOption +#pragma warning restore CA1515 { /// /// Instrumentation is not enabled for any signal. @@ -99,7 +103,7 @@ public enum EnableInstrumentationOption [GlobalSetup(Target = nameof(GetRequestForAspNetCoreApp))] public void GetRequestForAspNetCoreAppGlobalSetup() { - KeyValuePair[] config = new KeyValuePair[] { new KeyValuePair("OTEL_SEMCONV_STABILITY_OPT_IN", "http") }; + KeyValuePair[] config = [new("OTEL_SEMCONV_STABILITY_OPT_IN", "http")]; var configuration = new ConfigurationBuilder() .AddInMemoryCollection(config) .Build(); diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs index fb0284ac09..1d0ad5aa7f 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/BasicTests.cs @@ -241,11 +241,7 @@ public async Task CustomPropagator(bool addSampler) } finally { - Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[] - { - new TraceContextPropagator(), - new BaggagePropagator(), - })); + Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([new TraceContextPropagator(), new BaggagePropagator()])); } } @@ -299,14 +295,9 @@ void ConfigureTestServices(IServiceCollection services) this.tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAspNetCoreInstrumentation((opt) => opt.Filter = (ctx) => { - if (ctx.Request.Path == "/api/values/2") - { - throw new Exception("from InstrumentationFilter"); - } - else - { - return true; - } + return ctx.Request.Path == "/api/values/2" + ? throw new Exception("from InstrumentationFilter") + : true; }) .AddInMemoryExporter(exportedItems) .Build(); @@ -394,11 +385,7 @@ public async Task ExtractContextIrrespectiveOfSamplingDecision(SamplingDecision } finally { - Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[] - { - new TraceContextPropagator(), - new BaggagePropagator(), - })); + Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([new TraceContextPropagator(), new BaggagePropagator()])); } } @@ -415,7 +402,7 @@ public async Task ExtractContextIrrespectiveOfTheFilterApplied() Sdk.SetDefaultTextMapPropagator(new ExtractOnlyPropagator(activityContext, expectedBaggage)); // Arrange - bool isFilterCalled = false; + var isFilterCalled = false; using var testFactory = this.factory .WithWebHostBuilder(builder => { @@ -466,11 +453,7 @@ public async Task ExtractContextIrrespectiveOfTheFilterApplied() } finally { - Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[] - { - new TraceContextPropagator(), - new BaggagePropagator(), - })); + Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator([new TraceContextPropagator(), new BaggagePropagator()])); } } @@ -479,7 +462,7 @@ public async Task BaggageIsNotClearedWhenActivityStopped() { int? baggageCountAfterStart = null; int? baggageCountAfterStop = null; - using EventWaitHandle stopSignal = new EventWaitHandle(false, EventResetMode.ManualReset); + using var stopSignal = new EventWaitHandle(false, EventResetMode.ManualReset); void ConfigureTestServices(IServiceCollection services) { @@ -503,6 +486,8 @@ void ConfigureTestServices(IServiceCollection services) stopSignal.Set(); } + break; + default: break; } }, @@ -542,9 +527,9 @@ void ConfigureTestServices(IServiceCollection services) [InlineData(SamplingDecision.RecordAndSample, true, true)] public async Task FilterAndEnrichAreOnlyCalledWhenSampled(SamplingDecision samplingDecision, bool shouldFilterBeCalled, bool shouldEnrichBeCalled) { - bool filterCalled = false; - bool enrichWithHttpRequestCalled = false; - bool enrichWithHttpResponseCalled = false; + var filterCalled = false; + var enrichWithHttpRequestCalled = false; + var enrichWithHttpResponseCalled = false; void ConfigureTestServices(IServiceCollection services) { this.tracerProvider = Sdk.CreateTracerProviderBuilder() @@ -667,9 +652,10 @@ void ConfigureTestServices(IServiceCollection services) }) .CreateClient(); - var message = new HttpRequestMessage(); - - message.Method = new HttpMethod(originalMethod); + var message = new HttpRequestMessage + { + Method = new HttpMethod(originalMethod), + }; try { @@ -811,8 +797,8 @@ public async Task ShouldExportActivityWithOneOrMoreExceptionFilters(int mode) [Fact] public async Task DiagnosticSourceCallbacksAreReceivedOnlyForSubscribedEvents() { - int numberOfUnSubscribedEvents = 0; - int numberofSubscribedEvents = 0; + var numberOfUnSubscribedEvents = 0; + var numberofSubscribedEvents = 0; this.tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAspNetCoreInstrumentation( @@ -866,9 +852,9 @@ public async Task DiagnosticSourceCallbacksAreReceivedOnlyForSubscribedEvents() [Fact] public async Task DiagnosticSourceExceptionCallbackIsReceivedForUnHandledException() { - int numberOfUnSubscribedEvents = 0; - int numberofSubscribedEvents = 0; - int numberOfExceptionCallbacks = 0; + var numberOfUnSubscribedEvents = 0; + var numberofSubscribedEvents = 0; + var numberOfExceptionCallbacks = 0; this.tracerProvider = Sdk.CreateTracerProviderBuilder() .AddAspNetCoreInstrumentation( @@ -941,10 +927,10 @@ public async Task DiagnosticSourceExceptionCallbackIsReceivedForUnHandledExcepti [Fact] public async Task DiagnosticSourceExceptionCallBackIsNotReceivedForExceptionsHandledInMiddleware() { - int numberOfUnSubscribedEvents = 0; - int numberOfSubscribedEvents = 0; - int numberOfExceptionCallbacks = 0; - bool exceptionHandled = false; + var numberOfUnSubscribedEvents = 0; + var numberOfSubscribedEvents = 0; + var numberOfExceptionCallbacks = 0; + var exceptionHandled = false; // configure SDK this.tracerProvider = Sdk.CreateTracerProviderBuilder() diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs index b5c6db209c..859a53f746 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/DependencyInjectionConfigTests.cs @@ -28,7 +28,7 @@ public void TestTracingOptionsDIConfig(string? name) { name ??= Options.DefaultName; - bool optionsPickedFromDI = false; + var optionsPickedFromDI = false; void ConfigureTestServices(IServiceCollection services) { services.AddOpenTelemetry() diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs index e0eb0c32b5..c3f80a9cee 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/MetricTests.cs @@ -132,7 +132,10 @@ void ConfigureTestServices(IServiceCollection services) app.UseRateLimiter(); - static string GetTicks() => (DateTime.Now.Ticks & 0x11111).ToString("00000"); + static string GetTicks() + { + return (DateTime.Now.Ticks & 0x11111).ToString("00000"); + } app.MapGet("/", () => Results.Ok($"Hello {GetTicks()}")) .RequireRateLimiting("fixed"); @@ -226,7 +229,7 @@ public async Task RequestMetricIsCaptured(string api, string expectedRoute, stri AssertMetricPoints( metricPoints: metricPoints, - expectedRoutes: new List { expectedRoute }, + expectedRoutes: [expectedRoute], expectedErrorType, expectedStatusCode, expectedTagsCount: expectedErrorType == null ? 5 : 6); @@ -260,8 +263,10 @@ public async Task HttpRequestMethodIsCapturedAsPerSpec(string originalMethod, st }) .CreateClient(); - var message = new HttpRequestMessage(); - message.Method = new HttpMethod(originalMethod); + var message = new HttpRequestMessage + { + Method = new HttpMethod(originalMethod), + }; try { @@ -370,7 +375,7 @@ private static void AssertMetricPoint( Assert.True(sum > 0); var attributes = new KeyValuePair[metricPoint.Tags.Count]; - int i = 0; + var i = 0; foreach (var tag in metricPoint.Tags) { attributes[i++] = tag; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs index 44d0e84e43..e14243fbbe 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs @@ -11,7 +11,7 @@ namespace RouteTests; public static class RoutingTestCases { - private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions + private static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new JsonStringEnumConverter() }, @@ -37,7 +37,7 @@ private static List GetArgumentsFromTestCaseObject(IEnumerable apps = new(); + private readonly Dictionary apps = []; private readonly RouteInfoDiagnosticObserver diagnostics = new(); - private readonly List testResults = new(); + private readonly List testResults = []; public RoutingTestFixture() { diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs index e140a3bb60..c6cbc6fba4 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs @@ -20,8 +20,8 @@ public class RoutingTests : IClassFixture private const string HttpRoute = "http.route"; private readonly RoutingTestFixture fixture; - private readonly List exportedActivities = new(); - private readonly List exportedMetrics = new(); + private readonly List exportedActivities = []; + private readonly List exportedMetrics = []; public RoutingTests(RoutingTestFixture fixture) { @@ -58,7 +58,7 @@ public async Task TestHttpRoute(TestCase testCase) meterProvider.ForceFlush(); - var durationMetric = this.exportedMetrics.Single(x => x.Name == "http.server.request.duration" || x.Name == "http.server.duration"); + var durationMetric = this.exportedMetrics.Single(x => x.Name is "http.server.request.duration" or "http.server.duration"); var metricPoints = new List(); foreach (var mp in durationMetric.GetMetricPoints()) { @@ -69,7 +69,7 @@ public async Task TestHttpRoute(TestCase testCase) var metricPoint = Assert.Single(metricPoints); GetTagsFromActivity(activity, out var activityHttpStatusCode, out var activityHttpMethod, out var activityHttpRoute); - GetTagsFromMetricPoint(Environment.Version.Major < 8, metricPoint, out var metricHttpStatusCode, out var metricHttpMethod, out var metricHttpRoute); + GetTagsFromMetricPoint(metricPoint, out var metricHttpStatusCode, out var metricHttpMethod, out var metricHttpRoute); Assert.Equal(testCase.ExpectedStatusCode, activityHttpStatusCode); Assert.Equal(testCase.ExpectedStatusCode, metricHttpStatusCode); @@ -78,7 +78,7 @@ public async Task TestHttpRoute(TestCase testCase) // TODO: The CurrentHttpRoute property will go away. It They only serve to capture status quo. // If CurrentHttpRoute is null, then that means we already conform to the correct behavior. - var expectedHttpRoute = testCase.CurrentHttpRoute != null ? testCase.CurrentHttpRoute : testCase.ExpectedHttpRoute; + var expectedHttpRoute = testCase.CurrentHttpRoute ?? testCase.ExpectedHttpRoute; Assert.Equal(expectedHttpRoute, activityHttpRoute); Assert.Equal(expectedHttpRoute, metricHttpRoute); @@ -112,7 +112,7 @@ private static void GetTagsFromActivity(Activity activity, out int httpStatusCod httpRoute = activity.GetTagItem(HttpRoute) as string ?? string.Empty; } - private static void GetTagsFromMetricPoint(bool useLegacyConventions, MetricPoint metricPoint, out int httpStatusCode, out string httpMethod, out string? httpRoute) + private static void GetTagsFromMetricPoint(MetricPoint metricPoint, out int httpStatusCode, out string httpMethod, out string? httpRoute) { var expectedStatusCodeKey = HttpStatusCode; var expectedHttpMethodKey = HttpMethod; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs index 20fc1f281b..98c15a18ba 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs @@ -19,7 +19,7 @@ public ActionDescriptorInfo(ActionDescriptor actionDescriptor) { this.AttributeRouteInfo = actionDescriptor.AttributeRouteInfo?.Template; - this.ActionParameters = new List(); + this.ActionParameters = []; foreach (var item in actionDescriptor.Parameters) { this.ActionParameters.Add(item.Name); diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/AttributeRouteController.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/AttributeRouteController.cs index 93e4174166..5394349281 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/AttributeRouteController.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/AttributeRouteController.cs @@ -14,8 +14,10 @@ public class AttributeRouteController : ControllerBase public IActionResult Get() => this.Ok(); [HttpGet("[action]/{id}")] +#pragma warning disable IDE0060 // Remove unused parameter public IActionResult Get(int id) => this.Ok(); [HttpGet("{id}/[action]")] public IActionResult GetWithActionNameInDifferentSpotInTemplate(int id) => this.Ok(); +#pragma warning restore IDE0060 // Remove unused parameter } diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/ConventionalRouteController.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/ConventionalRouteController.cs index ac6bc3be0f..4e8dafd4b3 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/ConventionalRouteController.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/Controllers/ConventionalRouteController.cs @@ -9,7 +9,9 @@ public class ConventionalRouteController : Controller { public IActionResult Default() => this.Ok(); +#pragma warning disable IDE0060 // Remove unused parameter public IActionResult ActionWithParameter(int id) => this.Ok(); public IActionResult ActionWithStringParameter(string id, int num) => this.Ok(); +#pragma warning restore IDE0060 // Remove unused parameter } diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs index 610145dbc7..0d8d2e9668 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs @@ -52,9 +52,6 @@ public void SetValues(HttpContext context) public void SetValues(ActionDescriptor actionDescriptor) { - if (this.ActionDescriptor == null) - { - this.ActionDescriptor = new ActionDescriptorInfo(actionDescriptor); - } + this.ActionDescriptor ??= new ActionDescriptorInfo(actionDescriptor); } } diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs index 3b3feb59e1..e5e4025ec4 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs @@ -20,7 +20,7 @@ internal sealed class RouteInfoDiagnosticObserver : IDisposable, IObserver listenerSubscriptions = new(); + private readonly List listenerSubscriptions = []; private IDisposable? allSourcesSubscription; private long disposed; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs index aa864b5bab..cc9d682db6 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs @@ -49,21 +49,15 @@ internal class TestApplicationFactory public static WebApplication? CreateApplication(TestApplicationScenario config) { Debug.Assert(Directory.Exists(ContentRootPath), $"Cannot find ContentRootPath: {ContentRootPath}"); - switch (config) + return config switch { - case TestApplicationScenario.ConventionalRouting: - return CreateConventionalRoutingApplication(); - case TestApplicationScenario.AttributeRouting: - return CreateAttributeRoutingApplication(); - case TestApplicationScenario.MinimalApi: - return CreateMinimalApiApplication(); - case TestApplicationScenario.RazorPages: - return CreateRazorPagesApplication(); - case TestApplicationScenario.ExceptionMiddleware: - return CreateExceptionHandlerApplication(); - default: - throw new ArgumentException($"Invalid {nameof(TestApplicationScenario)}"); - } + TestApplicationScenario.ConventionalRouting => CreateConventionalRoutingApplication(), + TestApplicationScenario.AttributeRouting => CreateAttributeRoutingApplication(), + TestApplicationScenario.MinimalApi => CreateMinimalApiApplication(), + TestApplicationScenario.RazorPages => CreateRazorPagesApplication(), + TestApplicationScenario.ExceptionMiddleware => CreateExceptionHandlerApplication(), + _ => throw new ArgumentException($"Invalid {nameof(TestApplicationScenario)}"), + }; } private static WebApplication CreateConventionalRoutingApplication() diff --git a/test/TestApp.AspNetCore/CallbackMiddleware.cs b/test/TestApp.AspNetCore/CallbackMiddleware.cs index 9ee236845d..4afcc87a4d 100644 --- a/test/TestApp.AspNetCore/CallbackMiddleware.cs +++ b/test/TestApp.AspNetCore/CallbackMiddleware.cs @@ -3,7 +3,7 @@ namespace TestApp.AspNetCore; -public class CallbackMiddleware +internal class CallbackMiddleware { private readonly TestCallbackMiddleware testCallbackMiddleware; private readonly RequestDelegate next; diff --git a/test/TestApp.AspNetCore/Controllers/ChildActivityController.cs b/test/TestApp.AspNetCore/Controllers/ChildActivityController.cs index b55927000f..068e587204 100644 --- a/test/TestApp.AspNetCore/Controllers/ChildActivityController.cs +++ b/test/TestApp.AspNetCore/Controllers/ChildActivityController.cs @@ -8,7 +8,9 @@ namespace TestApp.AspNetCore.Controllers; +#pragma warning disable CA1515 public class ChildActivityController : Controller +#pragma warning restore CA1515 { [HttpGet] [Route("api/GetChildActivityTraceContext")] diff --git a/test/TestApp.AspNetCore/Controllers/ErrorController.cs b/test/TestApp.AspNetCore/Controllers/ErrorController.cs index 24c904cfe9..acecf79292 100644 --- a/test/TestApp.AspNetCore/Controllers/ErrorController.cs +++ b/test/TestApp.AspNetCore/Controllers/ErrorController.cs @@ -6,7 +6,9 @@ namespace TestApp.AspNetCore.Controllers; [Route("api/[controller]")] +#pragma warning disable CA1515 public class ErrorController : Controller +#pragma warning restore CA1515 { // GET api/error [HttpGet] diff --git a/test/TestApp.AspNetCore/Controllers/ValuesController.cs b/test/TestApp.AspNetCore/Controllers/ValuesController.cs index 27a9ab0d2d..6173415709 100644 --- a/test/TestApp.AspNetCore/Controllers/ValuesController.cs +++ b/test/TestApp.AspNetCore/Controllers/ValuesController.cs @@ -6,17 +6,20 @@ namespace TestApp.AspNetCore.Controllers; [Route("api/[controller]")] +#pragma warning disable CA1515 public class ValuesController : Controller +#pragma warning restore CA1515 { // GET api/values [HttpGet] public IEnumerable Get() { - return new string[] { "value1", "value2" }; + return ["value1", "value2"]; } // GET api/values/5 [HttpGet("{id}")] +#pragma warning disable IDE0060 // Remove unused parameter public string Get(int id) { return "value"; @@ -37,6 +40,7 @@ public void Put(int id, [FromBody] string value) // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) +#pragma warning restore IDE0060 // Remove unused parameter { } } diff --git a/test/TestApp.AspNetCore/Filters/ExceptionFilter1.cs b/test/TestApp.AspNetCore/Filters/ExceptionFilter1.cs index 1f05886069..9f23da3f0a 100644 --- a/test/TestApp.AspNetCore/Filters/ExceptionFilter1.cs +++ b/test/TestApp.AspNetCore/Filters/ExceptionFilter1.cs @@ -5,7 +5,9 @@ namespace TestApp.AspNetCore.Filters; +#pragma warning disable CA1515 public class ExceptionFilter1 : IExceptionFilter +#pragma warning restore CA1515 { public void OnException(ExceptionContext context) { diff --git a/test/TestApp.AspNetCore/Filters/ExceptionFilter2.cs b/test/TestApp.AspNetCore/Filters/ExceptionFilter2.cs index fc81905c65..4bf428d53f 100644 --- a/test/TestApp.AspNetCore/Filters/ExceptionFilter2.cs +++ b/test/TestApp.AspNetCore/Filters/ExceptionFilter2.cs @@ -5,7 +5,9 @@ namespace TestApp.AspNetCore.Filters; +#pragma warning disable CA1515 public class ExceptionFilter2 : IExceptionFilter +#pragma warning restore CA1515 { public void OnException(ExceptionContext context) { diff --git a/test/TestApp.AspNetCore/Program.cs b/test/TestApp.AspNetCore/Program.cs index 5cbe2b5e3a..c673e205eb 100644 --- a/test/TestApp.AspNetCore/Program.cs +++ b/test/TestApp.AspNetCore/Program.cs @@ -3,7 +3,9 @@ using TestApp.AspNetCore; +#pragma warning disable CA1515 public class Program +#pragma warning restore CA1515 { public static void Main(string[] args) { diff --git a/test/TestApp.AspNetCore/TestActivityMiddleware.cs b/test/TestApp.AspNetCore/TestActivityMiddleware.cs index be1e2e5a1e..e14ad9295c 100644 --- a/test/TestApp.AspNetCore/TestActivityMiddleware.cs +++ b/test/TestApp.AspNetCore/TestActivityMiddleware.cs @@ -3,7 +3,9 @@ namespace TestApp.AspNetCore; +#pragma warning disable CA1515 public class TestActivityMiddleware +#pragma warning restore CA1515 { public virtual void PreProcess(HttpContext context) { diff --git a/test/TestApp.AspNetCore/TestCallbackMiddleware.cs b/test/TestApp.AspNetCore/TestCallbackMiddleware.cs index ba11577ff0..50e563da16 100644 --- a/test/TestApp.AspNetCore/TestCallbackMiddleware.cs +++ b/test/TestApp.AspNetCore/TestCallbackMiddleware.cs @@ -3,7 +3,9 @@ namespace TestApp.AspNetCore; +#pragma warning disable CA1515 public class TestCallbackMiddleware +#pragma warning restore CA1515 { public virtual async Task ProcessAsync(HttpContext context) { diff --git a/test/TestApp.AspNetCore/TestMiddleware.cs b/test/TestApp.AspNetCore/TestMiddleware.cs index 39acf58db3..711814d263 100644 --- a/test/TestApp.AspNetCore/TestMiddleware.cs +++ b/test/TestApp.AspNetCore/TestMiddleware.cs @@ -3,7 +3,9 @@ namespace TestApp.AspNetCore; +#pragma warning disable CA1515 public static class TestMiddleware +#pragma warning restore CA1515 { private static readonly AsyncLocal?> Current = new();