diff --git a/build/Common.props b/build/Common.props index bbbe345136..ff82b6647f 100644 --- a/build/Common.props +++ b/build/Common.props @@ -44,7 +44,7 @@ [8.0.0,9.0) [1.9.0-beta.2] [1.9.0,2.0) - [1.10.0-beta.1] + [1.10.0-rc.1] [2.6.122,3.0) [2.4.0,3.0) [3.16.0,4.0) diff --git a/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md b/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md index 7ca97b842c..317de4751a 100644 --- a/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md +++ b/src/OpenTelemetry.Exporter.Geneva/CHANGELOG.md @@ -19,6 +19,9 @@ For configuration details see: [OtlpProtobufEncoding](./README.md#otlpprotobufencoding). +* Update OpenTelemetry SDK version to `1.10.0-rc.1`. + ([#2294](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/2294)) + ## 1.9.0 Released 2024-Jun-21 diff --git a/src/OpenTelemetry.Exporter.Geneva/Common.GenevaExporter.props b/src/OpenTelemetry.Exporter.Geneva/Common.GenevaExporter.props index 5570a7a1fe..78181066e1 100644 --- a/src/OpenTelemetry.Exporter.Geneva/Common.GenevaExporter.props +++ b/src/OpenTelemetry.Exporter.Geneva/Common.GenevaExporter.props @@ -1,6 +1,6 @@ - $(OpenTelemetryCoreLatestVersion) + $(OpenTelemetryCoreLatestPrereleaseVersion) diff --git a/src/OpenTelemetry.Exporter.Geneva/Internal/ReentrantExportProcessor.cs b/src/OpenTelemetry.Exporter.Geneva/Internal/ReentrantExportProcessor.cs index b0da2159fc..71ac6bbb6e 100644 --- a/src/OpenTelemetry.Exporter.Geneva/Internal/ReentrantExportProcessor.cs +++ b/src/OpenTelemetry.Exporter.Geneva/Internal/ReentrantExportProcessor.cs @@ -1,21 +1,11 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -using System.Linq.Expressions; -using System.Reflection; - namespace OpenTelemetry.Exporter.Geneva; -// This export processor exports without synchronization. -// Once OpenTelemetry .NET officially support this, -// we can get rid of this class. -// This is currently only used in ETW export, where we know -// that the underlying system is safe under concurrent calls. internal class ReentrantExportProcessor : BaseExportProcessor where T : class { - private static readonly Func> CreateBatch = BuildCreateBatchDelegate(); - public ReentrantExportProcessor(BaseExporter exporter) : base(exporter) { @@ -23,16 +13,6 @@ public ReentrantExportProcessor(BaseExporter exporter) protected override void OnExport(T data) { - this.exporter.Export(CreateBatch(data)); - } - - private static Func> BuildCreateBatchDelegate() - { - var flags = BindingFlags.Instance | BindingFlags.NonPublic; - var ctor = typeof(Batch).GetConstructor(flags, null, new Type[] { typeof(T) }, null) - ?? throw new InvalidOperationException("Batch ctor accepting a single item could not be found reflectively"); - var value = Expression.Parameter(typeof(T), null); - var lambda = Expression.Lambda>>(Expression.New(ctor, value), value); - return lambda.Compile(); + this.exporter.Export(new(data)); } } diff --git a/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md b/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md index 0803ff2ac5..b4f4b438cc 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md +++ b/src/OpenTelemetry.Exporter.OneCollector/CHANGELOG.md @@ -15,6 +15,10 @@ also be applied to subsequent `LogRecord`s in the same batch. ([#2205](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/2205)) +* Update OpenTelemetry SDK version to `1.10.0-rc.1` and removed the direct + reference to `Microsoft.Extensions.Configuration.Binder`. + ([#2295](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/2295)) + ## 1.9.3 Released 2024-Oct-11 diff --git a/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj b/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj index dfb5f27c1d..c8d10cef7d 100644 --- a/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj +++ b/src/OpenTelemetry.Exporter.OneCollector/OpenTelemetry.Exporter.OneCollector.csproj @@ -18,13 +18,12 @@ - $(OpenTelemetryCoreLatestVersion) + $(OpenTelemetryCoreLatestPrereleaseVersion) $(DefineConstants);EXPOSE_EXPERIMENTAL_FEATURES - diff --git a/src/OpenTelemetry.Instrumentation.ElasticsearchClient/Implementation/ElasticsearchRequestPipelineDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.ElasticsearchClient/Implementation/ElasticsearchRequestPipelineDiagnosticListener.cs index 0687bd2582..5f57879521 100644 --- a/src/OpenTelemetry.Instrumentation.ElasticsearchClient/Implementation/ElasticsearchRequestPipelineDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.ElasticsearchClient/Implementation/ElasticsearchRequestPipelineDiagnosticListener.cs @@ -57,6 +57,8 @@ public override void OnEventWritten(string name, object? payload) case "CallElasticsearch.Stop": this.OnStopActivity(activity, payload); break; + default: + break; } } @@ -69,12 +71,7 @@ private static string GetDisplayName(Activity activity, object? method, string? case "CallElasticsearch" when method != null: { var methodName = MethodNameCache.GetOrAdd(method, $"Elasticsearch {method}"); - if (elasticType == null) - { - return methodName; - } - - return $"{methodName} {elasticType}"; + return elasticType == null ? methodName : $"{methodName} {elasticType}"; } default: @@ -122,7 +119,7 @@ private string ParseAndFormatRequest(string debugInformation) var request = ParseRequest.Match(debugInformation); if (request.Success) { - string? body = request.Groups[1]?.Value?.Trim(); + var body = request.Groups[1]?.Value?.Trim(); if (body == null) { return debugInformation; @@ -193,7 +190,7 @@ private void OnStartActivity(Activity activity, object? payload) } var uriHostNameType = Uri.CheckHostName(uri.Host); - if (uriHostNameType == UriHostNameType.IPv4 || uriHostNameType == UriHostNameType.IPv6) + if (uriHostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6) { activity.SetTag(SemanticConventions.AttributeNetPeerIp, uri.Host); } @@ -269,14 +266,10 @@ private void OnStopActivity(Activity activity, object? payload) if (originalException is HttpRequestException) { - if (originalException.InnerException is SocketException exception) + if (originalException.InnerException is SocketException { SocketErrorCode: SocketError.HostNotFound }) { - switch (exception.SocketErrorCode) - { - case SocketError.HostNotFound: - activity.SetStatus(Status.Error.WithDescription(originalException.Message)); - return; - } + activity.SetStatus(Status.Error.WithDescription(originalException.Message)); + return; } if (originalException.InnerException != null) diff --git a/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersInstrumentationOptions.cs b/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersInstrumentationOptions.cs index 7fdc25d72b..8e4df4cc81 100644 --- a/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersInstrumentationOptions.cs +++ b/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersInstrumentationOptions.cs @@ -8,7 +8,7 @@ namespace OpenTelemetry.Instrumentation.EventCounters; /// public class EventCountersInstrumentationOptions { - internal readonly HashSet EventSourceNames = new(); + internal readonly HashSet EventSourceNames = []; /// /// Gets or sets the subscription interval in seconds for reading values diff --git a/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersMetrics.cs b/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersMetrics.cs index 8b42388883..4cb8444f76 100644 --- a/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersMetrics.cs +++ b/src/OpenTelemetry.Instrumentation.EventCounters/EventCountersMetrics.cs @@ -18,8 +18,8 @@ internal sealed class EventCountersMetrics : EventListener private const int MaxInstrumentNameLength = 63; private readonly EventCountersInstrumentationOptions options; - private readonly List preInitEventSources = new(); - private readonly List enabledEventSources = new(); + private readonly List preInitEventSources = []; + private readonly List enabledEventSources = []; private readonly ConcurrentDictionary<(string, string), Instrument> instruments = new(); private readonly ConcurrentDictionary<(string, string), double> values = new(); private bool isDisposed; @@ -45,7 +45,7 @@ public EventCountersMetrics(EventCountersInstrumentationOptions options) { this.options = options; - foreach (EventSource eventSource in this.preInitEventSources) + foreach (var eventSource in this.preInitEventSources) { if (this.options.ShouldListenToSource(eventSource.Name)) { @@ -167,7 +167,7 @@ private static Dictionary GetEnableEventsArguments(EventCounters /// private static string GetInstrumentName(string sourceName, string eventName) { - int totalLength = Prefix.Length + 1 + sourceName.Length + 1 + eventName.Length; + var totalLength = Prefix.Length + 1 + sourceName.Length + 1 + eventName.Length; if (totalLength <= MaxInstrumentNameLength) { return string.Concat(Prefix, ".", sourceName, ".", eventName); diff --git a/src/OpenTelemetry.Instrumentation.Hangfire/Implementation/HangfireInstrumentationJobFilterAttribute.cs b/src/OpenTelemetry.Instrumentation.Hangfire/Implementation/HangfireInstrumentationJobFilterAttribute.cs index f793e52a62..0f0afaaa2a 100644 --- a/src/OpenTelemetry.Instrumentation.Hangfire/Implementation/HangfireInstrumentationJobFilterAttribute.cs +++ b/src/OpenTelemetry.Instrumentation.Hangfire/Implementation/HangfireInstrumentationJobFilterAttribute.cs @@ -122,7 +122,7 @@ private static void InjectActivityProperties(IDictionary jobPara private static IEnumerable ExtractActivityProperties(Dictionary telemetryData, string key) { - return telemetryData.TryGetValue(key, out var value) ? new[] { value } : Enumerable.Empty(); + return telemetryData.TryGetValue(key, out var value) ? [value] : []; } private void SetStatusAndRecordException(Activity activity, Exception exception) diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs index 40daae9660..4400a15f5b 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientInstrumentation.cs @@ -10,18 +10,18 @@ namespace OpenTelemetry.Instrumentation.Http; /// internal sealed class HttpClientInstrumentation : IDisposable { - private static readonly HashSet ExcludedDiagnosticSourceEventsNet7OrGreater = new() - { + private static readonly HashSet ExcludedDiagnosticSourceEventsNet7OrGreater = + [ "System.Net.Http.Request", "System.Net.Http.Response", - "System.Net.Http.HttpRequestOut", - }; + "System.Net.Http.HttpRequestOut" + ]; - private static readonly HashSet ExcludedDiagnosticSourceEvents = new() - { + private static readonly HashSet ExcludedDiagnosticSourceEvents = + [ "System.Net.Http.Request", - "System.Net.Http.Response", - }; + "System.Net.Http.Response" + ]; private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber; @@ -43,14 +43,9 @@ public HttpClientInstrumentation(HttpClientTraceInstrumentationOptions options) // the framework will fall back to creating activity anyways due to active diagnostic source listener // To prevent this, isEnabled is implemented which will return false always // so that the sampler's decision is respected. - if (HttpHandlerDiagnosticListener.IsNet7OrGreater) - { - this.diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabledNet7OrGreater, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); - } - else - { - this.diagnosticSourceSubscriber = new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabled, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); - } + this.diagnosticSourceSubscriber = HttpHandlerDiagnosticListener.IsNet7OrGreater + ? new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabledNet7OrGreater, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent) + : new DiagnosticSourceSubscriber(new HttpHandlerDiagnosticListener(options), this.isEnabled, HttpInstrumentationEventSource.Log.UnknownErrorProcessingEvent); this.diagnosticSourceSubscriber.Subscribe(); } diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs index e03cd6a46a..8913f8daf7 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientMetrics.cs @@ -10,11 +10,11 @@ namespace OpenTelemetry.Instrumentation.Http; /// internal sealed class HttpClientMetrics : IDisposable { - private static readonly HashSet ExcludedDiagnosticSourceEvents = new() - { + private static readonly HashSet ExcludedDiagnosticSourceEvents = + [ "System.Net.Http.Request", - "System.Net.Http.Response", - }; + "System.Net.Http.Response" + ]; private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber; diff --git a/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs b/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs index e63f77bae3..cba754cc9f 100644 --- a/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs +++ b/src/OpenTelemetry.Instrumentation.Http/HttpClientTraceInstrumentationOptions.cs @@ -165,7 +165,7 @@ internal bool EventFilterHttpRequestMessage(string activityName, object arg1) { return this.FilterHttpRequestMessage == null || - !TryParseHttpRequestMessage(activityName, arg1, out HttpRequestMessage? requestMessage) || + !TryParseHttpRequestMessage(activityName, arg1, out var requestMessage) || this.FilterHttpRequestMessage(requestMessage); } catch (Exception ex) diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs index 14e2ebbec7..5b65c673d0 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerDiagnosticListener.cs @@ -65,6 +65,8 @@ public override void OnEventWritten(string name, object? payload) this.OnException(activity, payload); } + break; + default: break; } } @@ -81,7 +83,7 @@ public void OnStartActivity(Activity activity, object? payload) // By this time, samplers have already run and // activity.IsAllDataRequested populated accordingly. - if (!TryFetchRequest(payload, out HttpRequestMessage? request)) + if (!TryFetchRequest(payload, out var request)) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnStartActivity)); return; @@ -109,7 +111,7 @@ public void OnStartActivity(Activity activity, object? payload) { try { - if (this.options.EventFilterHttpRequestMessage(activity.OperationName, request) == false) + if (!this.options.EventFilterHttpRequestMessage(activity.OperationName, request)) { HttpInstrumentationEventSource.Log.RequestIsFilteredOut(activity.OperationName); activity.IsAllDataRequested = false; @@ -161,12 +163,7 @@ public void OnStartActivity(Activity activity, object? payload) #endif static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) { - if (!StartRequestFetcher.TryFetch(payload, out request) || request == null) - { - return false; - } - - return true; + return StartRequestFetcher.TryFetch(payload, out request) && request != null; } } @@ -176,7 +173,7 @@ public void OnStopActivity(Activity activity, object? payload) { var requestTaskStatus = GetRequestStatus(payload); - ActivityStatusCode currentStatusCode = activity.Status; + var currentStatusCode = activity.Status; if (requestTaskStatus != TaskStatus.RanToCompletion) { if (requestTaskStatus == TaskStatus.Canceled) @@ -200,7 +197,7 @@ public void OnStopActivity(Activity activity, object? payload) } } - if (TryFetchResponse(payload, out HttpResponseMessage? response)) + if (TryFetchResponse(payload, out var response)) { if (currentStatusCode == ActivityStatusCode.Unset) { @@ -246,12 +243,7 @@ static TaskStatus GetRequestStatus(object? payload) #endif static bool TryFetchResponse(object? payload, [NotNullWhen(true)] out HttpResponseMessage? response) { - if (StopResponseFetcher.TryFetch(payload, out response) && response != null) - { - return true; - } - - return false; + return StopResponseFetcher.TryFetch(payload, out response) && response != null; } } @@ -259,7 +251,7 @@ public void OnException(Activity activity, object? payload) { if (activity.IsAllDataRequested) { - if (!TryFetchException(payload, out Exception? exc)) + if (!TryFetchException(payload, out var exc)) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnException)); return; @@ -299,12 +291,7 @@ public void OnException(Activity activity, object? payload) #endif static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception? exc) { - if (!StopExceptionFetcher.TryFetch(payload, out exc) || exc == null) - { - return false; - } - - return true; + return StopExceptionFetcher.TryFetch(payload, out exc) && exc != null; } } diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs index 7a841bf654..dd3dc6970c 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpHandlerMetricsDiagnosticListener.cs @@ -39,7 +39,7 @@ public HttpHandlerMetricsDiagnosticListener(string name) public static void OnStopEventWritten(Activity activity, object? payload) { - if (TryFetchRequest(payload, out HttpRequestMessage? request)) + if (TryFetchRequest(payload, out var request)) { // see the spec https://github.com/open-telemetry/semantic-conventions/blob/v1.23.0/docs/http/http-metrics.md TagList tags = default; @@ -58,7 +58,7 @@ public static void OnStopEventWritten(Activity activity, object? payload) } } - if (TryFetchResponse(payload, out HttpResponseMessage? response)) + if (TryFetchResponse(payload, out var response)) { tags.Add(new KeyValuePair(SemanticConventions.AttributeNetworkProtocolVersion, RequestDataHelper.GetHttpProtocolVersion(response.Version))); tags.Add(new KeyValuePair(SemanticConventions.AttributeHttpResponseStatusCode, TelemetryHelper.GetBoxedStatusCode(response.StatusCode))); @@ -98,21 +98,25 @@ public static void OnStopEventWritten(Activity activity, object? payload) #if NET [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The System.Net.Http library guarantees that top-level properties are preserved")] #endif - static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) => - StopRequestFetcher.TryFetch(payload, out request) && request != null; + static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) + { + return StopRequestFetcher.TryFetch(payload, out request) && request != null; + } // The AOT-annotation DynamicallyAccessedMembers in System.Net.Http library ensures that top-level properties on the payload object are always preserved. // see https://github.com/dotnet/runtime/blob/f9246538e3d49b90b0e9128d7b1defef57cd6911/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs#L325 #if NET [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The System.Net.Http library guarantees that top-level properties are preserved")] #endif - static bool TryFetchResponse(object? payload, [NotNullWhen(true)] out HttpResponseMessage? response) => - StopResponseFetcher.TryFetch(payload, out response) && response != null; + static bool TryFetchResponse(object? payload, [NotNullWhen(true)] out HttpResponseMessage? response) + { + return StopResponseFetcher.TryFetch(payload, out response) && response != null; + } } public static void OnExceptionEventWritten(Activity activity, object? payload) { - if (!TryFetchException(payload, out Exception? exc) || !TryFetchRequest(payload, out HttpRequestMessage? request)) + if (!TryFetchException(payload, out var exc) || !TryFetchRequest(payload, out var request)) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerMetricsDiagnosticListener), nameof(OnExceptionEventWritten)); return; @@ -131,12 +135,7 @@ public static void OnExceptionEventWritten(Activity activity, object? payload) #endif static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception? exc) { - if (!StopExceptionFetcher.TryFetch(payload, out exc) || exc == null) - { - return false; - } - - return true; + return StopExceptionFetcher.TryFetch(payload, out exc) && exc != null; } // The AOT-annotation DynamicallyAccessedMembers in System.Net.Http library ensures that top-level properties on the payload object are always preserved. @@ -146,12 +145,7 @@ static bool TryFetchException(object? payload, [NotNullWhen(true)] out Exception #endif static bool TryFetchRequest(object? payload, [NotNullWhen(true)] out HttpRequestMessage? request) { - if (!RequestFetcher.TryFetch(payload, out request) || request == null) - { - return false; - } - - return true; + return RequestFetcher.TryFetch(payload, out request) && request != null; } } diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs index c99639639d..7f8ba01066 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/HttpWebRequestActivitySource.netfx.cs @@ -40,8 +40,6 @@ internal static class HttpWebRequestActivitySource private static readonly Meter WebRequestMeter = new(MeterName, Version); private static readonly Histogram HttpClientRequestDuration = WebRequestMeter.CreateHistogram("http.client.request.duration", "s", "Duration of HTTP client requests."); - private static HttpClientTraceInstrumentationOptions tracingOptions; - // Fields for reflection private static FieldInfo connectionGroupListField; private static Type connectionGroupType; @@ -86,14 +84,7 @@ static HttpWebRequestActivitySource() } } - internal static HttpClientTraceInstrumentationOptions TracingOptions - { - get => tracingOptions; - set - { - tracingOptions = value; - } - } + internal static HttpClientTraceInstrumentationOptions TracingOptions { get; set; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void AddRequestTagsAndInstrumentRequest(HttpWebRequest request, Activity activity) @@ -108,7 +99,7 @@ private static void AddRequestTagsAndInstrumentRequest(HttpWebRequest request, A activity.SetTag(SemanticConventions.AttributeServerAddress, request.RequestUri.Host); activity.SetTag(SemanticConventions.AttributeServerPort, request.RequestUri.Port); - activity.SetTag(SemanticConventions.AttributeUrlFull, HttpTagHelper.GetUriTagValueFromRequestUri(request.RequestUri, tracingOptions.DisableUrlQueryRedaction)); + activity.SetTag(SemanticConventions.AttributeUrlFull, HttpTagHelper.GetUriTagValueFromRequestUri(request.RequestUri, TracingOptions.DisableUrlQueryRedaction)); try { @@ -232,7 +223,7 @@ private static void ProcessRequest(HttpWebRequest request) return; } - Activity activity = enableTracing + var activity = enableTracing ? WebRequestActivitySource.StartActivity(ActivityName, ActivityKind.Client) : null; @@ -243,12 +234,12 @@ private static void ProcessRequest(HttpWebRequest request) // Eg: Parent could be the Asp.Net activity. InstrumentRequest(request, activityContext); - IAsyncResult asyncContext = writeAResultAccessor(request); + var asyncContext = writeAResultAccessor(request); if (asyncContext != null) { // Flow here is for [Begin]GetRequestStream[Async]. - AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); + var callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); asyncCallbackModifier(asyncContext, callback.AsyncCallback); } else @@ -256,7 +247,7 @@ private static void ProcessRequest(HttpWebRequest request) // Flow here is for [Begin]GetResponse[Async] without a prior call to [Begin]GetRequestStream[Async]. asyncContext = readAResultAccessor(request); - AsyncCallbackWrapper callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); + var callback = new AsyncCallbackWrapper(request, activity, asyncCallbackAccessor(asyncContext), Stopwatch.GetTimestamp()); asyncCallbackModifier(asyncContext, callback.AsyncCallback); } @@ -268,7 +259,7 @@ private static void ProcessRequest(HttpWebRequest request) private static void HookOrProcessResult(HttpWebRequest request) { - IAsyncResult writeAsyncContext = writeAResultAccessor(request); + var writeAsyncContext = writeAResultAccessor(request); if (writeAsyncContext == null || asyncCallbackAccessor(writeAsyncContext)?.Target is not AsyncCallbackWrapper writeAsyncContextCallback) { // If we already hooked into the read result during ProcessRequest or we hooked up after the fact already we don't need to do anything here. @@ -277,7 +268,7 @@ private static void HookOrProcessResult(HttpWebRequest request) // If we got here it means the user called [Begin]GetRequestStream[Async] and we have to hook the read result after the fact. - IAsyncResult readAsyncContext = readAResultAccessor(request); + var readAsyncContext = readAResultAccessor(request); if (readAsyncContext == null) { // We're still trying to establish the connection (no read has started). @@ -295,7 +286,7 @@ private static void HookOrProcessResult(HttpWebRequest request) } // Hook into the result callback if it hasn't already fired. - AsyncCallbackWrapper callback = new AsyncCallbackWrapper(writeAsyncContextCallback.Request, writeAsyncContextCallback.Activity, asyncCallbackAccessor(readAsyncContext), Stopwatch.GetTimestamp()); + var callback = new AsyncCallbackWrapper(writeAsyncContextCallback.Request, writeAsyncContextCallback.Activity, asyncCallbackAccessor(readAsyncContext), Stopwatch.GetTimestamp()); asyncCallbackModifier(readAsyncContext, callback.AsyncCallback); } @@ -304,7 +295,7 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC HttpStatusCode? httpStatusCode = null; string errorType = null; Version protocolVersion = null; - ActivityStatusCode activityStatus = ActivityStatusCode.Unset; + var activityStatus = ActivityStatusCode.Unset; // Activity may be null if we are not tracing in these cases: // 1. No listeners @@ -349,7 +340,7 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC } else { - HttpWebResponse response = (HttpWebResponse)result; + var response = (HttpWebResponse)result; if (forceResponseCopy || (asyncCallback == null && isContextAwareResultChecker(asyncResult))) { @@ -358,13 +349,12 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC // in which case they could dispose the HttpWebResponse before our listeners have a chance to work with it. // Disposed HttpWebResponse throws when accessing properties, so let's make a copy of the data to ensure that doesn't happen. - HttpWebResponse responseCopy = httpWebResponseCtor( - new object[] - { - uriAccessor(response), verbAccessor(response), coreResponseDataAccessor(response), mediaTypeAccessor(response), + var responseCopy = httpWebResponseCtor( + [ + uriAccessor(response), verbAccessor(response), coreResponseDataAccessor(response), mediaTypeAccessor(response), usesProxySemanticsAccessor(response), DecompressionMethods.None, - isWebSocketResponseAccessor(response), connectionGroupNameAccessor(response), - }); + isWebSocketResponseAccessor(response), connectionGroupNameAccessor(response) + ]); if (activity != null) { @@ -458,8 +448,8 @@ private static void PrepareReflectionObjects() { // At any point, if the operation failed, it should just throw. The caller should catch all exceptions and swallow. - Type servicePointType = typeof(ServicePoint); - Assembly systemNetHttpAssembly = servicePointType.Assembly; + var servicePointType = typeof(ServicePoint); + var systemNetHttpAssembly = servicePointType.Assembly; connectionGroupListField = servicePointType.GetField("m_ConnectionGroupList", BindingFlags.Instance | BindingFlags.NonPublic); connectionGroupType = systemNetHttpAssembly?.GetType("System.Net.ConnectionGroup"); connectionListField = connectionGroupType?.GetField("m_ConnectionList", BindingFlags.Instance | BindingFlags.NonPublic); @@ -489,7 +479,7 @@ private static void PrepareReflectionObjects() private static bool PrepareAsyncResultReflectionObjects(Assembly systemNetHttpAssembly) { - Type lazyAsyncResultType = systemNetHttpAssembly?.GetType("System.Net.LazyAsyncResult"); + var lazyAsyncResultType = systemNetHttpAssembly?.GetType("System.Net.LazyAsyncResult"); if (lazyAsyncResultType != null) { asyncCallbackAccessor = CreateFieldGetter(lazyAsyncResultType, "m_AsyncCallback", BindingFlags.NonPublic | BindingFlags.Instance); @@ -500,7 +490,7 @@ private static bool PrepareAsyncResultReflectionObjects(Assembly systemNetHttpAs resultAccessor = CreateFieldGetter(lazyAsyncResultType, "m_Result", BindingFlags.NonPublic | BindingFlags.Instance); } - Type contextAwareResultType = systemNetHttpAssembly?.GetType("System.Net.ContextAwareResult"); + var contextAwareResultType = systemNetHttpAssembly?.GetType("System.Net.ContextAwareResult"); if (contextAwareResultType != null) { isContextAwareResultChecker = CreateTypeChecker(contextAwareResultType); @@ -517,8 +507,8 @@ private static bool PrepareAsyncResultReflectionObjects(Assembly systemNetHttpAs private static bool PrepareHttpWebResponseReflectionObjects(Assembly systemNetHttpAssembly) { - Type knownHttpVerbType = systemNetHttpAssembly?.GetType("System.Net.KnownHttpVerb"); - Type coreResponseData = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData"); + var knownHttpVerbType = systemNetHttpAssembly?.GetType("System.Net.KnownHttpVerb"); + var coreResponseData = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData"); if (knownHttpVerbType != null && coreResponseData != null) { @@ -529,7 +519,7 @@ private static bool PrepareHttpWebResponseReflectionObjects(Assembly systemNetHt typeof(bool), typeof(string), }; - ConstructorInfo ctor = typeof(HttpWebResponse).GetConstructor( + var ctor = typeof(HttpWebResponse).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, constructorParameterTypes, @@ -563,11 +553,11 @@ private static bool PrepareHttpWebResponseReflectionObjects(Assembly systemNetHt private static void PerformInjection() { - FieldInfo servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic) - ?? throw new InvalidOperationException("Unable to access the ServicePointTable field"); + var servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("Unable to access the ServicePointTable field"); - Hashtable originalTable = servicePointTableField.GetValue(null) as Hashtable; - ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? new Hashtable()); + var originalTable = servicePointTableField.GetValue(null) as Hashtable; + var newTable = new ServicePointHashtable(originalTable ?? []); foreach (DictionaryEntry existingServicePoint in originalTable) { @@ -586,8 +576,8 @@ private static void HookServicePoint(object value) // Replace the ConnectionGroup hashtable inside this ServicePoint object, // which allows us to intercept each new ConnectionGroup object added under // this ServicePoint. - Hashtable originalTable = connectionGroupListField.GetValue(servicePoint) as Hashtable; - ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? new Hashtable()); + var originalTable = connectionGroupListField.GetValue(servicePoint) as Hashtable; + var newTable = new ConnectionGroupHashtable(originalTable ?? []); foreach (DictionaryEntry existingConnectionGroup in originalTable) { @@ -605,10 +595,10 @@ private static void HookConnectionGroup(object value) // Replace the Connection arraylist inside this ConnectionGroup object, // which allows us to intercept each new Connection object added under // this ConnectionGroup. - ArrayList originalArrayList = connectionListField.GetValue(value) as ArrayList; - ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? new ArrayList()); + var originalArrayList = connectionListField.GetValue(value) as ArrayList; + var newArrayList = new ConnectionArrayList(originalArrayList ?? []); - foreach (object connection in originalArrayList) + foreach (var connection in originalArrayList) { HookConnection(connection); } @@ -624,8 +614,8 @@ private static void HookConnection(object value) // Replace the HttpWebRequest arraylist inside this Connection object, // which allows us to intercept each new HttpWebRequest object added under // this Connection. - ArrayList originalArrayList = writeListField.GetValue(value) as ArrayList; - HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? new ArrayList()); + var originalArrayList = writeListField.GetValue(value) as ArrayList; + var newArrayList = new HttpWebRequestArrayList(originalArrayList ?? []); writeListField.SetValue(value, newArrayList); } @@ -634,12 +624,12 @@ private static void HookConnection(object value) private static Func CreateFieldGetter(string fieldName, BindingFlags flags) where TClass : class { - FieldInfo field = typeof(TClass).GetField(fieldName, flags); + var field = typeof(TClass).GetField(fieldName, flags); if (field != null) { - string methodName = field.ReflectedType.FullName + ".get_" + field.Name; - DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(TClass) }, true); - ILGenerator generator = getterMethod.GetILGenerator(); + var methodName = field.ReflectedType.FullName + ".get_" + field.Name; + var getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(TClass)], true); + var generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, field); generator.Emit(OpCodes.Ret); @@ -655,12 +645,12 @@ private static Func CreateFieldGetter(string fie /// private static Func CreateFieldGetter(Type classType, string fieldName, BindingFlags flags) { - FieldInfo field = classType.GetField(fieldName, flags); + var field = classType.GetField(fieldName, flags); if (field != null) { - string methodName = classType.FullName + ".get_" + field.Name; - DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(object) }, true); - ILGenerator generator = getterMethod.GetILGenerator(); + var methodName = classType.FullName + ".get_" + field.Name; + var getterMethod = new DynamicMethod(methodName, typeof(TField), [typeof(object)], true); + var generator = getterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); generator.Emit(OpCodes.Ldfld, field); @@ -678,12 +668,12 @@ private static Func CreateFieldGetter(Type classType, st /// private static Action CreateFieldSetter(Type classType, string fieldName, BindingFlags flags) { - FieldInfo field = classType.GetField(fieldName, flags); + var field = classType.GetField(fieldName, flags); if (field != null) { - string methodName = classType.FullName + ".set_" + field.Name; - DynamicMethod setterMethod = new DynamicMethod(methodName, null, new[] { typeof(object), typeof(TField) }, true); - ILGenerator generator = setterMethod.GetILGenerator(); + var methodName = classType.FullName + ".set_" + field.Name; + var setterMethod = new DynamicMethod(methodName, null, [typeof(object), typeof(TField)], true); + var generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, classType); generator.Emit(OpCodes.Ldarg_1); @@ -701,9 +691,9 @@ private static Action CreateFieldSetter(Type classType, /// private static Func CreateTypeChecker(Type classType) { - string methodName = classType.FullName + ".typeCheck"; - DynamicMethod setterMethod = new DynamicMethod(methodName, typeof(bool), new[] { typeof(object) }, true); - ILGenerator generator = setterMethod.GetILGenerator(); + var methodName = classType.FullName + ".typeCheck"; + var setterMethod = new DynamicMethod(methodName, typeof(bool), [typeof(object)], true); + var generator = setterMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Isinst, classType); generator.Emit(OpCodes.Ldnull); @@ -718,13 +708,13 @@ private static Func CreateTypeChecker(Type classType) /// private static Func CreateTypeInstance(ConstructorInfo constructorInfo) { - Type classType = typeof(T); - string methodName = classType.FullName + ".ctor"; - DynamicMethod setterMethod = new DynamicMethod(methodName, classType, new Type[] { typeof(object[]) }, true); - ILGenerator generator = setterMethod.GetILGenerator(); + var classType = typeof(T); + var methodName = classType.FullName + ".ctor"; + var setterMethod = new DynamicMethod(methodName, classType, [typeof(object[])], true); + var generator = setterMethod.GetILGenerator(); - ParameterInfo[] ctorParams = constructorInfo.GetParameters(); - for (int i = 0; i < ctorParams.Length; i++) + var ctorParams = constructorInfo.GetParameters(); + for (var i = 0; i < ctorParams.Length; i++) { generator.Emit(OpCodes.Ldarg_0); switch (i) @@ -742,7 +732,7 @@ private static Func CreateTypeInstance(ConstructorInfo construct } generator.Emit(OpCodes.Ldelem_Ref); - Type paramType = ctorParams[i].ParameterType; + var paramType = ctorParams[i].ParameterType; generator.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType); } @@ -1083,7 +1073,7 @@ public override void TrimToSize() public ArrayList Swap() { - ArrayList old = this.list; + var old = this.list; this.list = new ArrayList(old.Capacity); return old; } @@ -1125,7 +1115,7 @@ public HttpWebRequestArrayList(ArrayList list) public override int Add(object value) { // Add before firing events so if some user code cancels/aborts the request it will be found in the outstanding list. - int index = base.Add(value); + var index = base.Add(value); if (value is HttpWebRequest request) { @@ -1137,7 +1127,7 @@ public override int Add(object value) public override void RemoveAt(int index) { - object request = this[index]; + var request = this[index]; base.RemoveAt(index); @@ -1149,8 +1139,8 @@ public override void RemoveAt(int index) public override void Clear() { - ArrayList oldList = this.Swap(); - for (int i = 0; i < oldList.Count; i++) + var oldList = this.Swap(); + for (var i = 0; i < oldList.Count; i++) { if (oldList[i] is HttpWebRequest request) { @@ -1183,8 +1173,8 @@ public AsyncCallbackWrapper(HttpWebRequest request, Activity activity, AsyncCall public void AsyncCallback(IAsyncResult asyncResult) { - object result = resultAccessor(asyncResult); - if (result is Exception || result is HttpWebResponse) + var result = resultAccessor(asyncResult); + if (result is Exception or HttpWebResponse) { ProcessResult( asyncResult, diff --git a/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs b/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs index 49bd111f4e..4a5a4e84f4 100644 --- a/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs +++ b/src/OpenTelemetry.Instrumentation.Http/Implementation/TelemetryHelper.cs @@ -12,24 +12,14 @@ internal static class TelemetryHelper public static object GetBoxedStatusCode(HttpStatusCode statusCode) { - int intStatusCode = (int)statusCode; - if (intStatusCode >= 100 && intStatusCode < 600) - { - return BoxedStatusCodes[intStatusCode - 100].Item1; - } - - return statusCode; + var intStatusCode = (int)statusCode; + return intStatusCode is >= 100 and < 600 ? BoxedStatusCodes[intStatusCode - 100].Item1 : statusCode; } public static string GetStatusCodeString(HttpStatusCode statusCode) { - int intStatusCode = (int)statusCode; - if (intStatusCode >= 100 && intStatusCode < 600) - { - return BoxedStatusCodes[intStatusCode - 100].Item2; - } - - return statusCode.ToString(); + var intStatusCode = (int)statusCode; + return intStatusCode is >= 100 and < 600 ? BoxedStatusCodes[intStatusCode - 100].Item2 : statusCode.ToString(); } private static (object, string)[] InitializeBoxedStatusCodes() diff --git a/src/OpenTelemetry.Instrumentation.Owin/Implementation/DiagnosticsMiddleware.cs b/src/OpenTelemetry.Instrumentation.Owin/Implementation/DiagnosticsMiddleware.cs index cf029720c0..56092245f4 100644 --- a/src/OpenTelemetry.Instrumentation.Owin/Implementation/DiagnosticsMiddleware.cs +++ b/src/OpenTelemetry.Instrumentation.Owin/Implementation/DiagnosticsMiddleware.cs @@ -77,7 +77,7 @@ private static void BeginRequest(IOwinContext owinContext) var textMapPropagator = Propagators.DefaultTextMapPropagator; var ctx = textMapPropagator.Extract(default, owinContext.Request, OwinRequestHeaderValuesGetter); - Activity? activity = OwinInstrumentationActivitySource.ActivitySource.StartActivity( + var activity = OwinInstrumentationActivitySource.ActivitySource.StartActivity( OwinInstrumentationActivitySource.IncomingRequestActivityName, ActivityKind.Server, ctx.ActivityContext); @@ -103,7 +103,7 @@ private static void BeginRequest(IOwinContext owinContext) activity.SetTag(SemanticConventions.AttributeUrlQuery, request.Query); activity.SetTag(SemanticConventions.AttributeUrlScheme, owinContext.Request.Scheme); - if (request.Headers.TryGetValue("User-Agent", out string[] userAgent) && userAgent.Length > 0) + if (request.Headers.TryGetValue("User-Agent", out var userAgent) && userAgent.Length > 0) { activity.SetTag(SemanticConventions.AttributeUserAgentOriginal, userAgent[0]); } @@ -124,7 +124,7 @@ private static void BeginRequest(IOwinContext owinContext) } } - if (!(textMapPropagator is TraceContextPropagator)) + if (textMapPropagator is not TraceContextPropagator) { Baggage.Current = ctx.Baggage; } @@ -136,7 +136,7 @@ private static void BeginRequest(IOwinContext owinContext) [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void RequestEnd(IOwinContext owinContext, Exception? exception, long startTimestamp) { - if (owinContext.Environment.TryGetValue(ContextKey, out object context) + if (owinContext.Environment.TryGetValue(ContextKey, out var context) && context is Activity activity) { if (Activity.Current != activity) @@ -191,7 +191,7 @@ private static void RequestEnd(IOwinContext owinContext, Exception? exception, l new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode)); } - if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator)) + if (Propagators.DefaultTextMapPropagator is not TraceContextPropagator) { Baggage.Current = default; } @@ -209,21 +209,4 @@ private static void RequestEnd(IOwinContext owinContext, Exception? exception, l new(SemanticConventions.AttributeHttpResponseStatusCode, owinContext.Response.StatusCode)); } } - - /// - /// Gets the OpenTelemetry standard uri tag value for a span based on its request . - /// - /// . - /// Span uri value. - private static string GetUriTagValueFromRequestUri(Uri uri, bool disableQueryRedaction) - { - if (string.IsNullOrEmpty(uri.UserInfo) && disableQueryRedaction) - { - return uri.OriginalString; - } - - var query = disableQueryRedaction ? uri.Query : RedactionHelper.GetRedactedQueryString(uri.Query); - - return string.Concat(uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath, query, uri.Fragment); - } } diff --git a/src/OpenTelemetry.Instrumentation.Process/ProcessMetrics.cs b/src/OpenTelemetry.Instrumentation.Process/ProcessMetrics.cs index effd7de5ea..b14ce70614 100644 --- a/src/OpenTelemetry.Instrumentation.Process/ProcessMetrics.cs +++ b/src/OpenTelemetry.Instrumentation.Process/ProcessMetrics.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics.Metrics; using System.Reflection; using OpenTelemetry.Internal; diff --git a/src/OpenTelemetry.Instrumentation.Quartz/Implementation/QuartzDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.Quartz/Implementation/QuartzDiagnosticListener.cs index bb6e68b523..9f390287d9 100644 --- a/src/OpenTelemetry.Instrumentation.Quartz/Implementation/QuartzDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.Quartz/Implementation/QuartzDiagnosticListener.cs @@ -28,7 +28,7 @@ public QuartzDiagnosticListener(string sourceName, QuartzInstrumentationOptions public override void OnEventWritten(string name, object? payload) { - Activity? activity = Activity.Current; + var activity = Activity.Current; Guard.ThrowIfNull(activity); switch (name) { @@ -44,6 +44,8 @@ public override void OnEventWritten(string name, object? payload) case "Quartz.Job.Veto.Exception": this.OnException(activity, payload); break; + default: + break; } } @@ -127,8 +129,7 @@ private void OnException(Activity activity, object? payload) { if (activity.IsAllDataRequested) { - var exc = payload as Exception; - if (exc == null) + if (payload is not Exception exc) { QuartzInstrumentationEventSource.Log.NullPayload(nameof(QuartzDiagnosticListener), nameof(this.OnStopActivity)); return; diff --git a/src/OpenTelemetry.Instrumentation.Runtime/RuntimeMetrics.cs b/src/OpenTelemetry.Instrumentation.Runtime/RuntimeMetrics.cs index b267c9c4a6..a67f264633 100644 --- a/src/OpenTelemetry.Instrumentation.Runtime/RuntimeMetrics.cs +++ b/src/OpenTelemetry.Instrumentation.Runtime/RuntimeMetrics.cs @@ -24,14 +24,16 @@ internal sealed class RuntimeMetrics #endif private const int NumberOfGenerations = 3; - private static readonly string[] GenNames = new string[] { "gen0", "gen1", "gen2", "loh", "poh" }; + private static readonly string[] GenNames = ["gen0", "gen1", "gen2", "loh", "poh"]; +#if NET private static bool isGcInfoAvailable; +#endif static RuntimeMetrics() { MeterInstance.CreateObservableCounter( "process.runtime.dotnet.gc.collections.count", - () => GetGarbageCollectionCounts(), + GetGarbageCollectionCounts, description: "Number of garbage collections that have occurred since process start."); MeterInstance.CreateObservableUpDownCounter( @@ -51,19 +53,14 @@ static RuntimeMetrics() "process.runtime.dotnet.gc.committed_memory.size", () => { - if (!IsGcInfoAvailable) - { - return Array.Empty>(); - } - - return new Measurement[] { new(GC.GetGCMemoryInfo().TotalCommittedBytes) }; + return !IsGcInfoAvailable ? Array.Empty>() : [new(GC.GetGCMemoryInfo().TotalCommittedBytes)]; }, unit: "bytes", description: "The amount of committed virtual memory for the managed GC heap, as observed during the latest garbage collection. Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future. The value will be unavailable until at least one garbage collection has occurred."); // GC.GetGCMemoryInfo().GenerationInfo[i].SizeAfterBytes is better but it has a bug in .NET 6. See context in https://github.com/open-telemetry/opentelemetry-dotnet-contrib/issues/496 Func? getGenerationSize = null; - bool isCodeRunningOnBuggyRuntimeVersion = Environment.Version.Major == 6; + var isCodeRunningOnBuggyRuntimeVersion = Environment.Version.Major == 6; if (isCodeRunningOnBuggyRuntimeVersion) { var mi = typeof(GC).GetMethod("GetGenerationSize", BindingFlags.NonPublic | BindingFlags.Static); @@ -82,22 +79,17 @@ static RuntimeMetrics() { if (!IsGcInfoAvailable) { - return Array.Empty>(); + return []; } var generationInfo = GC.GetGCMemoryInfo().GenerationInfo; - Measurement[] measurements = new Measurement[generationInfo.Length]; - int maxSupportedLength = Math.Min(generationInfo.Length, GenNames.Length); - for (int i = 0; i < maxSupportedLength; ++i) + var measurements = new Measurement[generationInfo.Length]; + var maxSupportedLength = Math.Min(generationInfo.Length, GenNames.Length); + for (var i = 0; i < maxSupportedLength; ++i) { - if (isCodeRunningOnBuggyRuntimeVersion) - { - measurements[i] = new((long)getGenerationSize!(i), new KeyValuePair("generation", GenNames[i])); - } - else - { - measurements[i] = new(generationInfo[i].SizeAfterBytes, new KeyValuePair("generation", GenNames[i])); - } + measurements[i] = isCodeRunningOnBuggyRuntimeVersion + ? new((long)getGenerationSize!(i), new KeyValuePair("generation", GenNames[i])) + : new(generationInfo[i].SizeAfterBytes, new KeyValuePair("generation", GenNames[i])); } return measurements; @@ -115,13 +107,13 @@ static RuntimeMetrics() { if (!IsGcInfoAvailable) { - return Array.Empty>(); + return []; } var generationInfo = GC.GetGCMemoryInfo().GenerationInfo; - Measurement[] measurements = new Measurement[generationInfo.Length]; - int maxSupportedLength = Math.Min(generationInfo.Length, GenNames.Length); - for (int i = 0; i < maxSupportedLength; ++i) + var measurements = new Measurement[generationInfo.Length]; + var maxSupportedLength = Math.Min(generationInfo.Length, GenNames.Length); + for (var i = 0; i < maxSupportedLength; ++i) { measurements[i] = new(generationInfo[i].FragmentationAfterBytes, new KeyValuePair("generation", GenNames[i])); } @@ -201,15 +193,17 @@ static RuntimeMetrics() exceptionCounter.Add(1); }; } - +#pragma warning disable SA1313 /// /// Initializes a new instance of the class. /// - /// The options to define the metrics. - public RuntimeMetrics(RuntimeInstrumentationOptions options) + /// The options to define the metrics. + public RuntimeMetrics(RuntimeInstrumentationOptions _1) +#pragma warning restore SA1313 { } +#if NET private static bool IsGcInfoAvailable { get @@ -227,12 +221,13 @@ private static bool IsGcInfoAvailable return isGcInfoAvailable; } } +#endif private static IEnumerable> GetGarbageCollectionCounts() { long collectionsFromHigherGeneration = 0; - for (int gen = NumberOfGenerations - 1; gen >= 0; --gen) + for (var gen = NumberOfGenerations - 1; gen >= 0; --gen) { long collectionsFromThisGeneration = GC.CollectionCount(gen); diff --git a/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlClientDiagnosticListener.cs b/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlClientDiagnosticListener.cs index 36c3ac89ba..027a6dc749 100644 --- a/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlClientDiagnosticListener.cs +++ b/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlClientDiagnosticListener.cs @@ -98,7 +98,7 @@ public override void OnEventWritten(string name, object? payload) _ = this.commandTextFetcher.TryFetch(command, out var commandText); - if (this.commandTypeFetcher.TryFetch(command, out CommandType commandType)) + if (this.commandTypeFetcher.TryFetch(command, out var commandType)) { switch (commandType) { @@ -135,6 +135,8 @@ public override void OnEventWritten(string name, object? payload) case CommandType.TableDirect: break; + default: + break; } } @@ -186,7 +188,7 @@ public override void OnEventWritten(string name, object? payload) { if (activity.IsAllDataRequested) { - if (this.exceptionFetcher.TryFetch(payload, out Exception? exception) && exception != null) + if (this.exceptionFetcher.TryFetch(payload, out var exception) && exception != null) { activity.AddTag(SemanticConventions.AttributeErrorType, exception.GetType().FullName); @@ -214,6 +216,8 @@ public override void OnEventWritten(string name, object? payload) } } + break; + default: break; } } diff --git a/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlConnectionDetails.cs b/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlConnectionDetails.cs index 2e5c595335..78110fd1cd 100644 --- a/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlConnectionDetails.cs +++ b/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlConnectionDetails.cs @@ -55,32 +55,32 @@ private SqlConnectionDetails() public static SqlConnectionDetails ParseFromDataSource(string dataSource) { - if (ConnectionDetailCache.TryGetValue(dataSource, out SqlConnectionDetails? connectionDetails)) + if (ConnectionDetailCache.TryGetValue(dataSource, out var connectionDetails)) { return connectionDetails; } var match = DataSourceRegex.Match(dataSource); - string? serverHostName = match.Groups[2].Value; + var serverHostName = match.Groups[2].Value; string? serverIpAddress = null; string? instanceName = null; int? port = null; var uriHostNameType = Uri.CheckHostName(serverHostName); - if (uriHostNameType == UriHostNameType.IPv4 || uriHostNameType == UriHostNameType.IPv6) + if (uriHostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6) { serverIpAddress = serverHostName; serverHostName = null; } - string maybeProtocol = match.Groups[1].Value; - bool isNamedPipe = maybeProtocol.Length > 0 && - maybeProtocol.StartsWith("np", StringComparison.OrdinalIgnoreCase); + var maybeProtocol = match.Groups[1].Value; + var isNamedPipe = maybeProtocol.Length > 0 && + maybeProtocol.StartsWith("np", StringComparison.OrdinalIgnoreCase); if (isNamedPipe) { - string pipeName = match.Groups[3].Value; + var pipeName = match.Groups[3].Value; if (pipeName.Length > 0) { var namedInstancePipeMatch = NamedPipeRegex.Match(pipeName); @@ -95,11 +95,11 @@ public static SqlConnectionDetails ParseFromDataSource(string dataSource) if (match.Groups[4].Length > 0) { instanceName = match.Groups[3].Value; - port = int.TryParse(match.Groups[4].Value, out int parsedPort) + port = int.TryParse(match.Groups[4].Value, out var parsedPort) ? parsedPort == 1433 ? null : parsedPort : null; } - else if (int.TryParse(match.Groups[3].Value, out int parsedPort)) + else if (int.TryParse(match.Groups[3].Value, out var parsedPort)) { instanceName = null; port = parsedPort == 1433 ? null : parsedPort; diff --git a/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlEventSourceListener.netfx.cs b/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlEventSourceListener.netfx.cs index 371cae85a3..45f1800db2 100644 --- a/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlEventSourceListener.netfx.cs +++ b/src/OpenTelemetry.Instrumentation.SqlClient/Implementation/SqlEventSourceListener.netfx.cs @@ -112,8 +112,8 @@ private void OnBeginExecute(EventWrittenEventArgs eventData) return; } - string dataSource = (string)eventData.Payload[1]; - string databaseName = (string)eventData.Payload[2]; + var dataSource = (string)eventData.Payload[1]; + var databaseName = (string)eventData.Payload[2]; var startTags = SqlActivitySourceHelper.GetTagListFromConnectionInfo(dataSource, databaseName, this.options, out var activityName); var activity = SqlActivitySourceHelper.ActivitySource.StartActivity( activityName, @@ -129,7 +129,7 @@ private void OnBeginExecute(EventWrittenEventArgs eventData) if (activity.IsAllDataRequested) { - string commandText = (string)eventData.Payload[3]; + var commandText = (string)eventData.Payload[3]; if (!string.IsNullOrEmpty(commandText) && this.options.SetDbStatementForText) { if (this.options.EmitOldAttributes) @@ -170,7 +170,7 @@ private void OnEndExecute(EventWrittenEventArgs eventData) { if (activity.IsAllDataRequested) { - int compositeState = (int)eventData.Payload[1]; + var compositeState = (int)eventData.Payload[1]; if ((compositeState & 0b001) != 0b001) { if ((compositeState & 0b010) == 0b010) diff --git a/src/OpenTelemetry.Instrumentation.SqlClient/SqlClientInstrumentation.cs b/src/OpenTelemetry.Instrumentation.SqlClient/SqlClientInstrumentation.cs index 301f5a7891..c1b3ea6988 100644 --- a/src/OpenTelemetry.Instrumentation.SqlClient/SqlClientInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.SqlClient/SqlClientInstrumentation.cs @@ -20,15 +20,15 @@ internal sealed class SqlClientInstrumentation : IDisposable #if NETFRAMEWORK private readonly SqlEventSourceListener sqlEventSourceListener; #else - private static readonly HashSet DiagnosticSourceEvents = new() - { + private static readonly HashSet DiagnosticSourceEvents = + [ "System.Data.SqlClient.WriteCommandBefore", "Microsoft.Data.SqlClient.WriteCommandBefore", "System.Data.SqlClient.WriteCommandAfter", "Microsoft.Data.SqlClient.WriteCommandAfter", "System.Data.SqlClient.WriteCommandError", - "Microsoft.Data.SqlClient.WriteCommandError", - }; + "Microsoft.Data.SqlClient.WriteCommandError" + ]; private readonly Func isEnabled = (eventName, _, _) => DiagnosticSourceEvents.Contains(eventName); diff --git a/src/Shared/ActivityHelperExtensions.cs b/src/Shared/ActivityHelperExtensions.cs index 7425c97edc..2e5430ead6 100644 --- a/src/Shared/ActivityHelperExtensions.cs +++ b/src/Shared/ActivityHelperExtensions.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/Shared/ActivityInstrumentationHelper.cs b/src/Shared/ActivityInstrumentationHelper.cs index 02a0d83e16..0f7ec41d1a 100644 --- a/src/Shared/ActivityInstrumentationHelper.cs +++ b/src/Shared/ActivityInstrumentationHelper.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; namespace OpenTelemetry.Instrumentation; diff --git a/src/Shared/AssemblyVersionExtensions.cs b/src/Shared/AssemblyVersionExtensions.cs index 4c71ae3598..953de906cc 100644 --- a/src/Shared/AssemblyVersionExtensions.cs +++ b/src/Shared/AssemblyVersionExtensions.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using System.Reflection; diff --git a/src/Shared/Configuration/IConfigurationExtensionsLogger.cs b/src/Shared/Configuration/IConfigurationExtensionsLogger.cs index 0835cf6ff8..196a485bf3 100644 --- a/src/Shared/Configuration/IConfigurationExtensionsLogger.cs +++ b/src/Shared/Configuration/IConfigurationExtensionsLogger.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - namespace Microsoft.Extensions.Configuration; internal interface IConfigurationExtensionsLogger diff --git a/src/Shared/Configuration/OpenTelemetryConfigurationExtensions.cs b/src/Shared/Configuration/OpenTelemetryConfigurationExtensions.cs index e663c53a67..3637927de2 100644 --- a/src/Shared/Configuration/OpenTelemetryConfigurationExtensions.cs +++ b/src/Shared/Configuration/OpenTelemetryConfigurationExtensions.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; #if NET || NETSTANDARD2_1 using System.Diagnostics.CodeAnalysis; diff --git a/src/Shared/DatabaseSemanticConventionHelper.cs b/src/Shared/DatabaseSemanticConventionHelper.cs index a3bc4b5e98..1225e43069 100644 --- a/src/Shared/DatabaseSemanticConventionHelper.cs +++ b/src/Shared/DatabaseSemanticConventionHelper.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Configuration; diff --git a/src/Shared/DiagnosticSourceListener.cs b/src/Shared/DiagnosticSourceListener.cs index 3ffad9bf33..9b0b07b3c8 100644 --- a/src/Shared/DiagnosticSourceListener.cs +++ b/src/Shared/DiagnosticSourceListener.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using OpenTelemetry.Internal; diff --git a/src/Shared/DiagnosticSourceSubscriber.cs b/src/Shared/DiagnosticSourceSubscriber.cs index 3318216db0..87863b2193 100644 --- a/src/Shared/DiagnosticSourceSubscriber.cs +++ b/src/Shared/DiagnosticSourceSubscriber.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using OpenTelemetry.Internal; diff --git a/src/Shared/ExceptionExtensions.cs b/src/Shared/ExceptionExtensions.cs index 9070b59c20..5071a8feeb 100644 --- a/src/Shared/ExceptionExtensions.cs +++ b/src/Shared/ExceptionExtensions.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Globalization; namespace OpenTelemetry.Internal; diff --git a/src/Shared/GrpcStatusCanonicalCode.cs b/src/Shared/GrpcStatusCanonicalCode.cs index d4ec2cf7fb..8abad05f25 100644 --- a/src/Shared/GrpcStatusCanonicalCode.cs +++ b/src/Shared/GrpcStatusCanonicalCode.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - namespace OpenTelemetry.Instrumentation; /// diff --git a/src/Shared/GrpcTagHelper.cs b/src/Shared/GrpcTagHelper.cs index d7c22b1c63..7911cc5c7d 100644 --- a/src/Shared/GrpcTagHelper.cs +++ b/src/Shared/GrpcTagHelper.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using System.Text.RegularExpressions; using OpenTelemetry.Trace; diff --git a/src/Shared/Guard.cs b/src/Shared/Guard.cs index a00cfafb09..d8b88d6a07 100644 --- a/src/Shared/Guard.cs +++ b/src/Shared/Guard.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - // Note: For some targets this file will contain more than one type/namespace. #pragma warning disable IDE0161 // Convert to file-scoped namespace diff --git a/src/Shared/ListenerHandler.cs b/src/Shared/ListenerHandler.cs index a7c6f9049d..d711aab6b0 100644 --- a/src/Shared/ListenerHandler.cs +++ b/src/Shared/ListenerHandler.cs @@ -3,8 +3,6 @@ using System.Diagnostics; -#nullable enable - namespace OpenTelemetry.Instrumentation; /// diff --git a/src/Shared/MultiTypePropertyFetcher.cs b/src/Shared/MultiTypePropertyFetcher.cs index 1370094a58..b5f82fd86d 100644 --- a/src/Shared/MultiTypePropertyFetcher.cs +++ b/src/Shared/MultiTypePropertyFetcher.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Collections.Concurrent; using System.Reflection; diff --git a/src/Shared/Options/DelegatingOptionsFactoryServiceCollectionExtensions.cs b/src/Shared/Options/DelegatingOptionsFactoryServiceCollectionExtensions.cs index b3b9736277..81e9ac0a66 100644 --- a/src/Shared/Options/DelegatingOptionsFactoryServiceCollectionExtensions.cs +++ b/src/Shared/Options/DelegatingOptionsFactoryServiceCollectionExtensions.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; #if NET using System.Diagnostics.CodeAnalysis; diff --git a/src/Shared/Options/SingletonOptionsManager.cs b/src/Shared/Options/SingletonOptionsManager.cs index 4c7718e78c..d3b1928d55 100644 --- a/src/Shared/Options/SingletonOptionsManager.cs +++ b/src/Shared/Options/SingletonOptionsManager.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - #if NET using System.Diagnostics.CodeAnalysis; #endif diff --git a/src/Shared/PropertyFetcher.AOT.cs b/src/Shared/PropertyFetcher.AOT.cs index 209f91cada..19b3153814 100644 --- a/src/Shared/PropertyFetcher.AOT.cs +++ b/src/Shared/PropertyFetcher.AOT.cs @@ -5,8 +5,6 @@ // Usages of the non-AOT-compatible version can be moved over to this one when they need to support AOT/trimming. // Copied from https://github.com/open-telemetry/opentelemetry-dotnet/blob/86a6ba0b7f7ed1f5e84e5a6610e640989cd3ae9f/src/Shared/DiagnosticSourceInstrumentation/PropertyFetcher.cs#L30 -#nullable enable - #if NETSTANDARD2_1_0_OR_GREATER || NET using System.Diagnostics.CodeAnalysis; #endif diff --git a/src/Shared/RedactionHelper.cs b/src/Shared/RedactionHelper.cs index 045d99cad2..ed34bb3e4f 100644 --- a/src/Shared/RedactionHelper.cs +++ b/src/Shared/RedactionHelper.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Text; namespace OpenTelemetry.Internal; diff --git a/src/Shared/RequestDataHelper.cs b/src/Shared/RequestDataHelper.cs index 6acce7fe40..edd9532569 100644 --- a/src/Shared/RequestDataHelper.cs +++ b/src/Shared/RequestDataHelper.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - #if NET using System.Collections.Frozen; #endif diff --git a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs index 479026a277..af493c8574 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TLDTraceExporterBenchmarks.cs @@ -55,7 +55,7 @@ public TLDTraceExporterBenchmarks() this.activity = testActivity!; this.activity.SetTag("tagString", "value"); this.activity.SetTag("tagInt", 100); - this.activity.SetStatus(Status.Error); + this.activity.SetStatus(ActivityStatusCode.Error); } this.msgPackExporter = new MsgPackTraceExporter(new GenevaExporterOptions @@ -128,7 +128,7 @@ private Batch CreateBatch() { activity.SetTag("tagString", "value"); activity.SetTag("tagInt", 100); - activity.SetStatus(Status.Error); + activity.SetStatus(ActivityStatusCode.Error); } return batchGeneratorExporter.Batch; diff --git a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs index cfec940e3f..2a4d7e01f5 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Benchmarks/Exporter/TraceExporterBenchmarks.cs @@ -54,7 +54,7 @@ public TraceExporterBenchmarks() this.activity = testActivity!; this.activity.SetTag("tagString", "value"); this.activity.SetTag("tagInt", 100); - this.activity.SetStatus(Status.Error); + this.activity.SetStatus(ActivityStatusCode.Error); } activityListener.Dispose(); @@ -129,7 +129,7 @@ private Batch CreateBatch() { activity.SetTag("tagString", "value"); activity.SetTag("tagInt", 100); - activity.SetStatus(Status.Error); + activity.SetStatus(ActivityStatusCode.Error); } return batchGeneratorExporter.Batch; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs index e5065cc143..eaa566ed9d 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaLogExporterTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Diagnostics; using System.Globalization; using System.Net.Sockets; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterOptionsTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterOptionsTests.cs index e711d89757..5ccc866188 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterOptionsTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterOptionsTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using Xunit; namespace OpenTelemetry.Exporter.Geneva.Tests; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs index 62d1176481..d7f189a0e6 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaMetricExporterTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Diagnostics; using System.Diagnostics.Metrics; using System.Globalization; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs index c4d8d21205..06e6ee74d0 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/GenevaTraceExporterTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Diagnostics; using System.Net.Sockets; using System.Reflection; @@ -173,12 +175,12 @@ public void GenevaTraceExporter_Success_Windows() using (var activity = source.StartActivity("Bar")) { - activity.SetStatus(Status.Error); + activity.SetStatus(ActivityStatusCode.Error); } using (var activity = source.StartActivity("Baz")) { - activity.SetStatus(Status.Ok); + activity.SetStatus(ActivityStatusCode.Ok); } } @@ -296,21 +298,25 @@ public void GenevaTraceExporter_Serialization_Success(bool hasTableNameMapping, activity?.SetTag("clientRequestId", "58a37988-2c05-427a-891f-5e0e1266fcc5"); activity?.SetTag("foo", 1); activity?.SetTag("bar", 2); +#pragma warning disable CS0618 // Type or member is obsolete activity?.SetStatus(Status.Error.WithDescription("Error description from OTel API")); +#pragma warning restore CS0618 // Type or member is obsolete } } using (var activity = source.StartActivity("TestActivityForSetStatusAPI")) { - activity?.SetStatus(ActivityStatusCode.Error, "Error description from .NET API"); + activity?.SetStatus(ActivityStatusCode.Error, description: "Error description from .NET API"); } // If the activity Status is set using both the OTel API and the .NET API, the `Status` and `StatusDescription` set by // the .NET API is chosen using (var activity = source.StartActivity("PreferStatusFromDotnetAPI")) { +#pragma warning disable CS0618 // Type or member is obsolete activity?.SetStatus(Status.Error.WithDescription("Error description from OTel API")); - activity?.SetStatus(ActivityStatusCode.Error, "Error description from .NET API"); +#pragma warning restore CS0618 // Type or member is obsolete + activity?.SetStatus(ActivityStatusCode.Error, description: "Error description from .NET API"); customChecksForActivity = mapping => { Assert.Equal("Error description from .NET API", mapping["statusMessage"]); @@ -678,17 +684,19 @@ private void AssertFluentdForwardModeForActivity(GenevaExporterOptions exporterO Assert.Equal((byte)activity.Kind, mapping["kind"]); Assert.Equal(activity.StartTimeUtc, mapping["startTime"]); - var activityStatusCode = activity.GetStatus().StatusCode; +#pragma warning disable CS0618 // Type or member is obsolete + var otelApiStatusCode = activity.GetStatus(); +#pragma warning restore CS0618 // Type or member is obsolete if (activity.Status == ActivityStatusCode.Error) { Assert.False((bool)mapping["success"]); Assert.Equal(activity.StatusDescription, mapping["statusMessage"]); } - else if (activityStatusCode == StatusCode.Error) + else if (otelApiStatusCode.StatusCode == StatusCode.Error) { Assert.False((bool)mapping["success"]); - var activityStatusDesc = activity.GetStatus().Description; + var activityStatusDesc = otelApiStatusCode.Description; Assert.Equal(activityStatusDesc, mapping["statusMessage"]); } else diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/JsonSerializerTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/JsonSerializerTests.cs index c49a58b40c..783e3524cf 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/JsonSerializerTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/JsonSerializerTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Text; using OpenTelemetry.Exporter.Geneva.Tld; using Xunit; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/LogSerializationTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/LogSerializationTests.cs index dd311dcff1..d71cbb2cb7 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/LogSerializationTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/LogSerializationTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Net.Sockets; using System.Runtime.InteropServices; using Microsoft.Extensions.Logging; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/MessagePackSerializerTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/MessagePackSerializerTests.cs index 997a6afd87..640f78f0c0 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/MessagePackSerializerTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/MessagePackSerializerTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Globalization; using System.Text; using OpenTelemetry.Exporter.Geneva.MsgPack; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/OpenTelemetry.Exporter.Geneva.Tests.csproj b/test/OpenTelemetry.Exporter.Geneva.Tests/OpenTelemetry.Exporter.Geneva.Tests.csproj index 4cc8b83b36..31ae1a4442 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/OpenTelemetry.Exporter.Geneva.Tests.csproj +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/OpenTelemetry.Exporter.Geneva.Tests.csproj @@ -8,7 +8,6 @@ $(TargetFrameworks);net48;net472;net471;net47;net462 Unit test project for Geneva Exporters for OpenTelemetry. $(NoWarn);SA1311;SA1312;SA1313;SA1123;SA1202;OTEL1002 - disable diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/OtlpProtobufMetricExporterTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/OtlpProtobufMetricExporterTests.cs index 4870b6aee1..5ac0832ba0 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/OtlpProtobufMetricExporterTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/OtlpProtobufMetricExporterTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Diagnostics; using System.Diagnostics.Metrics; using Google.Protobuf; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/TableNameSerializerTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/TableNameSerializerTests.cs index b4b01ab8f4..636676c55c 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/TableNameSerializerTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/TableNameSerializerTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Text; using Xunit; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketDataTransportTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketDataTransportTests.cs index 753de5c7e0..0fb9e2302c 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketDataTransportTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketDataTransportTests.cs @@ -1,6 +1,8 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#nullable disable + using System.Net.Sockets; using System.Reflection; using OpenTelemetry.Exporter.Geneva.Transports; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketEndPointTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketEndPointTests.cs index d0d922ca2b..85351d141c 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketEndPointTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/UnixDomainSocketEndPointTests.cs @@ -3,6 +3,8 @@ #if !NET +#nullable disable + using System.Net; using System.Net.Sockets; using System.Text; diff --git a/test/OpenTelemetry.Exporter.Geneva.Tests/UnixUserEventsDataTransportTests.cs b/test/OpenTelemetry.Exporter.Geneva.Tests/UnixUserEventsDataTransportTests.cs index 6cc7956eb9..4af7484581 100644 --- a/test/OpenTelemetry.Exporter.Geneva.Tests/UnixUserEventsDataTransportTests.cs +++ b/test/OpenTelemetry.Exporter.Geneva.Tests/UnixUserEventsDataTransportTests.cs @@ -3,8 +3,6 @@ #if NET6_0_OR_GREATER -#nullable enable - using System.Diagnostics; using System.Globalization; using System.Text.RegularExpressions; diff --git a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs index 35452ace15..7b46ec5013 100644 --- a/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs +++ b/test/OpenTelemetry.Exporter.Instana.Tests/Processors/EventsActivityProcessorTests.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using OpenTelemetry.Exporter.Instana.Implementation; using OpenTelemetry.Exporter.Instana.Implementation.Processors; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs index e14243fbbe..f02b4203fe 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestCases.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Reflection; using System.Text.Json; using System.Text.Json.Serialization; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestFixture.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestFixture.cs index fdb42af421..a49503722b 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestFixture.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestFixture.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Globalization; using System.Text; using Microsoft.AspNetCore.Builder; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestResult.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestResult.cs index f1df77ba10..affa074c20 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestResult.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTestResult.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Text.Json; using System.Text.Json.Serialization; using RouteTests.TestApplication; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs index c6cbc6fba4..93199709ea 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/RoutingTests.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using OpenTelemetry; using OpenTelemetry.Metrics; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs index 98c15a18ba..e0df2673e8 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ActionDescriptorInfo.cs @@ -1,7 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable using System.Text.Json.Serialization; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Controllers; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ControllerActionDescriptorInfo.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ControllerActionDescriptorInfo.cs index ae5ef6b907..34260c4889 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ControllerActionDescriptorInfo.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/ControllerActionDescriptorInfo.cs @@ -1,7 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable using System.Text.Json.Serialization; namespace RouteTests.TestApplication; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/PageActionDescriptorInfo.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/PageActionDescriptorInfo.cs index dda48ae462..bdaf96851a 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/PageActionDescriptorInfo.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/PageActionDescriptorInfo.cs @@ -1,7 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable using System.Text.Json.Serialization; namespace RouteTests.TestApplication; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs index 0d8d2e9668..2754617e78 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfo.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Text.Json.Serialization; using Microsoft.AspNetCore.Http; #if NET diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs index e5e4025ec4..a144f56b58 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/RouteInfoDiagnosticObserver.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Diagnostics; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs index cc9d682db6..c50fe412f2 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestApplication/TestApplicationFactory.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; diff --git a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestCase.cs b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestCase.cs index 36710fe4a9..f4e07d2388 100644 --- a/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestCase.cs +++ b/test/OpenTelemetry.Instrumentation.AspNetCore.Tests/RouteTests/TestCase.cs @@ -1,7 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable using RouteTests.TestApplication; namespace RouteTests; diff --git a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/Customer.cs b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/Customer.cs index 2ace4b977c..a0d5bbe566 100644 --- a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/Customer.cs +++ b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/Customer.cs @@ -3,7 +3,7 @@ namespace OpenTelemetry.Instrumentation.ElasticsearchClient.Tests; -public class Customer +internal class Customer { public string? Id { get; set; } diff --git a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/DependencyInjectionConfigTests.cs b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/DependencyInjectionConfigTests.cs index fc2abb01ae..b8a3d14c34 100644 --- a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/DependencyInjectionConfigTests.cs +++ b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/DependencyInjectionConfigTests.cs @@ -15,7 +15,7 @@ public class DependencyInjectionConfigTests [InlineData("CustomName")] public async Task TestTracingOptionsDiConfig(string? name) { - bool optionsPickedFromDi = false; + var optionsPickedFromDi = false; var services = new ServiceCollection(); diff --git a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/ElasticsearchClientTests.cs b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/ElasticsearchClientTests.cs index 2d8cf5a40b..5e23f346c5 100644 --- a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/ElasticsearchClientTests.cs +++ b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/ElasticsearchClientTests.cs @@ -181,7 +181,7 @@ public async Task CanCaptureSearchCall() [Fact] public async Task CanRecordAndSampleSearchCall() { - bool samplerCalled = false; + var samplerCalled = false; var sampler = new TestSampler { @@ -193,10 +193,10 @@ public async Task CanRecordAndSampleSearchCall() }, }; - using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); + using var testActivityProcessor = new TestActivityProcessor(); - int startCalled = 0; - int endCalled = 0; + var startCalled = 0; + var endCalled = 0; testActivityProcessor.StartAction = (a) => @@ -239,9 +239,9 @@ public async Task CanRecordAndSampleSearchCall() } [Fact] - public async Task CanSupressDownstreamActivities() + public async Task CanSuppressDownstreamActivities() { - bool samplerCalled = false; + var samplerCalled = false; var sampler = new TestSampler { @@ -253,10 +253,10 @@ public async Task CanSupressDownstreamActivities() }, }; - using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); + using var testActivityProcessor = new TestActivityProcessor(); - int startCalled = 0; - int endCalled = 0; + var startCalled = 0; + var endCalled = 0; testActivityProcessor.StartAction = (a) => @@ -301,7 +301,7 @@ public async Task CanSupressDownstreamActivities() [Fact] public async Task CanDropSearchCall() { - bool samplerCalled = false; + var samplerCalled = false; var sampler = new TestSampler { @@ -313,10 +313,10 @@ public async Task CanDropSearchCall() }, }; - using TestActivityProcessor testActivityProcessor = new TestActivityProcessor(); + using var testActivityProcessor = new TestActivityProcessor(); - int startCalled = 0; - int endCalled = 0; + var startCalled = 0; + var endCalled = 0; testActivityProcessor.StartAction = (a) => @@ -725,8 +725,8 @@ public async Task DoesNotCaptureWhenInstrumentationIsSuppressed() public async Task CapturesBasedOnSamplingDecision(SamplingDecision samplingDecision, bool isActivityExpected) { var expectedResource = ResourceBuilder.CreateDefault().AddService("test-service"); - bool startActivityCalled = false; - bool endActivityCalled = false; + var startActivityCalled = false; + var endActivityCalled = false; var processor = new TestActivityProcessor( activity => startActivityCalled = true, activity => endActivityCalled = true); @@ -851,7 +851,7 @@ public async Task ShouldRemoveSensitiveInformation() Assert.Single(exportedItems); var searchActivity = exportedItems[0]; - string? dbUrl = (string?)searchActivity.GetTagValue(SemanticConventions.AttributeUrlFull); + var dbUrl = (string?)searchActivity.GetTagValue(SemanticConventions.AttributeUrlFull); Assert.DoesNotContain("sensitive", dbUrl); Assert.Contains("REDACTED:REDACTED", dbUrl); diff --git a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/InMemoryConnectionWithDownstreamActivity.cs b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/InMemoryConnectionWithDownstreamActivity.cs index ba9dfa1278..8fdb784976 100644 --- a/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/InMemoryConnectionWithDownstreamActivity.cs +++ b/test/OpenTelemetry.Instrumentation.ElasticsearchClient.Tests/InMemoryConnectionWithDownstreamActivity.cs @@ -6,10 +6,10 @@ namespace OpenTelemetry.Instrumentation.ElasticsearchClient.Tests; -public class InMemoryConnectionWithDownstreamActivity : InMemoryConnection +internal class InMemoryConnectionWithDownstreamActivity : InMemoryConnection { - internal static readonly ActivitySource ActivitySource = new ActivitySource("Downstream"); - internal static readonly ActivitySource NestedActivitySource = new ActivitySource("NestedDownstream"); + internal static readonly ActivitySource ActivitySource = new("Downstream"); + internal static readonly ActivitySource NestedActivitySource = new("NestedDownstream"); public override Task RequestAsync(RequestData requestData, CancellationToken cancellationToken) { diff --git a/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs b/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs index 0b82bc5445..ccd2150a5c 100644 --- a/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs +++ b/test/OpenTelemetry.Instrumentation.EventCounters.Tests/EventCountersMetricsTests.cs @@ -13,7 +13,7 @@ public class EventCountersMetricsTests public void EventCounter() { // Arrange - List metricItems = new(); + List metricItems = []; using EventSource source = new("a"); using EventCounter counter = new("c", source); @@ -39,7 +39,7 @@ public void EventCounter() public void IncrementingEventCounter() { // Arrange - List metricItems = new(); + List metricItems = []; using EventSource source = new("b"); using IncrementingEventCounter incCounter = new("inc-c", source); @@ -67,8 +67,8 @@ public void IncrementingEventCounter() public void PollingCounter() { // Arrange - int i = 0; - List metricItems = new(); + var i = 0; + List metricItems = []; using EventSource source = new("c"); using PollingCounter pollCounter = new("poll-c", source, () => ++i * 10); @@ -93,8 +93,8 @@ public void PollingCounter() public void IncrementingPollingCounter() { // Arrange - int i = 1; - List metricItems = new(); + var i = 1; + List metricItems = []; using EventSource source = new("d"); using IncrementingPollingCounter incPollCounter = new("inc-poll-c", source, () => i++); @@ -142,7 +142,7 @@ public void ThrowExceptionForUnsupportedEventSources() public void EventSourceNameShortening(string sourceName, string eventName, string expectedInstrumentName) { // Arrange - List metricItems = new(); + List metricItems = []; using EventSource source = new(sourceName); using IncrementingEventCounter connections = new(eventName, source); @@ -167,11 +167,11 @@ public void EventSourceNameShortening(string sourceName, string eventName, strin public async Task InstrumentNameTooLong() { // Arrange - List metricItems = new(); + List metricItems = []; using EventSource source = new("source"); // ec.s. + event name is 63; - string veryLongEventName = new string('e', 100); + var veryLongEventName = new string('e', 100); using IncrementingEventCounter connections = new(veryLongEventName, source); using var meterProvider = Sdk.CreateMeterProviderBuilder() diff --git a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireFixture.cs b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireFixture.cs index 614882d572..7157660583 100644 --- a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireFixture.cs +++ b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireFixture.cs @@ -7,7 +7,9 @@ namespace OpenTelemetry.Instrumentation.Hangfire.Tests; +#pragma warning disable CA1515 public class HangfireFixture : IDisposable +#pragma warning restore CA1515 { public HangfireFixture() { diff --git a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs index 2b301d0f34..37fb369af7 100644 --- a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs +++ b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/HangfireInstrumentationJobFilterAttributeTests.cs @@ -34,8 +34,8 @@ public async Task Should_Create_Activity() await this.WaitJobProcessedAsync(jobId, 5); // Assert - Assert.Single(exportedItems, i => i.GetTagItem("job.id") as string == jobId); - var activity = exportedItems.Single(i => i.GetTagItem("job.id") as string == jobId); + Assert.Single(exportedItems, i => (i.GetTagItem("job.id") as string) == jobId); + var activity = exportedItems.Single(i => (i.GetTagItem("job.id") as string) == jobId); Assert.Contains("JOB TestJob.Execute", activity.DisplayName); Assert.Equal(ActivityKind.Internal, activity.Kind); } @@ -55,8 +55,8 @@ public async Task Should_Create_Activity_With_Status_Error_When_Job_Failed() await this.WaitJobProcessedAsync(jobId, 5); // Assert - Assert.Single(exportedItems, i => i.GetTagItem("job.id") as string == jobId); - var activity = exportedItems.Single(i => i.GetTagItem("job.id") as string == jobId); + Assert.Single(exportedItems, i => (i.GetTagItem("job.id") as string) == jobId); + var activity = exportedItems.Single(i => (i.GetTagItem("job.id") as string) == jobId); Assert.Contains("JOB TestJob.ThrowException", activity.DisplayName); Assert.Equal(ActivityKind.Internal, activity.Kind); Assert.Equal(ActivityStatusCode.Error, activity.Status); @@ -79,8 +79,8 @@ public async Task Should_Create_Activity_With_Exception_Event_When_Job_Failed_An await this.WaitJobProcessedAsync(jobId, 5); // Assert - Assert.Single(exportedItems, i => i.GetTagItem("job.id") as string == jobId); - var activity = exportedItems.Single(i => i.GetTagItem("job.id") as string == jobId); + Assert.Single(exportedItems, i => (i.GetTagItem("job.id") as string) == jobId); + var activity = exportedItems.Single(i => (i.GetTagItem("job.id") as string) == jobId); Assert.Contains("JOB TestJob.ThrowException", activity.DisplayName); Assert.Equal(ActivityKind.Internal, activity.Kind); Assert.Equal(ActivityStatusCode.Error, activity.Status); @@ -103,8 +103,8 @@ public async Task Should_Create_Activity_Without_Exception_Event_When_Job_Failed await this.WaitJobProcessedAsync(jobId, 5); // Assert - Assert.Single(exportedItems, i => i.GetTagItem("job.id") as string == jobId); - var activity = exportedItems.Single(i => i.GetTagItem("job.id") as string == jobId); + Assert.Single(exportedItems, i => (i.GetTagItem("job.id") as string) == jobId); + var activity = exportedItems.Single(i => (i.GetTagItem("job.id") as string) == jobId); Assert.Contains("JOB TestJob.ThrowException", activity.DisplayName); Assert.Equal(ActivityKind.Internal, activity.Kind); Assert.Equal(ActivityStatusCode.Error, activity.Status); @@ -128,8 +128,8 @@ public async Task Should_Create_Activity_With_Custom_DisplayName() await this.WaitJobProcessedAsync(jobId, 5); // Assert - Assert.Single(exportedItems, i => i.GetTagItem("job.id") as string == jobId); - var activity = exportedItems.Single(i => i.GetTagItem("job.id") as string == jobId); + Assert.Single(exportedItems, i => (i.GetTagItem("job.id") as string) == jobId); + var activity = exportedItems.Single(i => (i.GetTagItem("job.id") as string) == jobId); Assert.Contains($"JOB {jobId}", activity.DisplayName); Assert.Equal(ActivityKind.Internal, activity.Kind); } @@ -174,7 +174,7 @@ public async Task Should_Respect_Filter_Option(string filter, bool shouldRecord) private async Task WaitJobProcessedAsync(string jobId, int timeToWaitInSeconds) { var timeout = DateTime.Now.AddSeconds(timeToWaitInSeconds); - string[] states = new[] { "Enqueued", "Processing" }; + string[] states = ["Enqueued", "Processing"]; JobDetailsDto jobDetails; while (((jobDetails = this.hangfireFixture.MonitoringApi.JobDetails(jobId)) == null || jobDetails.History.All(h => states.Contains(h.StateName))) && DateTime.Now < timeout) diff --git a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/ProcessorMock.cs b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/ProcessorMock.cs index 81620efad1..e7652b7ff4 100644 --- a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/ProcessorMock.cs +++ b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/ProcessorMock.cs @@ -3,7 +3,7 @@ namespace OpenTelemetry.Instrumentation.Hangfire.Tests; -public class ProcessorMock : BaseProcessor +internal class ProcessorMock : BaseProcessor { private readonly Action? onStart; private readonly Action? onEnd; diff --git a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/TestJob.cs b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/TestJob.cs index ae2d973450..795e4e73df 100644 --- a/test/OpenTelemetry.Instrumentation.Hangfire.Tests/TestJob.cs +++ b/test/OpenTelemetry.Instrumentation.Hangfire.Tests/TestJob.cs @@ -3,7 +3,7 @@ namespace OpenTelemetry.Instrumentation.Hangfire.Tests; -public class TestJob +internal class TestJob { public void Execute() { diff --git a/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs b/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs index 5664716337..1905acb938 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Benchmarks/Instrumentation/HttpClientInstrumentationBenchmarks.cs @@ -26,7 +26,9 @@ namespace OpenTelemetry.Instrumentation.Http.Benchmarks.Instrumentation; +#pragma warning disable CA1515 public class HttpClientInstrumentationBenchmarks +#pragma warning restore CA1515 { private static readonly Uri Url = new("http://localhost:5000"); @@ -36,7 +38,9 @@ public class HttpClientInstrumentationBenchmarks 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.Http.Tests/HttpClientTests.Basic.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs index 05bc602e81..0ee5a4b4c7 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.Basic.cs @@ -38,11 +38,7 @@ public HttpClientTests(ITestOutputHelper output) var custom_traceparent = ctx.Request.Headers["custom_traceparent"]; var contextRequired = ctx.Request.Headers["contextRequired"]; var responseCode = ctx.Request.Headers["responseCode"]; - if ((contextRequired == null - || bool.Parse(contextRequired)) - && - (string.IsNullOrWhiteSpace(traceparent) - && string.IsNullOrWhiteSpace(custom_traceparent))) + if ((contextRequired == null || bool.Parse(contextRequired)) && string.IsNullOrWhiteSpace(traceparent) && string.IsNullOrWhiteSpace(custom_traceparent)) { ctx.Response.StatusCode = 500; ctx.Response.StatusDescription = "Missing trace context"; @@ -189,8 +185,8 @@ public async Task InjectsHeadersAsync(bool shouldEnrich) #if NETFRAMEWORK if (shouldEnrich) { - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpWebRequest").FirstOrDefault().Value); - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpWebResponse").FirstOrDefault().Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpWebRequest").Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpWebResponse").Value); } else { @@ -206,8 +202,8 @@ public async Task InjectsHeadersAsync(bool shouldEnrich) if (shouldEnrich) { - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpRequestMessage").FirstOrDefault().Value); - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enrichedWithHttpResponseMessage").FirstOrDefault().Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpRequestMessage").Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enrichedWithHttpResponseMessage").Value); } else { diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs index 83e594179b..fd01551bf3 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpClientTests.cs @@ -151,13 +151,7 @@ public async Task ValidateNet8MetricsAsync(HttpOutTestCase tc) } var requestMetrics = metrics - .Where(metric => - metric.Name == "http.client.request.duration" || - metric.Name == "http.client.active_requests" || - metric.Name == "http.client.request.time_in_queue" || - metric.Name == "http.client.connection.duration" || - metric.Name == "http.client.open_connections" || - metric.Name == "dns.lookup.duration") + .Where(metric => metric.Name is "http.client.request.duration" or "http.client.active_requests" or "http.client.request.time_in_queue" or "http.client.connection.duration" or "http.client.open_connections" or "dns.lookup.duration") .ToArray(); if (tc.ResponseExpected) @@ -221,11 +215,11 @@ private static async Task HttpOutCallsAreCollectedSuccessfullyBodyAsync( bool enableTracing, bool enableMetrics) { - bool enrichWithHttpWebRequestCalled = false; - bool enrichWithHttpWebResponseCalled = false; - bool enrichWithHttpRequestMessageCalled = false; - bool enrichWithHttpResponseMessageCalled = false; - bool enrichWithExceptionCalled = false; + var enrichWithHttpWebRequestCalled = false; + var enrichWithHttpWebResponseCalled = false; + var enrichWithHttpRequestMessageCalled = false; + var enrichWithHttpResponseMessageCalled = false; + var enrichWithExceptionCalled = false; var testUrl = HttpTestData.NormalizeValues(tc.Url, host, port); @@ -337,7 +331,7 @@ private static async Task HttpOutCallsAreCollectedSuccessfullyBodyAsync( var normalizedAttributes = activity.TagObjects.Where(kv => !kv.Key.StartsWith("otel.", StringComparison.Ordinal)).ToDictionary(x => x.Key, x => x.Value?.ToString()); - int numberOfTags = activity.Status == ActivityStatusCode.Error ? 5 : 4; + var numberOfTags = activity.Status == ActivityStatusCode.Error ? 5 : 4; var expectedAttributeCount = numberOfTags + (tc.ResponseExpected ? 2 : 0); @@ -495,11 +489,11 @@ private static async Task HttpOutCallsAreCollectedSuccessfullyBodyAsync( private static async Task CheckEnrichment(Sampler sampler, bool enrichExpected, string url) { - bool enrichWithHttpWebRequestCalled = false; - bool enrichWithHttpWebResponseCalled = false; + var enrichWithHttpWebRequestCalled = false; + var enrichWithHttpWebResponseCalled = false; - bool enrichWithHttpRequestMessageCalled = false; - bool enrichWithHttpResponseMessageCalled = false; + var enrichWithHttpRequestMessageCalled = false; + var enrichWithHttpResponseMessageCalled = false; using (Sdk.CreateTracerProviderBuilder() .SetSampler(sampler) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs index dd632eb9e5..43cdefd887 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpOutTestCase.cs @@ -3,7 +3,9 @@ namespace OpenTelemetry.Instrumentation.Http.Tests; +#pragma warning disable CA1515 public class HttpOutTestCase +#pragma warning restore CA1515 { public HttpOutTestCase(string name, string method, string url, Dictionary? headers, int responseCode, string spanName, bool responseExpected, bool? recordException, string spanStatus, Dictionary spanAttributes) { diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs index 7f91eaaf0c..e139b23237 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpTestData.cs @@ -6,7 +6,7 @@ namespace OpenTelemetry.Instrumentation.Http.Tests; -public static class HttpTestData +internal static class HttpTestData { private static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs index ebcb77d0b0..9c035f97fa 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestActivitySourceTests.netfx.cs @@ -54,7 +54,7 @@ public HttpWebRequestActivitySourceTests() Activity.ForceDefaultIdFormat = false; this.testServer = TestHttpServer.RunServer( - ctx => ProcessServerRequest(ctx), + ProcessServerRequest, out this.testServerHost, out this.testServerPort); @@ -63,8 +63,8 @@ public HttpWebRequestActivitySourceTests() void ProcessServerRequest(HttpListenerContext context) { - string redirects = context.Request.QueryString["redirects"]; - if (!string.IsNullOrWhiteSpace(redirects) && int.TryParse(redirects, out int parsedRedirects) && parsedRedirects > 0) + var redirects = context.Request.QueryString["redirects"]; + if (!string.IsNullOrWhiteSpace(redirects) && int.TryParse(redirects, out var parsedRedirects) && parsedRedirects > 0) { context.Response.Redirect(this.BuildRequestUrl(queryString: $"redirects={--parsedRedirects}")); context.Response.OutputStream.Close(); @@ -74,7 +74,7 @@ void ProcessServerRequest(HttpListenerContext context) string responseContent; if (context.Request.QueryString["skipRequestContent"] == null) { - using StreamReader readStream = new StreamReader(context.Request.InputStream); + using var readStream = new StreamReader(context.Request.InputStream); responseContent = readStream.ReadToEnd(); } @@ -83,19 +83,12 @@ void ProcessServerRequest(HttpListenerContext context) responseContent = $"{{\"Id\":\"{Guid.NewGuid()}\"}}"; } - string responseCode = context.Request.QueryString["responseCode"]; - if (!string.IsNullOrWhiteSpace(responseCode)) - { - context.Response.StatusCode = int.Parse(responseCode); - } - else - { - context.Response.StatusCode = 200; - } + var responseCode = context.Request.QueryString["responseCode"]; + context.Response.StatusCode = !string.IsNullOrWhiteSpace(responseCode) ? int.Parse(responseCode) : 200; if (context.Response.StatusCode != 204) { - using StreamWriter writeStream = new StreamWriter(context.Response.OutputStream); + using var writeStream = new StreamWriter(context.Response.OutputStream); writeStream.Write(responseContent); } @@ -117,8 +110,8 @@ public void Dispose() [Fact] public void TestHttpDiagnosticListenerIsRegistered() { - bool listenerFound = false; - using ActivityListener activityListener = new ActivityListener + var listenerFound = false; + using var activityListener = new ActivityListener { ShouldListenTo = activitySource => { @@ -182,7 +175,7 @@ public async Task TestBasicReceiveAndResponseEvents(string method, string queryS Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be a response. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); @@ -222,7 +215,7 @@ public async Task TestBasicReceiveAndResponseEventsWithoutSampling(string method [InlineData("POST", 3)] public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int mode) { - string url = this.BuildRequestUrl(); + var url = this.BuildRequestUrl(); using var eventRecords = new ActivitySourceRecorder(); @@ -244,9 +237,9 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 2: { - object state = new object(); - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - IAsyncResult asyncResult = webRequest.BeginGetRequestStream( + var state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var asyncResult = webRequest.BeginGetRequestStream( ar => { Assert.Equal(state, ar.AsyncState); @@ -265,8 +258,8 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 3: { - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - object state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var state = new object(); webRequest.BeginGetRequestStream( ar => { @@ -290,7 +283,7 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int Assert.NotNull(stream); - using StreamWriter writer = new StreamWriter(stream); + using var writer = new StreamWriter(stream); writer.WriteLine("hello world"); } @@ -306,9 +299,9 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 2: { - object state = new object(); - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - IAsyncResult asyncResult = webRequest.BeginGetResponse( + var state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var asyncResult = webRequest.BeginGetResponse( ar => { Assert.Equal(state, ar.AsyncState); @@ -327,8 +320,8 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int break; case 3: { - using EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset); - object state = new object(); + using var handle = new EventWaitHandle(false, EventResetMode.ManualReset); + var state = new object(); webRequest.BeginGetResponse( ar => { @@ -352,7 +345,7 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int Assert.NotNull(webResponse); - using StreamReader reader = new StreamReader(webResponse.GetResponseStream()); + using var reader = new StreamReader(webResponse.GetResponseStream()); reader.ReadToEnd(); // Make sure response is not disposed. @@ -362,7 +355,7 @@ public async Task TestBasicReceiveAndResponseWebRequestEvents(string method, int Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be a response. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); @@ -450,14 +443,14 @@ public async Task DoNotInjectTraceParentWhenPresent(string method) [InlineData("POST")] public async Task TestResponseWithoutContentEvents(string method) { - string url = this.BuildRequestUrl(queryString: "responseCode=204"); + var url = this.BuildRequestUrl(queryString: "responseCode=204"); using var eventRecords = new ActivitySourceRecorder(); // Send a random Http request to generate some events using (var client = new HttpClient()) { - using HttpResponseMessage response = method == "GET" + using var response = method == "GET" ? await client.GetAsync(new Uri(url)) : await client.PostAsync(new Uri(url), new StringContent("hello world")); } @@ -468,7 +461,7 @@ public async Task TestResponseWithoutContentEvents(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be a response. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); @@ -490,7 +483,7 @@ public async Task TestRedirectedRequest(string method) using (var client = new HttpClient()) { - using HttpResponseMessage response = method == "GET" + using var response = method == "GET" ? await client.GetAsync(new Uri(this.BuildRequestUrl(queryString: "redirects=10"))) : await client.PostAsync(new Uri(this.BuildRequestUrl(queryString: "redirects=10")), new StringContent("hello world")); } @@ -509,8 +502,8 @@ public async Task TestRedirectedRequest(string method) [InlineData("POST")] public async Task TestRequestWithException(string method) { - string host = Guid.NewGuid().ToString() + ".com"; - string url = method == "GET" + var host = Guid.NewGuid().ToString() + ".com"; + var url = method == "GET" ? $"http://{host}" : $"http://{host}"; @@ -534,10 +527,10 @@ public async Task TestRequestWithException(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); // Check to make sure: The first record must be a request, the next record must be an exception. - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(host, null, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, activity.Status); @@ -552,9 +545,9 @@ public async Task TestRequestWithException(string method) [InlineData("POST")] public async Task TestCanceledRequest(string method) { - string url = this.BuildRequestUrl(); + var url = this.BuildRequestUrl(); - CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); using var eventRecords = new ActivitySourceRecorder(_ => { cts.Cancel(); }); using (var client = new HttpClient()) @@ -565,7 +558,7 @@ public async Task TestCanceledRequest(string method) ? client.GetAsync(new Uri(url), cts.Token) : client.PostAsync(new Uri(url), new StringContent("hello world"), cts.Token); }); - Assert.True(ex is TaskCanceledException || ex is WebException); + Assert.True(ex is TaskCanceledException or WebException); } // We should have one Start event and one Stop event with an exception. @@ -573,10 +566,10 @@ public async Task TestCanceledRequest(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); @@ -591,7 +584,7 @@ public async Task TestCanceledRequest(string method) [InlineData("POST")] public async Task TestSecureTransportFailureRequest(string method) { - string url = "https://expired.badssl.com/"; + var url = "https://expired.badssl.com/"; using var eventRecords = new ActivitySourceRecorder(); @@ -612,10 +605,10 @@ public async Task TestSecureTransportFailureRequest(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags("expired.badssl.com", null, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); @@ -634,7 +627,7 @@ public async Task TestSecureTransportRetryFailureRequest(string method) // It should retry. What we want to test for is 1 start, 1 exception event even // though multiple are actually sent. - string url = this.BuildRequestUrl(useHttps: true); + var url = this.BuildRequestUrl(useHttps: true); using var eventRecords = new ActivitySourceRecorder(); @@ -654,10 +647,10 @@ public async Task TestSecureTransportRetryFailureRequest(string method) Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Start")); Assert.Equal(1, eventRecords.Records.Count(rec => rec.Key == "Stop")); - Activity activity = AssertFirstEventWasStart(eventRecords); + var activity = AssertFirstEventWasStart(eventRecords); VerifyActivityStartTags(this.netPeerName, this.netPeerPort, method, url, activity); - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair exceptionEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var exceptionEvent)); Assert.Equal("Stop", exceptionEvent.Key); Assert.NotEqual(ActivityStatusCode.Unset, exceptionEvent.Value.Status); @@ -697,19 +690,19 @@ public async Task TestMultipleConcurrentRequests() using var parentActivity = new Activity("parent").Start(); using var eventRecords = new ActivitySourceRecorder(); - Dictionary> requestData = new Dictionary>(); - for (int i = 0; i < 10; i++) + Dictionary> requestData = []; + for (var i = 0; i < 10; i++) { - Uri uriWithRedirect = new Uri(this.BuildRequestUrl(queryString: $"q={i}&redirects=3")); + var uriWithRedirect = new Uri(this.BuildRequestUrl(queryString: $"q={i}&redirects=3")); requestData[uriWithRedirect] = null; } // Issue all requests simultaneously using var httpClient = new HttpClient(); - Dictionary> tasks = new Dictionary>(); + Dictionary> tasks = []; - CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); foreach (var url in requestData.Keys) { tasks.Add(url, httpClient.GetAsync(url, cts.Token)); @@ -736,18 +729,17 @@ await Task.WhenAll(tasks.Select(t => t.Value).ToArray()).ContinueWith(async _ => // Check to make sure: We have a WebRequest and a WebResponse for each successful request foreach (var pair in eventRecords.Records) { - Activity activity = pair.Value; + var activity = pair.Value; Assert.True( - pair.Key == "Start" || - pair.Key == "Stop", + pair.Key is "Start" or "Stop", "An unexpected event of name " + pair.Key + "was received"); } } private static Activity AssertFirstEventWasStart(ActivitySourceRecorder eventRecords) { - Assert.True(eventRecords.Records.TryDequeue(out KeyValuePair startEvent)); + Assert.True(eventRecords.Records.TryDequeue(out var startEvent)); Assert.Equal("Start", startEvent.Key); return startEvent.Value; } @@ -786,7 +778,7 @@ private static void VerifyActivityStopTags(int statusCode, Activity activity) private static void ValidateBaggage(HttpWebRequest request) { - string[] baggage = request.Headers["baggage"].Split(','); + var baggage = request.Headers["baggage"].Split(','); Assert.Equal(3, baggage.Length); Assert.Contains("key=value", baggage); diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs index a314e456db..cdc717d00b 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.Basic.cs @@ -87,8 +87,8 @@ public async Task BacksOffIfAlreadyInstrumented() [Fact] public async Task RequestNotCollectedWhenInstrumentationFilterApplied() { - bool httpWebRequestFilterApplied = false; - bool httpRequestMessageFilterApplied = false; + var httpWebRequestFilterApplied = false; + var httpRequestMessageFilterApplied = false; var exportedItems = new List(); @@ -186,8 +186,8 @@ public async Task InjectsHeadersAsync() Assert.NotEqual(default, activity.Context.SpanId); #if NETFRAMEWORK - string traceparent = request.Headers.Get("traceparent"); - string tracestate = request.Headers.Get("tracestate"); + var traceparent = request.Headers.Get("traceparent"); + var tracestate = request.Headers.Get("tracestate"); Assert.Equal($"00-{activity.Context.TraceId}-{activity.Context.SpanId}-01", traceparent); Assert.Equal("k1=v1,k2=v2", tracestate); @@ -285,7 +285,7 @@ public void AddHttpClientInstrumentationUsesOptionsApi(string? name) { name ??= Options.DefaultName; - int configurationDelegateInvocations = 0; + var configurationDelegateInvocations = 0; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .ConfigureServices(services => @@ -305,7 +305,7 @@ public void AddHttpClientInstrumentationUsesOptionsApi(string? name) public async Task ReportsExceptionEventForNetworkFailures() { var exportedItems = new List(); - bool exceptionThrown = false; + var exceptionThrown = false; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation(o => o.RecordException = true) @@ -334,7 +334,7 @@ public async Task ReportsExceptionEventForNetworkFailures() public async Task ReportsExceptionEventOnErrorResponse() { var exportedItems = new List(); - bool exceptionThrown = false; + var exceptionThrown = false; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation(o => o.RecordException = true) diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs index 24ebf2e3fe..9e01f266c4 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/HttpWebRequestTests.cs @@ -34,11 +34,11 @@ public void HttpOutCallsAreCollectedSuccessfully(HttpOutTestCase tc) out var host, out var port); - bool enrichWithHttpWebRequestCalled = false; - bool enrichWithHttpWebResponseCalled = false; - bool enrichWithHttpRequestMessageCalled = false; - bool enrichWithHttpResponseMessageCalled = false; - bool enrichWithExceptionCalled = false; + var enrichWithHttpWebRequestCalled = false; + var enrichWithHttpWebResponseCalled = false; + var enrichWithHttpRequestMessageCalled = false; + var enrichWithHttpResponseMessageCalled = false; + var enrichWithExceptionCalled = false; var exportedItems = new List(); using var tracerProvider = Sdk.CreateTracerProviderBuilder() @@ -92,19 +92,14 @@ public void HttpOutCallsAreCollectedSuccessfully(HttpOutTestCase tc) x => x.Key, x => { - if (x.Key == "network.protocol.version") - { - return "1.1"; - } - - return HttpTestData.NormalizeValues(x.Value, host, port); + return x.Key == "network.protocol.version" ? "1.1" : HttpTestData.NormalizeValues(x.Value, host, port); }); - foreach (KeyValuePair tag in activity.TagObjects) + foreach (var tag in activity.TagObjects) { var tagValue = tag.Value?.ToString(); - if (!tc.SpanAttributes.TryGetValue(tag.Key, out string? value)) + if (!tc.SpanAttributes.TryGetValue(tag.Key, out var value)) { if (tag.Key == SpanAttributeConstants.StatusCodeKey) { diff --git a/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs b/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs index 43a56ae26f..40143c2e6d 100644 --- a/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs +++ b/test/OpenTelemetry.Instrumentation.Http.Tests/RepeatHandler.cs @@ -7,7 +7,7 @@ namespace OpenTelemetry.Tests; -public class RepeatHandler : DelegatingHandler +internal class RepeatHandler : DelegatingHandler { private readonly int maxRetries; @@ -22,7 +22,7 @@ protected override async Task SendAsync( CancellationToken cancellationToken) { HttpResponseMessage? response = null; - for (int i = 0; i < this.maxRetries; i++) + for (var i = 0; i < this.maxRetries; i++) { response?.Dispose(); diff --git a/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs b/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs index 445818e461..849b30f0c3 100644 --- a/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs +++ b/test/OpenTelemetry.Instrumentation.Owin.Tests/DiagnosticsMiddlewareTests.cs @@ -24,7 +24,7 @@ public class DiagnosticsMiddlewareTests : IDisposable public DiagnosticsMiddlewareTests() { - Random random = new Random(); + var random = new Random(); var retryCount = 5; do { @@ -60,7 +60,7 @@ public DiagnosticsMiddlewareTests() return next(); }); - HttpConfiguration config = new HttpConfiguration(); + var config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", @@ -120,8 +120,8 @@ public async Task OutgoingRequestInstrumentationTest( bool generateRemoteException = false, bool recordException = false) { - List stoppedActivities = new List(); - List exportedMetrics = new List(); + List stoppedActivities = []; + List exportedMetrics = []; var builder = Sdk.CreateTracerProviderBuilder() .AddInMemoryExporter(stoppedActivities); @@ -135,9 +135,9 @@ public async Task OutgoingRequestInstrumentationTest( { if (enrich) { - if (!enrichmentException) - { - options.Enrich = (activity, eventName, context, exception) => + options.Enrich = enrichmentException + ? (_, _, _, _) => throw new Exception("Error while enriching activity") + : (activity, eventName, _, _) => { switch (eventName) { @@ -147,13 +147,10 @@ public async Task OutgoingRequestInstrumentationTest( case OwinEnrichEventType.EndRequest: activity.SetTag("client.endrequest", nameof(OwinEnrichEventType.EndRequest)); break; + default: + break; } }; - } - else - { - options.Enrich = (activity, eventName, context, exception) => throw new Exception("Error while enriching activity"); - } } options.Filter = _ => !filter; @@ -166,12 +163,12 @@ public async Task OutgoingRequestInstrumentationTest( meterBuilder.AddOwinInstrumentation(); } - using TracerProvider tracerProvider = builder.Build(); - using MeterProvider meterProvider = meterBuilder.Build(); + using var tracerProvider = builder.Build(); + using var meterProvider = meterBuilder.Build(); - using HttpClient client = new HttpClient(); + using var client = new HttpClient(); - Uri requestUri = generateRemoteException + var requestUri = generateRemoteException ? new Uri($"{this.serviceBaseUri}exception") : new Uri($"{this.serviceBaseUri}api/test"); @@ -192,7 +189,7 @@ Owin has finished to inspect the activity status. */ Assert.NotEmpty(stoppedActivities); Assert.Single(stoppedActivities); - Activity activity = stoppedActivities[0]; + var activity = stoppedActivities[0]; Assert.Equal(OwinInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName); Assert.Equal(requestUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == SemanticConventions.AttributeServerAddress).Value); @@ -257,6 +254,8 @@ Owin has finished to inspect the activity status. */ case SemanticConventions.AttributeHttpResponseStatusCode: Assert.Equal(generateRemoteException ? 500 : 200, tag.Value); break; + default: + break; } } } @@ -295,7 +294,7 @@ public async Task QueryParametersAreRedacted( Environment.SetEnvironmentVariable("OTEL_DOTNET_EXPERIMENTAL_OWIN_DISABLE_URL_QUERY_REDACTION", "true"); } - List stoppedActivities = new List(); + List stoppedActivities = []; var builder = Sdk.CreateTracerProviderBuilder() .ConfigureServices(services => @@ -316,10 +315,10 @@ public async Task QueryParametersAreRedacted( .AddOwinInstrumentation() .Build(); - using HttpClient client = new HttpClient(); + using var client = new HttpClient(); - Uri requestUri = new Uri($"{this.serviceBaseUri}{actualPath}"); - Uri expectedRequestUri = new Uri($"{this.serviceBaseUri}{expectedPath}"); + var requestUri = new Uri($"{this.serviceBaseUri}{actualPath}"); + var expectedRequestUri = new Uri($"{this.serviceBaseUri}{expectedPath}"); this.requestCompleteHandle.Reset(); @@ -340,7 +339,7 @@ Owin has finished to inspect the activity status. */ Assert.NotEmpty(stoppedActivities); Assert.Single(stoppedActivities); - Activity activity = stoppedActivities[0]; + var activity = stoppedActivities[0]; Assert.Equal(OwinInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName); Assert.Equal(requestUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == SemanticConventions.AttributeServerAddress).Value); @@ -356,7 +355,7 @@ Owin has finished to inspect the activity status. */ private List GetMetricPoints(Metric metric) { - List metricPoints = new(); + List metricPoints = []; foreach (var metricPoint in metric.GetMetricPoints()) { diff --git a/test/OpenTelemetry.Instrumentation.Quartz.Tests/QuartzDiagnosticListenerTests.cs b/test/OpenTelemetry.Instrumentation.Quartz.Tests/QuartzDiagnosticListenerTests.cs index b2faa5ea71..09289ecf17 100644 --- a/test/OpenTelemetry.Instrumentation.Quartz.Tests/QuartzDiagnosticListenerTests.cs +++ b/test/OpenTelemetry.Instrumentation.Quartz.Tests/QuartzDiagnosticListenerTests.cs @@ -21,8 +21,8 @@ public QuartzDiagnosticListenerTests() public async Task Should_Create_Activity() { // Arrange - Barrier barrier = new Barrier(2); - List jobExecTimestamps = new List(); + var barrier = new Barrier(2); + List jobExecTimestamps = []; var exportedItems = new List(); using var tel = Sdk.CreateTracerProviderBuilder() @@ -38,7 +38,7 @@ public async Task Should_Create_Activity() scheduler.Context.Put("DATESTAMPS", jobExecTimestamps); await scheduler.Start(); - JobDataMap jobDataMap = new JobDataMap { { "A", "B" } }; + var jobDataMap = new JobDataMap { { "A", "B" } }; var name = Guid.NewGuid().ToString(); var job = JobBuilder.Create() @@ -74,8 +74,8 @@ public async Task Should_Create_Activity() public async Task Should_Create_Activity_And_Enrich_When_Enrich() { // Arrange - Barrier barrier = new Barrier(2); - List jobExecTimestamps = new List(); + var barrier = new Barrier(2); + List jobExecTimestamps = []; var exportedItems = new List(); @@ -105,7 +105,7 @@ public async Task Should_Create_Activity_And_Enrich_When_Enrich() await scheduler.Start(); var testId = Guid.NewGuid().ToString(); - JobDataMap jobDataMap = new JobDataMap { { "TestId", testId } }; + var jobDataMap = new JobDataMap { { "TestId", testId } }; var name = Guid.NewGuid().ToString(); var job = JobBuilder.Create() @@ -141,8 +141,8 @@ public async Task Should_Create_Activity_And_Enrich_When_Enrich() public async Task Should_Record_Exception_When_Record_Exception_Enabled() { // Arrange - Barrier barrier = new Barrier(2); - List jobExecTimestamps = new List(); + var barrier = new Barrier(2); + List jobExecTimestamps = []; var exportedItems = new List(); @@ -162,7 +162,7 @@ public async Task Should_Record_Exception_When_Record_Exception_Enabled() await scheduler.Start(); var testId = Guid.NewGuid().ToString(); - JobDataMap jobDataMap = new JobDataMap { { "TestId", testId } }; + var jobDataMap = new JobDataMap { { "TestId", testId } }; var name = Guid.NewGuid().ToString(); var job = JobBuilder.Create() @@ -195,8 +195,8 @@ public async Task Should_Record_Exception_When_Record_Exception_Enabled() public async Task Should_Enrich_Exception_When_Record_Exception_Enabled_And_Enrich() { // Arrange - Barrier barrier = new Barrier(2); - List jobExecTimestamps = new List(); + var barrier = new Barrier(2); + List jobExecTimestamps = []; var exportedItems = new List(); @@ -229,7 +229,7 @@ public async Task Should_Enrich_Exception_When_Record_Exception_Enabled_And_Enri await scheduler.Start(); var testId = Guid.NewGuid().ToString(); - JobDataMap jobDataMap = new JobDataMap { { "TestId", testId } }; + var jobDataMap = new JobDataMap { { "TestId", testId } }; var name = Guid.NewGuid().ToString(); var job = JobBuilder.Create() @@ -262,8 +262,8 @@ public async Task Should_Enrich_Exception_When_Record_Exception_Enabled_And_Enri public async Task Should_Creates_Activity_Event_On_Job_Execution_Exception() { // Arrange - Barrier barrier = new Barrier(2); - List jobExecTimestamps = new List(); + var barrier = new Barrier(2); + List jobExecTimestamps = []; var exportedItems = new List(); using var tel = Sdk.CreateTracerProviderBuilder() @@ -291,7 +291,7 @@ public async Task Should_Creates_Activity_Event_On_Job_Execution_Exception() await scheduler.Start(); var testId = Guid.NewGuid().ToString(); - JobDataMap jobDataMap = new JobDataMap { { "TestId", testId } }; + var jobDataMap = new JobDataMap { { "TestId", testId } }; var name = Guid.NewGuid().ToString(); var job = JobBuilder.Create() @@ -323,8 +323,8 @@ public async Task Should_Creates_Activity_Event_On_Job_Execution_Exception() public async Task Should_Not_Record_Activity_When_Trace_Operation_Is_Not_Present() { // Arrange - Barrier barrier = new Barrier(2); - List jobExecTimestamps = new List(); + var barrier = new Barrier(2); + List jobExecTimestamps = []; var exportedItems = new List(); @@ -332,7 +332,7 @@ public async Task Should_Not_Record_Activity_When_Trace_Operation_Is_Not_Present .SetSampler(new AlwaysOnSampler()) .AddQuartzInstrumentation(q => { - q.TracedOperations = new HashSet(); + q.TracedOperations = []; }) .AddInMemoryExporter(exportedItems) .Build(); @@ -346,7 +346,7 @@ public async Task Should_Not_Record_Activity_When_Trace_Operation_Is_Not_Present await scheduler.Start(); var testId = Guid.NewGuid().ToString(); - JobDataMap jobDataMap = new JobDataMap { { "TestId", testId } }; + var jobDataMap = new JobDataMap { { "TestId", testId } }; var name = Guid.NewGuid().ToString(); var job = JobBuilder.Create() diff --git a/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJob.cs b/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJob.cs index 7be379f91c..e1fbee1e48 100644 --- a/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJob.cs +++ b/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJob.cs @@ -5,14 +5,14 @@ namespace OpenTelemetry.Instrumentation.Quartz.Tests; -public class TestJob : IJob +internal class TestJob : IJob { public Task Execute(IJobExecutionContext context) { try { - List jobExecTimestamps = (List)context.Scheduler.Context.Get("DATESTAMPS"); - Barrier barrier = (Barrier)context.Scheduler.Context.Get("BARRIER"); + var jobExecTimestamps = (List)context.Scheduler.Context.Get("DATESTAMPS"); + var barrier = (Barrier)context.Scheduler.Context.Get("BARRIER"); jobExecTimestamps.Add(DateTime.UtcNow); diff --git a/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJobExecutionExceptionJob.cs b/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJobExecutionExceptionJob.cs index 6ebed283b5..bb81998837 100644 --- a/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJobExecutionExceptionJob.cs +++ b/test/OpenTelemetry.Instrumentation.Quartz.Tests/TestJobExecutionExceptionJob.cs @@ -5,7 +5,7 @@ namespace OpenTelemetry.Instrumentation.Quartz.Tests; -public class TestJobExecutionExceptionJob : IJob +internal class TestJobExecutionExceptionJob : IJob { public Task Execute(IJobExecutionContext context) { diff --git a/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeInstrumentationOptionsTests.cs b/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeInstrumentationOptionsTests.cs index 39d8faff0d..4ee8aceb74 100644 --- a/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeInstrumentationOptionsTests.cs +++ b/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeInstrumentationOptionsTests.cs @@ -3,7 +3,7 @@ namespace OpenTelemetry.Instrumentation.Runtime.Tests; -public class RuntimeInstrumentationOptionsTests +internal class RuntimeInstrumentationOptionsTests { /* [Fact] diff --git a/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs b/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs index ace5166232..877c3a4d52 100644 --- a/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs +++ b/test/OpenTelemetry.Instrumentation.Runtime.Tests/RuntimeMetricsTests.cs @@ -113,9 +113,9 @@ public async Task ThreadingRelatedMetricsTest() .Build(); // Bump the count for `thread_pool.completed_items.count` metric - int taskCount = 50; - List tasks = new List(); - for (int i = 0; i < taskCount; i++) + var taskCount = 50; + var tasks = new List(); + for (var i = 0; i < taskCount; i++) { tasks.Add(Task.Run(() => { })); } @@ -137,15 +137,19 @@ public async Task ThreadingRelatedMetricsTest() var queueLengthMetric = exportedItems.FirstOrDefault(i => i.Name == "process.runtime.dotnet.thread_pool.queue.length"); Assert.NotNull(queueLengthMetric); - List timers = new List(); + var timers = new List(); try { // Create 10 timers to bump timer.count metrics. - int timerCount = 10; - TimerCallback timerCallback = _ => { }; - for (int i = 0; i < timerCount; i++) + var timerCount = 10; +#pragma warning disable SA1313 + static void TimerCallback(object? _) { - Timer timer = new Timer(timerCallback, null, 1000, 250); + } +#pragma warning restore SA1313 + for (var i = 0; i < timerCount; i++) + { + var timer = new Timer(TimerCallback, null, 1000, 250); timers.Add(timer); } @@ -157,7 +161,7 @@ public async Task ThreadingRelatedMetricsTest() } finally { - for (int i = 0; i < timers.Count; i++) + for (var i = 0; i < timers.Count; i++) { timers[i].Dispose(); } diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTests.cs b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTests.cs index cc70a4d8ee..6c13ba7171 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTests.cs +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTests.cs @@ -59,15 +59,15 @@ public void SuccessfulCommandTest( }) .Build(); - using SqlConnection sqlConnection = new SqlConnection(this.GetConnectionString()); + using var sqlConnection = new SqlConnection(this.GetConnectionString()); sqlConnection.Open(); - string dataSource = sqlConnection.DataSource; + var dataSource = sqlConnection.DataSource; sqlConnection.ChangeDatabase("master"); #pragma warning disable CA2100 - using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection) + using var sqlCommand = new SqlCommand(commandText, sqlConnection) #pragma warning restore CA2100 { CommandType = commandType, @@ -107,14 +107,11 @@ public void SuccessfulCommandTest( private string GetConnectionString() { - switch (this.fixture.DatabaseContainer) + return this.fixture.DatabaseContainer switch { - case SqlEdgeContainer container: - return container.GetConnectionString(); - case MsSqlContainer container: - return container.GetConnectionString(); - default: - throw new InvalidOperationException($"Container type '${this.fixture.DatabaseContainer.GetType().Name}' is not supported."); - } + SqlEdgeContainer container => container.GetConnectionString(), + MsSqlContainer container => container.GetConnectionString(), + _ => throw new InvalidOperationException($"Container type '${this.fixture.DatabaseContainer.GetType().Name}' is not supported."), + }; } } diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTestsFixture.cs b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTestsFixture.cs index 28e39184bf..549afff40b 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTestsFixture.cs +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientIntegrationTestsFixture.cs @@ -9,21 +9,21 @@ namespace OpenTelemetry.Instrumentation.SqlClient.Tests; +#pragma warning disable CA1515 public sealed class SqlClientIntegrationTestsFixture : IAsyncLifetime +#pragma warning restore CA1515 { // The Microsoft SQL Server Docker image is not compatible with ARM devices, such as Macs with Apple Silicon. - private readonly IContainer databaseContainer = Architecture.Arm64.Equals(RuntimeInformation.ProcessArchitecture) ? CreateSqlEdge() : CreateMsSql(); - - public IContainer DatabaseContainer => this.databaseContainer; + public IContainer DatabaseContainer { get; } = Architecture.Arm64.Equals(RuntimeInformation.ProcessArchitecture) ? CreateSqlEdge() : CreateMsSql(); public Task InitializeAsync() { - return this.databaseContainer.StartAsync(); + return this.DatabaseContainer.StartAsync(); } public Task DisposeAsync() { - return this.databaseContainer.DisposeAsync().AsTask(); + return this.DatabaseContainer.DisposeAsync().AsTask(); } private static SqlEdgeContainer CreateSqlEdge() diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTestCase.cs b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTestCase.cs index f2b7e07e2b..62ba66c37c 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTestCase.cs +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTestCase.cs @@ -5,7 +5,9 @@ namespace OpenTelemetry.Instrumentation.SqlClient.Tests; +#pragma warning disable CA1515 public class SqlClientTestCase : IEnumerable +#pragma warning restore CA1515 { public string ConnectionString { get; set; } = string.Empty; diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs index 9e68bb1624..5a5bc8d89c 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlClientTests.cs @@ -44,8 +44,8 @@ public void SqlClient_BadArgs() [Fact] public void SqlClient_NamedOptions() { - int defaultExporterOptionsConfigureOptionsInvocations = 0; - int namedExporterOptionsConfigureOptionsInvocations = 0; + var defaultExporterOptionsConfigureOptionsInvocations = 0; + var namedExporterOptionsConfigureOptionsInvocations = 0; using var tracerProvider = Sdk.CreateTracerProviderBuilder() .ConfigureServices(services => @@ -310,12 +310,7 @@ public void ShouldCollectTelemetryWhenFilterEvaluatesToTrue() }, cmd => { - if (cmd is SqlCommand command) - { - return command.CommandText == "select 2"; - } - - return true; + return cmd is not SqlCommand command || command.CommandText == "select 2"; }); Assert.Single(activities); @@ -333,12 +328,7 @@ public void ShouldNotCollectTelemetryWhenFilterEvaluatesToFalse() }, cmd => { - if (cmd is SqlCommand command) - { - return command.CommandText == "select 2"; - } - - return true; + return cmd is not SqlCommand command || command.CommandText == "select 2"; }); Assert.Empty(activities); @@ -406,7 +396,7 @@ internal static void VerifyActivityData( if (shouldEnrich) { Assert.NotEmpty(activity.Tags.Where(tag => tag.Key == "enriched")); - Assert.Equal("yes", activity.Tags.Where(tag => tag.Key == "enriched").FirstOrDefault().Value); + Assert.Equal("yes", activity.Tags.FirstOrDefault(tag => tag.Key == "enriched").Value); } else { @@ -461,6 +451,12 @@ internal static void VerifyActivityData( Assert.Null(activity.GetTagValue(SemanticConventions.AttributeDbQueryText)); } + break; + case CommandType.TableDirect: + Assert.Fail("Not supported command type: CommandType.TableDirect"); + break; + default: + Assert.Fail($"Not supported command type: {commandType}"); break; } } @@ -614,7 +610,7 @@ private Activity[] RunCommandWithFilter( afterExecuteEventData); } - return activities.ToArray(); + return [.. activities]; } #endif diff --git a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs index 2280e5502f..d91951692a 100644 --- a/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.SqlClient.Tests/SqlEventSourceTests.netfx.cs @@ -45,16 +45,16 @@ public async Task SuccessfulCommandTest(CommandType commandType, string commandT .Build(); Assert.NotNull(SqlConnectionString); - using SqlConnection sqlConnection = new SqlConnection(SqlConnectionString); + using var sqlConnection = new SqlConnection(SqlConnectionString); await sqlConnection.OpenAsync(); - string dataSource = sqlConnection.DataSource; + var dataSource = sqlConnection.DataSource; sqlConnection.ChangeDatabase("master"); #pragma warning disable CA2100 - using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection) + using var sqlCommand = new SqlCommand(commandText, sqlConnection) #pragma warning restore CA2100 { CommandType = commandType, @@ -114,7 +114,7 @@ public void EventSourceFakeTests( bool emitOldAttributes = true, bool emitNewAttributes = false) { - using IFakeBehavingSqlEventSource fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType); + using var fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var exportedItems = new List(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() @@ -128,21 +128,21 @@ public void EventSourceFakeTests( }) .Build(); - int objectId = Guid.NewGuid().GetHashCode(); + var objectId = Guid.NewGuid().GetHashCode(); var dataSource = "127.0.0.1\\instanceName,port"; fakeSqlEventSource.WriteBeginExecuteEvent(objectId, dataSource, "master", commandType == CommandType.StoredProcedure ? commandText : string.Empty); // success is stored in the first bit in compositeState 0b001 - int successFlag = !isFailure ? 1 : 0; + var successFlag = !isFailure ? 1 : 0; // isSqlException is stored in the second bit in compositeState 0b010 - int isSqlExceptionFlag = sqlExceptionNumber > 0 ? 2 : 0; + var isSqlExceptionFlag = sqlExceptionNumber > 0 ? 2 : 0; // synchronous state is stored in the third bit in compositeState 0b100 - int synchronousFlag = false ? 4 : 0; + var synchronousFlag = false ? 4 : 0; - int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag; + var compositeState = successFlag | isSqlExceptionFlag | synchronousFlag; fakeSqlEventSource.WriteEndExecuteEvent(objectId, compositeState, sqlExceptionNumber); shutdownSignal.Dispose(); @@ -158,7 +158,7 @@ public void EventSourceFakeTests( [InlineData(typeof(FakeMisbehavingMdsSqlEventSource))] public void EventSourceFakeUnknownEventWithNullPayloadTest(Type eventSourceType) { - using IFakeMisbehavingSqlEventSource fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType); + using var fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var exportedItems = new List(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() @@ -178,7 +178,7 @@ public void EventSourceFakeUnknownEventWithNullPayloadTest(Type eventSourceType) [InlineData(typeof(FakeMisbehavingMdsSqlEventSource))] public void EventSourceFakeInvalidPayloadTest(Type eventSourceType) { - using IFakeMisbehavingSqlEventSource fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType); + using var fakeSqlEventSource = (IFakeMisbehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var exportedItems = new List(); using var shutdownSignal = Sdk.CreateTracerProviderBuilder() @@ -199,7 +199,7 @@ public void EventSourceFakeInvalidPayloadTest(Type eventSourceType) [InlineData(typeof(FakeBehavingMdsSqlEventSource))] public void DefaultCaptureTextFalse(Type eventSourceType) { - using IFakeBehavingSqlEventSource fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType); + using var fakeSqlEventSource = (IFakeBehavingSqlEventSource)Activator.CreateInstance(eventSourceType); var exportedItems = new List(); var shutdownSignal = Sdk.CreateTracerProviderBuilder() @@ -207,21 +207,21 @@ public void DefaultCaptureTextFalse(Type eventSourceType) .AddSqlClientInstrumentation() .Build(); - int objectId = Guid.NewGuid().GetHashCode(); + var objectId = Guid.NewGuid().GetHashCode(); const string commandText = "TestCommandTest"; fakeSqlEventSource.WriteBeginExecuteEvent(objectId, "127.0.0.1", "master", commandText); // success is stored in the first bit in compositeState 0b001 - int successFlag = 1; + var successFlag = 1; // isSqlException is stored in the second bit in compositeState 0b010 - int isSqlExceptionFlag = 2; + var isSqlExceptionFlag = 2; // synchronous state is stored in the third bit in compositeState 0b100 - int synchronousFlag = 4; + var synchronousFlag = 4; - int compositeState = successFlag | isSqlExceptionFlag | synchronousFlag; + var compositeState = successFlag | isSqlExceptionFlag | synchronousFlag; fakeSqlEventSource.WriteEndExecuteEvent(objectId, compositeState, 0); shutdownSignal.Dispose(); diff --git a/test/Shared/CustomTextMapPropagator.cs b/test/Shared/CustomTextMapPropagator.cs index 8d3404e816..436879e8b5 100644 --- a/test/Shared/CustomTextMapPropagator.cs +++ b/test/Shared/CustomTextMapPropagator.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; using OpenTelemetry.Context.Propagation; diff --git a/test/Shared/EnabledOnDockerPlatformTheoryAttribute.cs b/test/Shared/EnabledOnDockerPlatformTheoryAttribute.cs index 215de236f9..bb4738d5c1 100644 --- a/test/Shared/EnabledOnDockerPlatformTheoryAttribute.cs +++ b/test/Shared/EnabledOnDockerPlatformTheoryAttribute.cs @@ -22,18 +22,29 @@ public EnabledOnDockerPlatformTheoryAttribute(DockerPlatform dockerPlatform) var stdout = new StringBuilder(); var stderr = new StringBuilder(); - void AppendStdout(object sender, DataReceivedEventArgs e) => stdout.Append(e.Data); - void AppendStderr(object sender, DataReceivedEventArgs e) => stderr.Append(e.Data); + void AppendStdout(object sender, DataReceivedEventArgs e) + { + stdout.Append(e.Data); + } - var processStartInfo = new ProcessStartInfo(); - processStartInfo.FileName = executable; - processStartInfo.Arguments = string.Join(" ", "version", "--format '{{.Server.Os}}'"); - processStartInfo.RedirectStandardOutput = true; - processStartInfo.RedirectStandardError = true; - processStartInfo.UseShellExecute = false; + void AppendStderr(object sender, DataReceivedEventArgs e) + { + stderr.Append(e.Data); + } - var process = new Process(); - process.StartInfo = processStartInfo; + var processStartInfo = new ProcessStartInfo + { + FileName = executable, + Arguments = string.Join(" ", "version", "--format '{{.Server.Os}}'"), + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + + var process = new Process + { + StartInfo = processStartInfo, + }; process.OutputDataReceived += AppendStdout; process.ErrorDataReceived += AppendStderr; @@ -58,7 +69,7 @@ public EnabledOnDockerPlatformTheoryAttribute(DockerPlatform dockerPlatform) this.Skip = $"The Docker {dockerPlatform} engine is not available."; } - public enum DockerPlatform + internal enum DockerPlatform { /// /// Docker Linux engine. diff --git a/test/Shared/EventSourceTestHelper.cs b/test/Shared/EventSourceTestHelper.cs index 02de7a2a76..837f3cd569 100644 --- a/test/Shared/EventSourceTestHelper.cs +++ b/test/Shared/EventSourceTestHelper.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics.Tracing; using System.Globalization; using System.Reflection; diff --git a/test/Shared/InMemoryEventListener.cs b/test/Shared/InMemoryEventListener.cs index bf3d3fd567..4ddb42bb52 100644 --- a/test/Shared/InMemoryEventListener.cs +++ b/test/Shared/InMemoryEventListener.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Collections.Concurrent; using System.Diagnostics.Tracing; diff --git a/test/Shared/PlatformHelpers.cs b/test/Shared/PlatformHelpers.cs index a737fa49f3..22b9c3a570 100644 --- a/test/Shared/PlatformHelpers.cs +++ b/test/Shared/PlatformHelpers.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - #pragma warning disable SA1649 // File name should match first type name #pragma warning disable SA1402 // File may only contain a single type diff --git a/test/Shared/SkipUnlessEnvVarFoundFactAttribute.cs b/test/Shared/SkipUnlessEnvVarFoundFactAttribute.cs index d6e4f02518..88bedacb31 100644 --- a/test/Shared/SkipUnlessEnvVarFoundFactAttribute.cs +++ b/test/Shared/SkipUnlessEnvVarFoundFactAttribute.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using Xunit; namespace OpenTelemetry.Tests; diff --git a/test/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs b/test/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs index 5820d36bef..2e43f8cb19 100644 --- a/test/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs +++ b/test/Shared/SkipUnlessEnvVarFoundTheoryAttribute.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using Xunit; namespace OpenTelemetry.Tests; diff --git a/test/Shared/TestActivityExportProcessor.cs b/test/Shared/TestActivityExportProcessor.cs index 0c4dadfb16..b882af8f8e 100644 --- a/test/Shared/TestActivityExportProcessor.cs +++ b/test/Shared/TestActivityExportProcessor.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; namespace OpenTelemetry.Tests; diff --git a/test/Shared/TestActivityProcessor.cs b/test/Shared/TestActivityProcessor.cs index b788c5fa7c..e0319da15a 100644 --- a/test/Shared/TestActivityProcessor.cs +++ b/test/Shared/TestActivityProcessor.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics; namespace OpenTelemetry.Tests; diff --git a/test/Shared/TestEventListener.cs b/test/Shared/TestEventListener.cs index 424ba512a6..29cb03d6bc 100644 --- a/test/Shared/TestEventListener.cs +++ b/test/Shared/TestEventListener.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using System.Diagnostics.Tracing; namespace OpenTelemetry.Tests; diff --git a/test/Shared/TestHttpServer.cs b/test/Shared/TestHttpServer.cs index c567606649..d294ff24eb 100644 --- a/test/Shared/TestHttpServer.cs +++ b/test/Shared/TestHttpServer.cs @@ -4,8 +4,6 @@ // Note: When implicit usings are enabled in a project this file will generate // warnings/errors without this suppression. -#nullable enable - using System.Net; #if !NETFRAMEWORK using System.Security.Cryptography; diff --git a/test/Shared/TestSampler.cs b/test/Shared/TestSampler.cs index c23bf68ed1..972985bfad 100644 --- a/test/Shared/TestSampler.cs +++ b/test/Shared/TestSampler.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using OpenTelemetry.Trace; namespace OpenTelemetry.Tests; diff --git a/test/Shared/TestTextMapPropagator.cs b/test/Shared/TestTextMapPropagator.cs index ba58606acf..5ce7fd9bd3 100644 --- a/test/Shared/TestTextMapPropagator.cs +++ b/test/Shared/TestTextMapPropagator.cs @@ -1,8 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#nullable enable - using OpenTelemetry.Context.Propagation; namespace OpenTelemetry.Tests;