From e61cea4cd7acac77767e7db78ca62fac5a40626e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Wed, 30 Oct 2024 17:10:02 +0100 Subject: [PATCH] [repo/WCF] Prepare to .NET9 (#2273) --- .../ActivityHelper.cs | 6 +- .../TelemetryHttpModule.cs | 8 +- .../AspNetParentSpanCorrector.cs | 17 +-- .../ClientChannelInstrumentation.cs | 8 +- .../HttpRequestMessagePropertyWrapper.cs | 19 ++-- .../RequestTelemetryStateTracker.cs | 9 +- .../TelemetryDispatchMessageInspector.cs | 8 +- .../WcfInstrumentationEventSource.cs | 2 +- src/Shared/PropertyFetcher.cs | 20 ++-- .../AspNetParentSpanCorrectorTests.netfx.cs | 6 +- .../TelemetryBindingElementForHttpTests.cs | 66 ++++++------ ...elemetryBindingElementForTcpTests.netfx.cs | 100 ++++++++---------- ...InspectorForOneWayOperationsTests.netfx.cs | 20 ++-- ...etryDispatchMessageInspectorTests.netfx.cs | 46 +++----- .../TelemetryPropagationTests.netfx.cs | 4 +- ...DownstreamInstrumentationBindingElement.cs | 2 + .../Tools/DownstreamInstrumentationChannel.cs | 4 +- ...DownstreamInstrumentationChannelFactory.cs | 9 +- ...wnstreamInstrumentationEndpointBehavior.cs | 2 + .../DownstreamInstrumentationExtensions.cs | 2 +- .../ErrorHandlerServiceBehavior.netfx.cs | 2 +- .../WCF/IServiceContract.cs | 2 + .../WCF/ServiceClient.cs | 2 + .../WCF/ServiceRequest.cs | 2 + .../WCF/ServiceResponse.cs | 2 + 25 files changed, 167 insertions(+), 201 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs index bf3717da0c..99c8fd8fd3 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/ActivityHelper.cs @@ -41,7 +41,7 @@ internal static class ActivityHelper /// if start has been called. public static bool HasStarted(HttpContext context, out Activity? aspNetActivity) { - object itemValue = context.Items[ContextKey]; + var itemValue = context.Items[ContextKey]; if (itemValue is ContextHolder contextHolder) { aspNetActivity = contextHolder.Activity; @@ -61,7 +61,7 @@ public static bool HasStarted(HttpContext context, out Activity? aspNetActivity) /// New root activity. public static Activity? StartAspNetActivity(TextMapPropagator textMapPropagator, HttpContext context, Action? onRequestStartedCallback) { - PropagationContext propagationContext = textMapPropagator.Extract(default, context.Request, HttpRequestHeaderValuesGetter); + var propagationContext = textMapPropagator.Extract(default, context.Request, HttpRequestHeaderValuesGetter); KeyValuePair[]? tags; if (context.Request?.Unvalidated?.Path is string path) @@ -75,7 +75,7 @@ public static bool HasStarted(HttpContext context, out Activity? aspNetActivity) tags = null; } - Activity? activity = AspNetSource.StartActivity(TelemetryHttpModule.AspNetActivityName, ActivityKind.Server, propagationContext.ActivityContext, tags); + var activity = AspNetSource.StartActivity(TelemetryHttpModule.AspNetActivityName, ActivityKind.Server, propagationContext.ActivityContext, tags); if (tags is not null) { diff --git a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModule.cs b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModule.cs index 92a8185447..f155c71352 100644 --- a/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModule.cs +++ b/src/OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule/TelemetryHttpModule.cs @@ -55,7 +55,7 @@ public void Init(HttpApplication context) // OnExecuteRequestStep is available starting with 4.7.1 try { - OnExecuteRequestStepMethodInfo.Invoke(context, new object[] { (Action)this.OnExecuteRequestStep }); + OnExecuteRequestStepMethodInfo.Invoke(context, [(Action)this.OnExecuteRequestStep]); } catch (Exception e) { @@ -80,11 +80,11 @@ private void OnExecuteRequestStep(HttpContextBase context, Action step) private void Application_EndRequest(object sender, EventArgs e) { AspNetTelemetryEventSource.Log.TraceCallback("Application_EndRequest"); - bool trackActivity = true; + var trackActivity = true; var context = ((HttpApplication)sender).Context; - if (!ActivityHelper.HasStarted(context, out Activity? aspNetActivity)) + if (!ActivityHelper.HasStarted(context, out var aspNetActivity)) { // Rewrite: In case of rewrite, a new request context is created, called the child request, and it goes through the entire IIS/ASP.NET integrated pipeline. // The child request can be mapped to any of the handlers configured in IIS, and it's execution is no different than it would be if it was received via the HTTP stack. @@ -119,7 +119,7 @@ private void Application_Error(object sender, EventArgs e) var exception = context.Error; if (exception != null) { - if (!ActivityHelper.HasStarted(context, out Activity? aspNetActivity)) + if (!ActivityHelper.HasStarted(context, out var aspNetActivity)) { aspNetActivity = ActivityHelper.StartAspNetActivity(Options.TextMapPropagator, context, Options.OnRequestStartedCallback); } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/AspNetParentSpanCorrector.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/AspNetParentSpanCorrector.cs index 9d8e691b61..bdcd994691 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/AspNetParentSpanCorrector.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/AspNetParentSpanCorrector.cs @@ -27,8 +27,8 @@ internal static class AspNetParentSpanCorrector private const string TelemetryHttpModuleOptionsTypeName = "OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModuleOptions, OpenTelemetry.Instrumentation.AspNet.TelemetryHttpModule"; private static readonly ReflectedInfo? ReflectedValues = Initialize(); - private static readonly PropertyFetcher RequestFetcher = new PropertyFetcher("Request"); - private static readonly PropertyFetcher HeadersFetcher = new PropertyFetcher("Headers"); + private static readonly PropertyFetcher RequestFetcher = new("Request"); + private static readonly PropertyFetcher HeadersFetcher = new("Headers"); private static bool isRegistered; public static void Register() @@ -63,11 +63,7 @@ private static void OnRequestStarted(Activity activity, object context) { try { - var isReadOnlyProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); - if (isReadOnlyProp == null) - { - throw new NotSupportedException("NameValueCollection.IsReadOnly property not found"); - } + var isReadOnlyProp = typeof(NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy) ?? throw new NotSupportedException("NameValueCollection.IsReadOnly property not found"); var setHeadersReadOnly = (Action)isReadOnlyProp.SetMethod.CreateDelegate(typeof(Action)); @@ -102,12 +98,7 @@ private static Func GenerateSubscribeLambda() var telemetryHttpModuleType = Type.GetType(TelemetryHttpModuleTypeName, true); var telemetryHttpModuleOptionsType = Type.GetType(TelemetryHttpModuleOptionsTypeName, true); - var onRequestStartedProp = telemetryHttpModuleOptionsType.GetProperty("OnRequestStartedCallback"); - if (onRequestStartedProp == null) - { - throw new NotSupportedException("TelemetryHttpModuleOptions.OnRequestStartedCallback property not found"); - } - + var onRequestStartedProp = telemetryHttpModuleOptionsType.GetProperty("OnRequestStartedCallback") ?? throw new NotSupportedException("TelemetryHttpModuleOptions.OnRequestStartedCallback property not found"); Func addOurCallbackToDelegate = (existingCallback) => { var myCallback = OnRequestStarted; diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ClientChannelInstrumentation.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ClientChannelInstrumentation.cs index 6fca3efada..ae569c3cf2 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ClientChannelInstrumentation.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ClientChannelInstrumentation.cs @@ -18,10 +18,10 @@ public static RequestTelemetryState BeforeSendRequest(Message request, Uri? remo return new RequestTelemetryState { SuppressionScope = SuppressDownstreamInstrumentation() }; } - Activity? activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( + var activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( WcfInstrumentationActivitySource.OutgoingRequestActivityName, ActivityKind.Client); - IDisposable? suppressionScope = SuppressDownstreamInstrumentation(); + var suppressionScope = SuppressDownstreamInstrumentation(); if (activity != null) { @@ -125,7 +125,7 @@ public static void AfterRequestCompleted(Message? reply, RequestTelemetryState? private static ActionMetadata GetActionMetadata(Message request, string action) { ActionMetadata? actionMetadata = null; - if (request.Properties.TryGetValue(TelemetryContextMessageProperty.Name, out object telemetryContextProperty)) + if (request.Properties.TryGetValue(TelemetryContextMessageProperty.Name, out var telemetryContextProperty)) { var actionMappings = (telemetryContextProperty as TelemetryContextMessageProperty)?.ActionMappings; if (actionMappings != null && actionMappings.TryGetValue(action, out var metadata)) @@ -134,7 +134,7 @@ private static ActionMetadata GetActionMetadata(Message request, string action) } } - return actionMetadata != null ? actionMetadata : new ActionMetadata( + return actionMetadata ?? new ActionMetadata( contractName: null, operationName: action); } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/HttpRequestMessagePropertyWrapper.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/HttpRequestMessagePropertyWrapper.cs index 26e62a054a..c6f4c58685 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/HttpRequestMessagePropertyWrapper.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/HttpRequestMessagePropertyWrapper.cs @@ -54,21 +54,18 @@ public static WebHeaderCollection GetHeaders(object httpRequestMessageProperty) var constructor = type.GetConstructor(Type.EmptyTypes) ?? throw new NotSupportedException("HttpRequestMessageProperty public parameterless constructor was not found"); - var headersProp = type.GetProperty("Headers", BindingFlags.Public | BindingFlags.Instance, null, typeof(WebHeaderCollection), Array.Empty(), null) + var headersProp = type.GetProperty("Headers", BindingFlags.Public | BindingFlags.Instance, null, typeof(WebHeaderCollection), [], null) ?? throw new NotSupportedException("HttpRequestMessageProperty.Headers property not found"); - var nameProp = type.GetProperty("Name", BindingFlags.Public | BindingFlags.Static, null, typeof(string), Array.Empty(), null) + var nameProp = type.GetProperty("Name", BindingFlags.Public | BindingFlags.Static, null, typeof(string), [], null) ?? throw new NotSupportedException("HttpRequestMessageProperty.Name property not found"); - if (nameProp.GetValue(null) is not string name) - { - throw new NotSupportedException("HttpRequestMessageProperty.Name property was null"); - } - - return new ReflectedInfo( - type: type, - name: name, - headersFetcher: new PropertyFetcher("Headers")); + return nameProp.GetValue(null) is not string name + ? throw new NotSupportedException("HttpRequestMessageProperty.Name property was null") + : new ReflectedInfo( + type: type, + name: name, + headersFetcher: new PropertyFetcher("Headers")); } catch (Exception ex) { diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/RequestTelemetryStateTracker.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/RequestTelemetryStateTracker.cs index 282f0c91e0..db8f5f1402 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/RequestTelemetryStateTracker.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/RequestTelemetryStateTracker.cs @@ -7,8 +7,8 @@ namespace OpenTelemetry.Instrumentation.Wcf.Implementation; internal static class RequestTelemetryStateTracker { - private static readonly Dictionary OutstandingRequestStates = new Dictionary(); - private static readonly SortedSet TimeoutQueue = new SortedSet(); + private static readonly Dictionary OutstandingRequestStates = []; + private static readonly SortedSet TimeoutQueue = []; private static readonly object Sync = new(); private static readonly Timer Timer = new(OnTimer); private static long currentTimerDueAt = Timeout.Infinite; @@ -61,10 +61,7 @@ private static void OnTimer(object? state) { if (entryTimeoutProps.ExpiresAt <= now) { - if (timedOutEntries == null) - { - timedOutEntries = new List>(); - } + timedOutEntries ??= []; timedOutEntries.Add(new(entryTimeoutProps, OutstandingRequestStates[entryTimeoutProps.MessageId])); } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/TelemetryDispatchMessageInspector.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/TelemetryDispatchMessageInspector.cs index 653ef55ad3..9c2c981b05 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/TelemetryDispatchMessageInspector.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/TelemetryDispatchMessageInspector.cs @@ -49,7 +49,7 @@ internal TelemetryDispatchMessageInspector(IDictionary a var textMapPropagator = Propagators.DefaultTextMapPropagator; var ctx = textMapPropagator.Extract(default, request, WcfInstrumentationActivitySource.MessageHeaderValuesGetter); - Activity? activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( + var activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( WcfInstrumentationActivitySource.IncomingRequestActivityName, ActivityKind.Server, ctx.ActivityContext); @@ -71,7 +71,7 @@ internal TelemetryDispatchMessageInspector(IDictionary a { activity.SetTag(WcfInstrumentationConstants.RpcSystemTag, WcfInstrumentationConstants.WcfSystemValue); - if (!this.actionMappings.TryGetValue(action, out ActionMetadata actionMetadata)) + if (!this.actionMappings.TryGetValue(action, out var actionMetadata)) { actionMetadata = new ActionMetadata( contractName: null, @@ -105,7 +105,7 @@ internal TelemetryDispatchMessageInspector(IDictionary a } } - if (!(textMapPropagator is TraceContextPropagator)) + if (textMapPropagator is not TraceContextPropagator) { Baggage.Current = ctx.Baggage; } @@ -139,7 +139,7 @@ public void BeforeSendReply(ref Message reply, object? correlationState) activity.Stop(); - if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator)) + if (Propagators.DefaultTextMapPropagator is not TraceContextPropagator) { Baggage.Current = default; } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs index 28655258e3..507b5c1f64 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs @@ -9,7 +9,7 @@ namespace OpenTelemetry.Instrumentation.Wcf.Implementation; [EventSource(Name = "OpenTelemetry-Instrumentation-Wcf")] internal sealed class WcfInstrumentationEventSource : EventSource { - public static readonly WcfInstrumentationEventSource Log = new WcfInstrumentationEventSource(); + public static readonly WcfInstrumentationEventSource Log = new(); [NonEvent] public void RequestFilterException(Exception ex) diff --git a/src/Shared/PropertyFetcher.cs b/src/Shared/PropertyFetcher.cs index 7dbcda9afa..1ed16cc7bb 100644 --- a/src/Shared/PropertyFetcher.cs +++ b/src/Shared/PropertyFetcher.cs @@ -34,12 +34,9 @@ public PropertyFetcher(string propertyName) /// Property fetched. public T Fetch(object obj) { - if (!this.TryFetch(obj, out T value)) - { - throw new ArgumentException("Supplied object was null or did not match the expected type.", nameof(obj)); - } - - return value; + return !this.TryFetch(obj, out var value) + ? throw new ArgumentException("Supplied object was null or did not match the expected type.", nameof(obj)) + : value; } /// @@ -59,12 +56,7 @@ public bool TryFetch(object obj, out T value) if (this.innerFetcher == null) { var type = obj.GetType().GetTypeInfo(); - var property = type.DeclaredProperties.FirstOrDefault(p => string.Equals(p.Name, this.propertyName, StringComparison.OrdinalIgnoreCase)); - if (property == null) - { - property = type.GetProperty(this.propertyName); - } - + var property = type.DeclaredProperties.FirstOrDefault(p => string.Equals(p.Name, this.propertyName, StringComparison.OrdinalIgnoreCase)) ?? type.GetProperty(this.propertyName); this.innerFetcher = PropertyFetch.FetcherForProperty(property); } @@ -107,7 +99,11 @@ private sealed class TypedPropertyFetch : Pr public TypedPropertyFetch(PropertyInfo property) { +#if NET + this.propertyFetch = property.GetMethod.CreateDelegate>(); +#else this.propertyFetch = (Func)property.GetMethod.CreateDelegate(typeof(Func)); +#endif } public override bool TryFetch(object obj, out T value) diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs index 63113a4f8d..dea64b6447 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/AspNetParentSpanCorrectorTests.netfx.cs @@ -31,7 +31,7 @@ public void IncomingRequestHeadersAreOverwrittenWithAspNetParent() var context = new FakeHttpContext(); var method = typeof(AspNetParentSpanCorrector).GetMethod("OnRequestStarted", BindingFlags.Static | BindingFlags.NonPublic); - method.Invoke(null, new object[] { aspNetActivity, context }); + method.Invoke(null, [aspNetActivity, context]); var headerVal = context.Request.Headers["traceparent"]; Assert.Contains(aspNetActivity.TraceId.ToString(), headerVal); @@ -43,12 +43,12 @@ public void IncomingRequestHeadersAreOverwrittenWithAspNetParent() private class FakeHttpContext { - public FakeRequest Request { get; } = new FakeRequest(); + public FakeRequest Request { get; } = new(); } private class FakeRequest { - public NameValueCollection Headers { get; } = new NameValueCollection(); + public NameValueCollection Headers { get; } = []; } } #endif diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs index d04fce5f0b..d255648c91 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForHttpTests.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using System.Net; using System.ServiceModel; -using System.ServiceModel.Channels; using OpenTelemetry.Instrumentation.Wcf.Tests.Tools; using OpenTelemetry.Trace; using Xunit; @@ -19,7 +18,7 @@ public class TelemetryBindingElementForHttpTests : IDisposable public TelemetryBindingElementForHttpTests() { - Random random = new Random(); + var random = new Random(); var retryCount = 5; HttpListener? createdListener = null; while (retryCount > 0) @@ -57,7 +56,9 @@ public TelemetryBindingElementForHttpTests() finally { initializationHandle.Dispose(); +#pragma warning disable IDE0059 // Unnecessary assignment of a value initializationHandle = null; +#pragma warning restore IDE0059 // Unnecessary assignment of a value } async void Listener() @@ -72,14 +73,14 @@ async void Listener() var ctx = await ctxTask.ConfigureAwait(false); - using StreamReader reader = new StreamReader(ctx.Request.InputStream); + using var reader = new StreamReader(ctx.Request.InputStream); - string request = reader.ReadToEnd(); + var request = reader.ReadToEnd(); ctx.Response.StatusCode = 200; ctx.Response.ContentType = "text/xml; charset=utf-8"; - using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) + using (var writer = new StreamWriter(ctx.Response.OutputStream)) { if (request.Contains("ExecuteWithEmptyActionName")) { @@ -139,7 +140,7 @@ public async Task OutgoingRequestInstrumentationTest( bool enrichmentException = false, bool emptyOrNullAction = false) { - List stoppedActivities = new List(); + List stoppedActivities = []; var builder = Sdk.CreateTracerProviderBuilder() .AddInMemoryExporter(stoppedActivities); @@ -151,9 +152,9 @@ public async Task OutgoingRequestInstrumentationTest( { if (enrich) { - if (!enrichmentException) - { - options.Enrich = (activity, eventName, message) => + options.Enrich = enrichmentException + ? (_, _, _) => throw new Exception("Error while enriching activity") + : (activity, eventName, _) => { switch (eventName) { @@ -163,25 +164,22 @@ public async Task OutgoingRequestInstrumentationTest( case WcfEnrichEventNames.AfterReceiveReply: activity.SetTag("client.afterreceivereply", WcfEnrichEventNames.AfterReceiveReply); break; + default: + break; } }; - } - else - { - options.Enrich = (activity, eventName, message) => throw new Exception("Error while enriching activity"); - } } - options.OutgoingRequestFilter = (Message m) => !filter; + options.OutgoingRequestFilter = _ => !filter; options.SuppressDownstreamInstrumentation = suppressDownstreamInstrumentation; options.SetSoapMessageVersion = includeVersion; }) .AddDownstreamInstrumentation(); } - TracerProvider? tracerProvider = builder.Build(); + var tracerProvider = builder.Build(); - ServiceClient client = new ServiceClient( + var client = new ServiceClient( new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); try @@ -243,7 +241,7 @@ await client.ExecuteAsync( Assert.NotEmpty(stoppedActivities); Assert.Single(stoppedActivities); - Activity activity = stoppedActivities[0]; + var activity = stoppedActivities[0]; if (emptyOrNullAction) { @@ -298,21 +296,19 @@ public async Task ActivitiesHaveCorrectParentTest() .AddWcfInstrumentation() .Build(); - ServiceClient client = new ServiceClient( + var client = new ServiceClient( new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); try { client.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); - using (var parentActivity = testSource.StartActivity("ParentActivity")) - { - client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); - client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); - var firstAsyncCall = client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); - await client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); - await firstAsyncCall; - } + using var parentActivity = testSource.StartActivity("ParentActivity"); + client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); + client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); + var firstAsyncCall = client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); + await client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); + await firstAsyncCall; } finally { @@ -351,10 +347,10 @@ public async Task ErrorsAreHandledProperlyTest() .AddWcfInstrumentation() .Build(); - ServiceClient client = new ServiceClient( + var client = new ServiceClient( new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); - ServiceClient clientBadUrl = new ServiceClient( + var clientBadUrl = new ServiceClient( new BasicHttpBinding(BasicHttpSecurityMode.None), new EndpointAddress(new Uri("http://localhost:1/Service"))); try @@ -362,13 +358,11 @@ public async Task ErrorsAreHandledProperlyTest() client.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); clientBadUrl.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); - using (var parentActivity = testSource.StartActivity("ParentActivity")) - { - Assert.ThrowsAny(() => client.ErrorSynchronous()); - await Assert.ThrowsAnyAsync(client.ErrorAsync); - Assert.ThrowsAny(() => clientBadUrl.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!"))); - await Assert.ThrowsAnyAsync(() => clientBadUrl.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!"))); - } + using var parentActivity = testSource.StartActivity("ParentActivity"); + Assert.ThrowsAny(client.ErrorSynchronous); + await Assert.ThrowsAnyAsync(client.ErrorAsync); + Assert.ThrowsAny(() => clientBadUrl.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!"))); + await Assert.ThrowsAnyAsync(() => clientBadUrl.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!"))); } finally { diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs index c4fd1d6fed..88088c0ef1 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryBindingElementForTcpTests.netfx.cs @@ -7,7 +7,6 @@ using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; -using System.ServiceModel.Channels; using System.ServiceModel.Security; using OpenTelemetry.Instrumentation.Wcf.Tests.Tools; using OpenTelemetry.Trace; @@ -53,7 +52,7 @@ public async Task OutgoingRequestInstrumentationTest( bool enrichmentException = false, bool emptyOrNullAction = false) { - List stoppedActivities = new List(); + List stoppedActivities = []; var builder = Sdk.CreateTracerProviderBuilder() .AddInMemoryExporter(stoppedActivities); @@ -65,9 +64,9 @@ public async Task OutgoingRequestInstrumentationTest( { if (enrich) { - if (!enrichmentException) - { - options.Enrich = (activity, eventName, message) => + options.Enrich = enrichmentException + ? (_, _, _) => throw new Exception("Error while enriching activity") + : (activity, eventName, _) => { switch (eventName) { @@ -77,23 +76,20 @@ public async Task OutgoingRequestInstrumentationTest( case WcfEnrichEventNames.AfterReceiveReply: activity.SetTag("client.afterreceivereply", WcfEnrichEventNames.AfterReceiveReply); break; + default: + break; } }; - } - else - { - options.Enrich = (activity, eventName, message) => throw new Exception("Error while enriching activity"); - } } - options.OutgoingRequestFilter = (Message m) => !filter; + options.OutgoingRequestFilter = _ => !filter; options.SuppressDownstreamInstrumentation = suppressDownstreamInstrumentation; options.SetSoapMessageVersion = includeVersion; }) .AddDownstreamInstrumentation(); } - TracerProvider? tracerProvider = builder.Build(); + var tracerProvider = builder.Build(); var client = new ServiceClient( new NetTcpBinding(SecurityMode.None), @@ -157,7 +153,7 @@ await client.ExecuteAsync( Assert.NotEmpty(stoppedActivities); Assert.Single(stoppedActivities); - Activity activity = stoppedActivities[0]; + var activity = stoppedActivities[0]; if (emptyOrNullAction) { @@ -220,14 +216,12 @@ public async Task ActivitiesHaveCorrectParentTest() { client.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); - using (var parentActivity = testSource.StartActivity("ParentActivity")) - { - client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); - client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); - var firstAsyncCall = client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); - await client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); - await firstAsyncCall; - } + using var parentActivity = testSource.StartActivity("ParentActivity"); + client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); + client.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!")); + var firstAsyncCall = client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); + await client.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!")); + await firstAsyncCall; } finally { @@ -277,21 +271,19 @@ public async Task ErrorsAreHandledProperlyTest() clientBadUrl.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); clientBadUrl2.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); - using (var parentActivity = testSource.StartActivity("ParentActivity")) - { - Assert.ThrowsAny(() => client.ErrorSynchronous()); - - // weird corner case: if an async call is made as the first hit (before the client is opened) the - // async execution context gets lost somewhere in WCF internals, so we'll explicitly open it first - client2.Open(); - await Assert.ThrowsAnyAsync(client2.ErrorAsync); - Assert.ThrowsAny(() => clientBadUrl.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!"))); - await Assert.ThrowsAnyAsync(() => clientBadUrl2.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!"))); - } + using var parentActivity = testSource.StartActivity("ParentActivity"); + Assert.ThrowsAny(client.ErrorSynchronous); + + // weird corner case: if an async call is made as the first hit (before the client is opened) the + // async execution context gets lost somewhere in WCF internals, so we'll explicitly open it first + client2.Open(); + await Assert.ThrowsAnyAsync(client2.ErrorAsync); + Assert.ThrowsAny(() => clientBadUrl.ExecuteSynchronous(new ServiceRequest(payload: "Hello Open Telemetry!"))); + await Assert.ThrowsAnyAsync(() => clientBadUrl2.ExecuteAsync(new ServiceRequest(payload: "Hello Open Telemetry!"))); } finally { - Action closeClient = client => + static void CloseClient(ServiceClient client) { if (client.State == CommunicationState.Faulted) { @@ -301,11 +293,12 @@ public async Task ErrorsAreHandledProperlyTest() { client.Close(); } - }; - closeClient(client); - closeClient(client2); - closeClient(clientBadUrl); - closeClient(clientBadUrl2); + } + + CloseClient(client); + CloseClient(client2); + CloseClient(clientBadUrl); + CloseClient(clientBadUrl2); tracerProvider?.Shutdown(); tracerProvider?.Dispose(); @@ -330,8 +323,10 @@ public async Task OrphanedTelemetryTimesOut() .AddWcfInstrumentation() .Build(); - var binding = new NetTcpBinding(SecurityMode.None); - binding.SendTimeout = TimeSpan.FromMilliseconds(1000); + var binding = new NetTcpBinding(SecurityMode.None) + { + SendTimeout = TimeSpan.FromMilliseconds(1000), + }; var client = new ServiceClient(binding, new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); try { @@ -378,8 +373,10 @@ public async Task DynamicTimeoutValuesAreRespected() .AddWcfInstrumentation() .Build(); - var binding = new NetTcpBinding(SecurityMode.None); - binding.SendTimeout = TimeSpan.FromMilliseconds(15000); + var binding = new NetTcpBinding(SecurityMode.None) + { + SendTimeout = TimeSpan.FromMilliseconds(15000), + }; var client = new ServiceClient(binding, new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); try { @@ -426,18 +423,20 @@ public void StreamedTransferWithTransportSecurityWithMessageCredentialWorks() // this config combination is unique because it uses an IRequestSessionChannel, // where other NetTcp configs use IDuplexChannel - List stoppedActivities = new List(); + List stoppedActivities = []; var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddInMemoryExporter(stoppedActivities) .AddWcfInstrumentation() .Build(); - var binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential); - binding.TransferMode = TransferMode.Streamed; + var binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential) + { + TransferMode = TransferMode.Streamed, + }; binding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign; binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows; var host = this.CreateServiceHost(binding, LoadCertificate()); - ServiceClient client = new ServiceClient(binding, new EndpointAddress(new Uri(host.BaseAddresses[0], "/Service"))); + var client = new ServiceClient(binding, new EndpointAddress(new Uri(host.BaseAddresses[0], "/Service"))); try { client.ClientCredentials.ClientCertificate.Certificate = LoadCertificate(); @@ -489,7 +488,7 @@ private static X509Certificate2 LoadCertificate() private ServiceHost CreateServiceHost(NetTcpBinding binding, X509Certificate2? cert) { ServiceHost? serviceHost = null; - Random random = new Random(); + var random = new Random(); var retryCount = 5; while (retryCount > 0) { @@ -527,12 +526,7 @@ private ServiceHost CreateServiceHost(NetTcpBinding binding, X509Certificate2? c } } - if (serviceHost == null) - { - throw new InvalidOperationException("ServiceHost could not be started."); - } - - return serviceHost; + return serviceHost ?? throw new InvalidOperationException("ServiceHost could not be started."); } } #endif diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs index aa91e53df6..3ee5ad8c15 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs @@ -18,14 +18,14 @@ public class TelemetryDispatchMessageInspectorForOneWayOperationsTests : IDispos private readonly Uri serviceBaseUri; private readonly ServiceHost serviceHost; - private readonly EventWaitHandle thrownExceptionsHandle = new EventWaitHandle(false, EventResetMode.ManualReset); - private readonly List thrownExceptions = new List(); + private readonly EventWaitHandle thrownExceptionsHandle = new(false, EventResetMode.ManualReset); + private readonly List thrownExceptions = []; public TelemetryDispatchMessageInspectorForOneWayOperationsTests(ITestOutputHelper outputHelper) { this.output = outputHelper; - Random random = new Random(); + var random = new Random(); var retryCount = 5; ServiceHost? createdHost = null; while (retryCount > 0) @@ -42,7 +42,7 @@ public TelemetryDispatchMessageInspectorForOneWayOperationsTests(ITestOutputHelp endpoint.Behaviors.Add(new TelemetryEndpointBehavior()); createdHost.Description.Behaviors.Add( - new ErrorHandlerServiceBehavior(this.thrownExceptionsHandle, ex => this.thrownExceptions.Add(ex))); + new ErrorHandlerServiceBehavior(this.thrownExceptionsHandle, this.thrownExceptions.Add)); createdHost.Open(); @@ -82,20 +82,20 @@ public void Dispose() [Fact] public void IncomingRequestOneWayOperationInstrumentationTest() { - List stoppedActivities = new List(); + List stoppedActivities = []; - using ActivityListener activityListener = new ActivityListener + using var activityListener = new ActivityListener { ShouldListenTo = activitySource => true, - ActivityStopped = activity => stoppedActivities.Add(activity), + ActivityStopped = stoppedActivities.Add, }; ActivitySource.AddActivityListener(activityListener); - TracerProvider? tracerProvider = Sdk.CreateTracerProviderBuilder() + var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddWcfInstrumentation() .Build(); - ServiceClient client = new ServiceClient( + var client = new ServiceClient( new NetTcpBinding(), new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); @@ -127,7 +127,7 @@ public void IncomingRequestOneWayOperationInstrumentationTest() Assert.NotEmpty(stoppedActivities); Assert.Single(stoppedActivities); - Activity activity = stoppedActivities[0]; + var activity = stoppedActivities[0]; Assert.Equal("http://opentelemetry.io/Service/ExecuteWithOneWay", activity.DisplayName); Assert.Equal("ExecuteWithOneWay", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); Assert.DoesNotContain(activity.TagObjects, t => t.Key == WcfInstrumentationConstants.SoapReplyActionTag); diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs index 938032f2a0..2faafc3a29 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs @@ -4,7 +4,6 @@ #if NETFRAMEWORK using System.Diagnostics; using System.ServiceModel; -using System.ServiceModel.Channels; using OpenTelemetry.Trace; using Xunit; using Xunit.Abstractions; @@ -22,7 +21,7 @@ public TelemetryDispatchMessageInspectorTests(ITestOutputHelper outputHelper) { this.output = outputHelper; - Random random = new Random(); + var random = new Random(); var retryCount = 5; ServiceHost? createdHost = null; while (retryCount > 0) @@ -82,15 +81,15 @@ public async Task IncomingRequestInstrumentationTest( bool filter = false, bool includeVersion = false, bool enrich = false, - bool enrichmentExcecption = false, + bool enrichmentException = false, bool emptyOrNullAction = false) { - List stoppedActivities = new List(); + List stoppedActivities = []; - using ActivityListener activityListener = new ActivityListener + using var activityListener = new ActivityListener { ShouldListenTo = activitySource => true, - ActivityStopped = activity => stoppedActivities.Add(activity), + ActivityStopped = stoppedActivities.Add, }; ActivitySource.AddActivityListener(activityListener); @@ -103,44 +102,31 @@ public async Task IncomingRequestInstrumentationTest( { if (enrich) { - if (!enrichmentExcecption) - { - options.Enrich = (activity, eventName, message) => + options.Enrich = enrichmentException + ? (_, _, _) => throw new Exception("Failure whilst enriching activity") + : (activity, eventName, _) => { switch (eventName) { case WcfEnrichEventNames.AfterReceiveRequest: - activity.SetTag( - "server.afterreceiverequest", - WcfEnrichEventNames.AfterReceiveRequest); + activity.SetTag("server.afterreceiverequest", WcfEnrichEventNames.AfterReceiveRequest); break; case WcfEnrichEventNames.BeforeSendReply: - activity.SetTag( - "server.beforesendreply", - WcfEnrichEventNames.BeforeSendReply); + activity.SetTag("server.beforesendreply", WcfEnrichEventNames.BeforeSendReply); + break; + default: break; } }; - } - else - { - options.Enrich = (activity, eventName, message) => - { - throw new Exception("Failure whilst enriching activity"); - }; - } } - options.IncomingRequestFilter = (Message m) => - { - return !filter; - }; + options.IncomingRequestFilter = _ => !filter; options.SetSoapMessageVersion = includeVersion; }) .Build(); } - ServiceClient client = new ServiceClient( + var client = new ServiceClient( new NetTcpBinding(), new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); try @@ -180,7 +166,7 @@ await client.ExecuteAsync( Assert.NotEmpty(stoppedActivities); Assert.Single(stoppedActivities); - Activity activity = stoppedActivities[0]; + var activity = stoppedActivities[0]; if (emptyOrNullAction) { @@ -208,7 +194,7 @@ await client.ExecuteAsync( Assert.Equal("Soap12 (http://www.w3.org/2003/05/soap-envelope) Addressing10 (http://www.w3.org/2005/08/addressing)", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.SoapMessageVersionTag).Value); } - if (enrich && !enrichmentExcecption) + if (enrich && !enrichmentException) { Assert.Equal(WcfEnrichEventNames.AfterReceiveRequest, activity.TagObjects.Single(t => t.Key == "server.afterreceiverequest").Value); Assert.Equal(WcfEnrichEventNames.BeforeSendReply, activity.TagObjects.Single(t => t.Key == "server.beforesendreply").Value); diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs index 3f377702a7..fc5fc7b5c3 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryPropagationTests.netfx.cs @@ -20,7 +20,7 @@ public class TelemetryPropagationTests : IDisposable public TelemetryPropagationTests() { - Random random = new Random(); + var random = new Random(); var retryCount = 5; ServiceHost? createdHost = null; while (retryCount > 0) @@ -101,7 +101,7 @@ public async Task TelemetryContextPropagatesTest( "rest" => new WebHttpBinding(), _ => throw new ArgumentException("Invalid endpoint type", nameof(endpoint)), }; - ServiceClient client = new ServiceClient(binding, new EndpointAddress(new Uri(serviceBase, $"/{endpoint}"))); + var client = new ServiceClient(binding, new EndpointAddress(new Uri(serviceBase, $"/{endpoint}"))); try { client.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationBindingElement.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationBindingElement.cs index 8d52c63e3c..ff6e69dba7 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationBindingElement.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationBindingElement.cs @@ -6,7 +6,9 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools; +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public class DownstreamInstrumentationBindingElement : BindingElement +#pragma warning restore CA1515 // Make class internal, public is needed for WCF { public override BindingElement Clone() { diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannel.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannel.cs index 8ee6338cd2..5b93254776 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannel.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannel.cs @@ -7,10 +7,12 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools; +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public class DownstreamInstrumentationChannel : DispatchProxy +#pragma warning restore CA1515 // Make class internal, public is needed for WCF { public const string DownstreamInstrumentationSourceName = "DownstreamInstrumentationSource"; - private static readonly ActivitySource DownstreamInstrumentationSource = new ActivitySource(DownstreamInstrumentationSourceName); + private static readonly ActivitySource DownstreamInstrumentationSource = new(DownstreamInstrumentationSourceName); private static bool failNextReceive; private object? Target { get; set; } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannelFactory.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannelFactory.cs index 41870371b9..78769adea8 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannelFactory.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationChannelFactory.cs @@ -6,7 +6,9 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools; +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public class DownstreamInstrumentationChannelFactory : DispatchProxy +#pragma warning restore CA1515 // Make class internal, public is needed for WCF where TChannel : notnull { public IChannelFactory? Target { get; set; } @@ -14,11 +16,6 @@ public class DownstreamInstrumentationChannelFactory : DispatchProxy protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) { var returnValue = targetMethod!.Invoke(this.Target, args); - if (targetMethod.Name == nameof(IChannelFactory.CreateChannel)) - { - return DownstreamInstrumentationChannel.Create((TChannel)returnValue!); - } - - return returnValue; + return targetMethod.Name == nameof(IChannelFactory.CreateChannel) ? DownstreamInstrumentationChannel.Create((TChannel)returnValue!) : returnValue; } } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationEndpointBehavior.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationEndpointBehavior.cs index 20c8417239..24b11c21cc 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationEndpointBehavior.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationEndpointBehavior.cs @@ -7,7 +7,9 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools; +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public class DownstreamInstrumentationEndpointBehavior : IEndpointBehavior +#pragma warning restore CA1515 // Make class internal, public is needed for WCF { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationExtensions.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationExtensions.cs index 958af96d95..278364b4f0 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationExtensions.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/DownstreamInstrumentationExtensions.cs @@ -5,7 +5,7 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools; -public static class DownstreamInstrumentationExtensions +internal static class DownstreamInstrumentationExtensions { public static TracerProviderBuilder AddDownstreamInstrumentation(this TracerProviderBuilder builder) => builder.AddSource(DownstreamInstrumentationChannel.DownstreamInstrumentationSourceName); diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs index a9d787c45f..cddb6acbe6 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs @@ -27,7 +27,7 @@ public void AddBindingParameters(ServiceDescription serviceDescription, ServiceH public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { - foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers) + foreach (var dispatcher in serviceHostBase.ChannelDispatchers.Cast()) { dispatcher.ErrorHandlers.Add(new ErrorHandler(this.handle, this.action)); } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs index b9c1cef19a..8eaec2db43 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs @@ -6,7 +6,9 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests; [ServiceContract(Namespace = "http://opentelemetry.io/", Name = "Service", SessionMode = SessionMode.Allowed)] +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public interface IServiceContract +#pragma warning restore CA1515 // Make class internal, public is needed for WCF { [OperationContract] Task ExecuteAsync(ServiceRequest request); diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs index b67b98caef..c3f2056b4c 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs @@ -6,7 +6,9 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests; +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public class ServiceClient : ClientBase, IServiceContract +#pragma warning restore CA1515 // Make class internal, public is needed for WCF { public ServiceClient(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs index c41027301b..1329f1b654 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs @@ -6,7 +6,9 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests; [DataContract] +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public class ServiceRequest +#pragma warning restore CA1515 // Make class internal, public is needed for WCF { public ServiceRequest(string payload) { diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs index d26066edc6..8dfef624bd 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs @@ -6,7 +6,9 @@ namespace OpenTelemetry.Instrumentation.Wcf.Tests; [DataContract] +#pragma warning disable CA1515 // Make class internal, public is needed for WCF public class ServiceResponse +#pragma warning restore CA1515 // Make class internal, public is needed for WCF { public ServiceResponse(string payload) {