From 2c57ff08c0398bf408a97113ad598985d4ad9635 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Thu, 4 Aug 2022 18:55:16 +0200 Subject: [PATCH] [WCF.Intrumentation] Filescoped namespace (#561) --- .../Implementation/ActionMetadata.cs | 11 +- .../WcfInstrumentationActivitySource.cs | 55 ++- .../WcfInstrumentationConstants.cs | 33 +- .../WcfInstrumentationEventSource.cs | 105 +++-- .../TelemetryClientMessageInspector.cs | 239 +++++----- .../TelemetryContractBehaviorAttribute.cs | 64 ++- .../TelemetryDispatchMessageInspector.cs | 196 ++++---- .../TelemetryEndpointBehavior.cs | 108 +++-- ...lemetryEndpointBehaviorExtensionElement.cs | 26 +- .../TelemetryServiceBehavior.cs | 49 +- ...elemetryServiceBehaviorExtensionElement.cs | 26 +- .../TracerProviderBuilderExtensions.cs | 41 +- .../WcfEnrichEventNames.cs | 43 +- .../WcfInstrumentationOptions.cs | 75 ++-- .../TelemetryClientMessageInspectorTests.cs | 417 +++++++++--------- ...InspectorForOneWayOperationsTests.netfx.cs | 193 ++++---- ...etryDispatchMessageInspectorTests.netfx.cs | 339 +++++++------- .../Tools/ErrorHandler.netfx.cs | 45 +- .../ErrorHandlerServiceBehavior.netfx.cs | 43 +- .../WCF/IServiceContract.cs | 21 +- .../WCF/Service.netfx.cs | 55 +-- .../WCF/ServiceClient.cs | 25 +- .../WCF/ServiceRequest.cs | 13 +- .../WCF/ServiceResponse.cs | 13 +- 24 files changed, 1110 insertions(+), 1125 deletions(-) diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ActionMetadata.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ActionMetadata.cs index 39c32c9c71..e4bc90e78b 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ActionMetadata.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/ActionMetadata.cs @@ -14,12 +14,11 @@ // limitations under the License. // -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +internal sealed class ActionMetadata { - internal sealed class ActionMetadata - { - public string ContractName { get; set; } + public string ContractName { get; set; } - public string OperationName { get; set; } - } + public string OperationName { get; set; } } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationActivitySource.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationActivitySource.cs index cd96f3bd5a..c90e363450 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationActivitySource.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationActivitySource.cs @@ -19,33 +19,32 @@ using System.Diagnostics; using System.ServiceModel.Channels; -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// WCF instrumentation. +/// +internal static class WcfInstrumentationActivitySource { - /// - /// WCF instrumentation. - /// - internal static class WcfInstrumentationActivitySource - { - public const string ActivitySourceName = "OpenTelemetry.WCF"; - public const string IncomingRequestActivityName = ActivitySourceName + ".IncomingRequest"; - public const string OutgoingRequestActivityName = ActivitySourceName + ".OutgoingRequest"; - - private static readonly Version Version = typeof(WcfInstrumentationActivitySource).Assembly.GetName().Version; - - public static ActivitySource ActivitySource { get; } = new ActivitySource(ActivitySourceName, Version.ToString()); - - public static Func> MessageHeaderValuesGetter { get; } - = (request, name) => - { - var headerIndex = request.Headers.FindHeader(name, "https://www.w3.org/TR/trace-context/"); - return headerIndex < 0 - ? null - : new[] { request.Headers.GetHeader(headerIndex) }; - }; - - public static Action MessageHeaderValueSetter { get; } - = (request, name, value) => request.Headers.Add(MessageHeader.CreateHeader(name, "https://www.w3.org/TR/trace-context/", value, false)); - - public static WcfInstrumentationOptions Options { get; set; } - } + public const string ActivitySourceName = "OpenTelemetry.WCF"; + public const string IncomingRequestActivityName = ActivitySourceName + ".IncomingRequest"; + public const string OutgoingRequestActivityName = ActivitySourceName + ".OutgoingRequest"; + + private static readonly Version Version = typeof(WcfInstrumentationActivitySource).Assembly.GetName().Version; + + public static ActivitySource ActivitySource { get; } = new ActivitySource(ActivitySourceName, Version.ToString()); + + public static Func> MessageHeaderValuesGetter { get; } + = (request, name) => + { + var headerIndex = request.Headers.FindHeader(name, "https://www.w3.org/TR/trace-context/"); + return headerIndex < 0 + ? null + : new[] { request.Headers.GetHeader(headerIndex) }; + }; + + public static Action MessageHeaderValueSetter { get; } + = (request, name, value) => request.Headers.Add(MessageHeader.CreateHeader(name, "https://www.w3.org/TR/trace-context/", value, false)); + + public static WcfInstrumentationOptions Options { get; set; } } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationConstants.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationConstants.cs index bff21a0caf..e3f934bb5e 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationConstants.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationConstants.cs @@ -14,23 +14,22 @@ // limitations under the License. // -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +internal static class WcfInstrumentationConstants { - internal static class WcfInstrumentationConstants - { - public const string RpcSystemTag = "rpc.system"; - public const string RpcServiceTag = "rpc.service"; - public const string RpcMethodTag = "rpc.method"; - public const string NetHostNameTag = "net.host.name"; - public const string NetHostPortTag = "net.host.port"; - public const string NetPeerNameTag = "net.peer.name"; - public const string NetPeerPortTag = "net.peer.port"; - public const string SoapMessageVersionTag = "soap.message_version"; - public const string SoapReplyActionTag = "soap.reply_action"; - public const string SoapViaTag = "soap.via"; - public const string WcfChannelSchemeTag = "wcf.channel.scheme"; - public const string WcfChannelPathTag = "wcf.channel.path"; + public const string RpcSystemTag = "rpc.system"; + public const string RpcServiceTag = "rpc.service"; + public const string RpcMethodTag = "rpc.method"; + public const string NetHostNameTag = "net.host.name"; + public const string NetHostPortTag = "net.host.port"; + public const string NetPeerNameTag = "net.peer.name"; + public const string NetPeerPortTag = "net.peer.port"; + public const string SoapMessageVersionTag = "soap.message_version"; + public const string SoapReplyActionTag = "soap.reply_action"; + public const string SoapViaTag = "soap.via"; + public const string WcfChannelSchemeTag = "wcf.channel.scheme"; + public const string WcfChannelPathTag = "wcf.channel.path"; - public const string WcfSystemValue = "wcf"; - } + public const string WcfSystemValue = "wcf"; } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs index bab42d7e92..fa73b497c1 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/Implementation/WcfInstrumentationEventSource.cs @@ -19,73 +19,72 @@ using System.Globalization; using System.Threading; -namespace OpenTelemetry.Instrumentation.Wcf.Implementation +namespace OpenTelemetry.Instrumentation.Wcf.Implementation; + +[EventSource(Name = "OpenTelemetry-Instrumentation-Wcf")] +internal sealed class WcfInstrumentationEventSource : EventSource { - [EventSource(Name = "OpenTelemetry-Instrumentation-Wcf")] - internal sealed class WcfInstrumentationEventSource : EventSource - { - public static readonly WcfInstrumentationEventSource Log = new WcfInstrumentationEventSource(); + public static readonly WcfInstrumentationEventSource Log = new WcfInstrumentationEventSource(); - [NonEvent] - public void RequestFilterException(Exception ex) + [NonEvent] + public void RequestFilterException(Exception ex) + { + if (this.IsEnabled(EventLevel.Error, (EventKeywords)(-1))) { - if (this.IsEnabled(EventLevel.Error, (EventKeywords)(-1))) - { - this.RequestFilterException(ToInvariantString(ex)); - } + this.RequestFilterException(ToInvariantString(ex)); } + } - [Event(EventIds.RequestIsFilteredOut, Message = "Request is filtered out.", Level = EventLevel.Verbose)] - public void RequestIsFilteredOut() - { - this.WriteEvent(EventIds.RequestIsFilteredOut); - } + [Event(EventIds.RequestIsFilteredOut, Message = "Request is filtered out.", Level = EventLevel.Verbose)] + public void RequestIsFilteredOut() + { + this.WriteEvent(EventIds.RequestIsFilteredOut); + } - [Event(EventIds.RequestFilterException, Message = "InstrumentationFilter threw exception. Request will not be collected. Exception {0}.", Level = EventLevel.Error)] - public void RequestFilterException(string exception) - { - this.WriteEvent(EventIds.RequestFilterException, exception); - } + [Event(EventIds.RequestFilterException, Message = "InstrumentationFilter threw exception. Request will not be collected. Exception {0}.", Level = EventLevel.Error)] + public void RequestFilterException(string exception) + { + this.WriteEvent(EventIds.RequestFilterException, exception); + } - [NonEvent] - public void EnrichmentException(Exception exception) + [NonEvent] + public void EnrichmentException(Exception exception) + { + if (this.IsEnabled(EventLevel.Error, (EventKeywords)(-1))) { - if (this.IsEnabled(EventLevel.Error, (EventKeywords)(-1))) - { - this.EnrichmentException(ToInvariantString(exception)); - } + this.EnrichmentException(ToInvariantString(exception)); } + } - [Event(EventIds.EnrichmentException, Message = "Enrichment threw exception. Exception {0}.", Level = EventLevel.Error)] - public void EnrichmentException(string exception) - { - this.WriteEvent(EventIds.EnrichmentException, exception); - } + [Event(EventIds.EnrichmentException, Message = "Enrichment threw exception. Exception {0}.", Level = EventLevel.Error)] + public void EnrichmentException(string exception) + { + this.WriteEvent(EventIds.EnrichmentException, exception); + } - /// - /// Returns a culture-independent string representation of the given object, - /// appropriate for diagnostics tracing. - /// - private static string ToInvariantString(Exception exception) - { - var originalUICulture = Thread.CurrentThread.CurrentUICulture; + /// + /// Returns a culture-independent string representation of the given object, + /// appropriate for diagnostics tracing. + /// + private static string ToInvariantString(Exception exception) + { + var originalUICulture = Thread.CurrentThread.CurrentUICulture; - try - { - Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; - return exception.ToString(); - } - finally - { - Thread.CurrentThread.CurrentUICulture = originalUICulture; - } + try + { + Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; + return exception.ToString(); } - - private class EventIds + finally { - public const int RequestIsFilteredOut = 1; - public const int RequestFilterException = 2; - public const int EnrichmentException = 3; + Thread.CurrentThread.CurrentUICulture = originalUICulture; } } + + private class EventIds + { + public const int RequestIsFilteredOut = 1; + public const int RequestFilterException = 2; + public const int EnrichmentException = 3; + } } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryClientMessageInspector.cs b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryClientMessageInspector.cs index 41d00e779a..2830e78c91 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryClientMessageInspector.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryClientMessageInspector.cs @@ -25,163 +25,162 @@ using OpenTelemetry.Internal; using OpenTelemetry.Trace; -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// An implementation which adds telemetry to outgoing requests. +/// +public class TelemetryClientMessageInspector : IClientMessageInspector { - /// - /// An implementation which adds telemetry to outgoing requests. - /// - public class TelemetryClientMessageInspector : IClientMessageInspector - { - private readonly IDictionary actionMappings; + private readonly IDictionary actionMappings; - internal TelemetryClientMessageInspector(IDictionary actionMappings) - { - Guard.ThrowIfNull(actionMappings); + internal TelemetryClientMessageInspector(IDictionary actionMappings) + { + Guard.ThrowIfNull(actionMappings); - this.actionMappings = actionMappings; - } + this.actionMappings = actionMappings; + } - /// - public object BeforeSendRequest(ref Message request, IClientChannel channel) + /// + public object BeforeSendRequest(ref Message request, IClientChannel channel) + { + try { - try - { - if (WcfInstrumentationActivitySource.Options == null || WcfInstrumentationActivitySource.Options.OutgoingRequestFilter?.Invoke(request) == false) - { - WcfInstrumentationEventSource.Log.RequestIsFilteredOut(); - return new State - { - SuppressionScope = this.SuppressDownstreamInstrumentation(), - }; - } - } - catch (Exception ex) + if (WcfInstrumentationActivitySource.Options == null || WcfInstrumentationActivitySource.Options.OutgoingRequestFilter?.Invoke(request) == false) { - WcfInstrumentationEventSource.Log.RequestFilterException(ex); + WcfInstrumentationEventSource.Log.RequestIsFilteredOut(); return new State { SuppressionScope = this.SuppressDownstreamInstrumentation(), }; } + } + catch (Exception ex) + { + WcfInstrumentationEventSource.Log.RequestFilterException(ex); + return new State + { + SuppressionScope = this.SuppressDownstreamInstrumentation(), + }; + } - Activity activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( - WcfInstrumentationActivitySource.OutgoingRequestActivityName, - ActivityKind.Client); - IDisposable suppressionScope = this.SuppressDownstreamInstrumentation(); + Activity activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( + WcfInstrumentationActivitySource.OutgoingRequestActivityName, + ActivityKind.Client); + IDisposable suppressionScope = this.SuppressDownstreamInstrumentation(); - if (activity != null) + if (activity != null) + { + string action; + if (!string.IsNullOrEmpty(request.Headers.Action)) { - string action; - if (!string.IsNullOrEmpty(request.Headers.Action)) - { - action = request.Headers.Action; - activity.DisplayName = action; - } - else - { - action = string.Empty; - } + action = request.Headers.Action; + activity.DisplayName = action; + } + else + { + action = string.Empty; + } - Propagators.DefaultTextMapPropagator.Inject( - new PropagationContext(activity.Context, Baggage.Current), - request, - WcfInstrumentationActivitySource.MessageHeaderValueSetter); + Propagators.DefaultTextMapPropagator.Inject( + new PropagationContext(activity.Context, Baggage.Current), + request, + WcfInstrumentationActivitySource.MessageHeaderValueSetter); - if (activity.IsAllDataRequested) - { - activity.SetTag(WcfInstrumentationConstants.RpcSystemTag, WcfInstrumentationConstants.WcfSystemValue); + if (activity.IsAllDataRequested) + { + activity.SetTag(WcfInstrumentationConstants.RpcSystemTag, WcfInstrumentationConstants.WcfSystemValue); - if (!this.actionMappings.TryGetValue(action, out ActionMetadata actionMetadata)) + if (!this.actionMappings.TryGetValue(action, out ActionMetadata actionMetadata)) + { + actionMetadata = new ActionMetadata { - actionMetadata = new ActionMetadata - { - ContractName = null, - OperationName = action, - }; - } + ContractName = null, + OperationName = action, + }; + } - activity.SetTag(WcfInstrumentationConstants.RpcServiceTag, actionMetadata.ContractName); - activity.SetTag(WcfInstrumentationConstants.RpcMethodTag, actionMetadata.OperationName); + activity.SetTag(WcfInstrumentationConstants.RpcServiceTag, actionMetadata.ContractName); + activity.SetTag(WcfInstrumentationConstants.RpcMethodTag, actionMetadata.OperationName); - if (WcfInstrumentationActivitySource.Options.SetSoapMessageVersion) - { - activity.SetTag(WcfInstrumentationConstants.SoapMessageVersionTag, request.Version.ToString()); - } + if (WcfInstrumentationActivitySource.Options.SetSoapMessageVersion) + { + activity.SetTag(WcfInstrumentationConstants.SoapMessageVersionTag, request.Version.ToString()); + } - var remoteAddressUri = request.Headers.To ?? channel.RemoteAddress?.Uri; - if (remoteAddressUri != null) - { - activity.SetTag(WcfInstrumentationConstants.NetPeerNameTag, remoteAddressUri.Host); - activity.SetTag(WcfInstrumentationConstants.NetPeerPortTag, remoteAddressUri.Port); - activity.SetTag(WcfInstrumentationConstants.WcfChannelSchemeTag, remoteAddressUri.Scheme); - activity.SetTag(WcfInstrumentationConstants.WcfChannelPathTag, remoteAddressUri.LocalPath); - } + var remoteAddressUri = request.Headers.To ?? channel.RemoteAddress?.Uri; + if (remoteAddressUri != null) + { + activity.SetTag(WcfInstrumentationConstants.NetPeerNameTag, remoteAddressUri.Host); + activity.SetTag(WcfInstrumentationConstants.NetPeerPortTag, remoteAddressUri.Port); + activity.SetTag(WcfInstrumentationConstants.WcfChannelSchemeTag, remoteAddressUri.Scheme); + activity.SetTag(WcfInstrumentationConstants.WcfChannelPathTag, remoteAddressUri.LocalPath); + } - if (request.Properties.Via != null) - { - activity.SetTag(WcfInstrumentationConstants.SoapViaTag, request.Properties.Via.ToString()); - } + if (request.Properties.Via != null) + { + activity.SetTag(WcfInstrumentationConstants.SoapViaTag, request.Properties.Via.ToString()); + } - try - { - WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.BeforeSendRequest, request); - } - catch (Exception ex) - { - WcfInstrumentationEventSource.Log.EnrichmentException(ex); - } + try + { + WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.BeforeSendRequest, request); + } + catch (Exception ex) + { + WcfInstrumentationEventSource.Log.EnrichmentException(ex); } } - - return new State - { - SuppressionScope = suppressionScope, - Activity = activity, - }; } - /// - public void AfterReceiveReply(ref Message reply, object correlationState) + return new State { - State state = (State)correlationState; + SuppressionScope = suppressionScope, + Activity = activity, + }; + } + + /// + public void AfterReceiveReply(ref Message reply, object correlationState) + { + State state = (State)correlationState; - state.SuppressionScope?.Dispose(); + state.SuppressionScope?.Dispose(); - if (state.Activity is Activity activity) + if (state.Activity is Activity activity) + { + if (activity.IsAllDataRequested) { - if (activity.IsAllDataRequested) + if (reply.IsFault) { - if (reply.IsFault) - { - activity.SetStatus(Status.Error); - } - - activity.SetTag(WcfInstrumentationConstants.SoapReplyActionTag, reply.Headers.Action); - try - { - WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.AfterReceiveReply, reply); - } - catch (Exception ex) - { - WcfInstrumentationEventSource.Log.EnrichmentException(ex); - } + activity.SetStatus(Status.Error); } - activity.Stop(); + activity.SetTag(WcfInstrumentationConstants.SoapReplyActionTag, reply.Headers.Action); + try + { + WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.AfterReceiveReply, reply); + } + catch (Exception ex) + { + WcfInstrumentationEventSource.Log.EnrichmentException(ex); + } } - } - private IDisposable SuppressDownstreamInstrumentation() - { - return WcfInstrumentationActivitySource.Options?.SuppressDownstreamInstrumentation ?? false - ? SuppressInstrumentationScope.Begin() - : null; + activity.Stop(); } + } - private class State - { - public IDisposable SuppressionScope; - public Activity Activity; - } + private IDisposable SuppressDownstreamInstrumentation() + { + return WcfInstrumentationActivitySource.Options?.SuppressDownstreamInstrumentation ?? false + ? SuppressInstrumentationScope.Begin() + : null; + } + + private class State + { + public IDisposable SuppressionScope; + public Activity Activity; } } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryContractBehaviorAttribute.cs b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryContractBehaviorAttribute.cs index 0c6bed3ee6..522dfc9ec3 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryContractBehaviorAttribute.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryContractBehaviorAttribute.cs @@ -19,47 +19,45 @@ using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; -namespace OpenTelemetry.Instrumentation.Wcf -{ +namespace OpenTelemetry.Instrumentation.Wcf; #if NETFRAMEWORK - /// - /// An to add the - /// to service operations - /// and to client operations - /// programmatically. - /// +/// +/// An to add the +/// to service operations +/// and to client operations +/// programmatically. +/// #else - /// - /// An to add the - /// to client operations - /// programmatically. - /// +/// +/// An to add the +/// to client operations +/// programmatically. +/// #endif - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false, AllowMultiple = false)] - public sealed class TelemetryContractBehaviorAttribute : Attribute, IContractBehavior +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false, AllowMultiple = false)] +public sealed class TelemetryContractBehaviorAttribute : Attribute, IContractBehavior +{ + /// + public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { - /// - public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) - { - } + } - /// - public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime) - { - TelemetryEndpointBehavior.ApplyClientBehaviorToClientRuntime(clientRuntime); - } + /// + public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime) + { + TelemetryEndpointBehavior.ApplyClientBehaviorToClientRuntime(clientRuntime); + } - /// - public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime) - { + /// + public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime) + { #if NETFRAMEWORK - TelemetryEndpointBehavior.ApplyDispatchBehaviorToEndpoint(dispatchRuntime.EndpointDispatcher); + TelemetryEndpointBehavior.ApplyDispatchBehaviorToEndpoint(dispatchRuntime.EndpointDispatcher); #endif - } + } - /// - public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint) - { - } + /// + public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint) + { } } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryDispatchMessageInspector.cs b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryDispatchMessageInspector.cs index 151292ed6c..26e109eaa9 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryDispatchMessageInspector.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryDispatchMessageInspector.cs @@ -26,140 +26,140 @@ using OpenTelemetry.Internal; using OpenTelemetry.Trace; -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// An implementation which adds telemetry to incoming requests. +/// +public class TelemetryDispatchMessageInspector : IDispatchMessageInspector { - /// - /// An implementation which adds telemetry to incoming requests. - /// - public class TelemetryDispatchMessageInspector : IDispatchMessageInspector + private readonly IDictionary actionMappings; + + internal TelemetryDispatchMessageInspector(IDictionary actionMappings) { - private readonly IDictionary actionMappings; + Guard.ThrowIfNull(actionMappings); - internal TelemetryDispatchMessageInspector(IDictionary actionMappings) - { - Guard.ThrowIfNull(actionMappings); + this.actionMappings = actionMappings; + } - this.actionMappings = actionMappings; + /// + public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) + { + try + { + if (WcfInstrumentationActivitySource.Options == null || WcfInstrumentationActivitySource.Options.IncomingRequestFilter?.Invoke(request) == false) + { + WcfInstrumentationEventSource.Log.RequestIsFilteredOut(); + return null; + } + } + catch (Exception ex) + { + WcfInstrumentationEventSource.Log.RequestFilterException(ex); + return null; } - /// - public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) + var textMapPropagator = Propagators.DefaultTextMapPropagator; + var ctx = textMapPropagator.Extract(default, request, WcfInstrumentationActivitySource.MessageHeaderValuesGetter); + + Activity activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( + WcfInstrumentationActivitySource.IncomingRequestActivityName, + ActivityKind.Server, + ctx.ActivityContext); + + if (activity != null) { - try + string action; + if (!string.IsNullOrEmpty(request.Headers.Action)) { - if (WcfInstrumentationActivitySource.Options == null || WcfInstrumentationActivitySource.Options.IncomingRequestFilter?.Invoke(request) == false) - { - WcfInstrumentationEventSource.Log.RequestIsFilteredOut(); - return null; - } + action = request.Headers.Action; + activity.DisplayName = action; } - catch (Exception ex) + else { - WcfInstrumentationEventSource.Log.RequestFilterException(ex); - return null; + action = string.Empty; } - var textMapPropagator = Propagators.DefaultTextMapPropagator; - var ctx = textMapPropagator.Extract(default, request, WcfInstrumentationActivitySource.MessageHeaderValuesGetter); - - Activity activity = WcfInstrumentationActivitySource.ActivitySource.StartActivity( - WcfInstrumentationActivitySource.IncomingRequestActivityName, - ActivityKind.Server, - ctx.ActivityContext); - - if (activity != null) + if (activity.IsAllDataRequested) { - string action; - if (!string.IsNullOrEmpty(request.Headers.Action)) - { - action = request.Headers.Action; - activity.DisplayName = action; - } - else - { - action = string.Empty; - } + activity.SetTag(WcfInstrumentationConstants.RpcSystemTag, WcfInstrumentationConstants.WcfSystemValue); - if (activity.IsAllDataRequested) + if (!this.actionMappings.TryGetValue(action, out ActionMetadata actionMetadata)) { - activity.SetTag(WcfInstrumentationConstants.RpcSystemTag, WcfInstrumentationConstants.WcfSystemValue); - - if (!this.actionMappings.TryGetValue(action, out ActionMetadata actionMetadata)) + actionMetadata = new ActionMetadata { - actionMetadata = new ActionMetadata - { - ContractName = null, - OperationName = action, - }; - } - - activity.SetTag(WcfInstrumentationConstants.RpcServiceTag, actionMetadata.ContractName); - activity.SetTag(WcfInstrumentationConstants.RpcMethodTag, actionMetadata.OperationName); + ContractName = null, + OperationName = action, + }; + } - if (WcfInstrumentationActivitySource.Options.SetSoapMessageVersion) - { - activity.SetTag(WcfInstrumentationConstants.SoapMessageVersionTag, request.Version.ToString()); - } + activity.SetTag(WcfInstrumentationConstants.RpcServiceTag, actionMetadata.ContractName); + activity.SetTag(WcfInstrumentationConstants.RpcMethodTag, actionMetadata.OperationName); - var localAddressUri = channel.LocalAddress?.Uri; - if (localAddressUri != null) - { - activity.SetTag(WcfInstrumentationConstants.NetHostNameTag, localAddressUri.Host); - activity.SetTag(WcfInstrumentationConstants.NetHostPortTag, localAddressUri.Port); - activity.SetTag(WcfInstrumentationConstants.WcfChannelSchemeTag, localAddressUri.Scheme); - activity.SetTag(WcfInstrumentationConstants.WcfChannelPathTag, localAddressUri.LocalPath); - } + if (WcfInstrumentationActivitySource.Options.SetSoapMessageVersion) + { + activity.SetTag(WcfInstrumentationConstants.SoapMessageVersionTag, request.Version.ToString()); + } - try - { - WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.AfterReceiveRequest, request); - } - catch (Exception ex) - { - WcfInstrumentationEventSource.Log.EnrichmentException(ex); - } + var localAddressUri = channel.LocalAddress?.Uri; + if (localAddressUri != null) + { + activity.SetTag(WcfInstrumentationConstants.NetHostNameTag, localAddressUri.Host); + activity.SetTag(WcfInstrumentationConstants.NetHostPortTag, localAddressUri.Port); + activity.SetTag(WcfInstrumentationConstants.WcfChannelSchemeTag, localAddressUri.Scheme); + activity.SetTag(WcfInstrumentationConstants.WcfChannelPathTag, localAddressUri.LocalPath); } - if (!(textMapPropagator is TraceContextPropagator)) + try { - Baggage.Current = ctx.Baggage; + WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.AfterReceiveRequest, request); + } + catch (Exception ex) + { + WcfInstrumentationEventSource.Log.EnrichmentException(ex); } } - return activity; + if (!(textMapPropagator is TraceContextPropagator)) + { + Baggage.Current = ctx.Baggage; + } } - /// - public void BeforeSendReply(ref Message reply, object correlationState) + return activity; + } + + /// + public void BeforeSendReply(ref Message reply, object correlationState) + { + if (correlationState is Activity activity) { - if (correlationState is Activity activity) + if (activity.IsAllDataRequested && reply != null) { - if (activity.IsAllDataRequested && reply != null) + if (reply.IsFault) { - if (reply.IsFault) - { - activity.SetStatus(Status.Error); - } - - activity.SetTag(WcfInstrumentationConstants.SoapReplyActionTag, reply.Headers.Action); - try - { - WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.BeforeSendReply, reply); - } - catch (Exception ex) - { - WcfInstrumentationEventSource.Log.EnrichmentException(ex); - } + activity.SetStatus(Status.Error); } - activity.Stop(); - - if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator)) + activity.SetTag(WcfInstrumentationConstants.SoapReplyActionTag, reply.Headers.Action); + try + { + WcfInstrumentationActivitySource.Options.Enrich?.Invoke(activity, WcfEnrichEventNames.BeforeSendReply, reply); + } + catch (Exception ex) { - Baggage.Current = default; + WcfInstrumentationEventSource.Log.EnrichmentException(ex); } } + + activity.Stop(); + + if (!(Propagators.DefaultTextMapPropagator is TraceContextPropagator)) + { + Baggage.Current = default; + } } } } + #endif diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehavior.cs b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehavior.cs index 06e4498282..73417ff793 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehavior.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehavior.cs @@ -20,78 +20,76 @@ using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; -namespace OpenTelemetry.Instrumentation.Wcf -{ +namespace OpenTelemetry.Instrumentation.Wcf; #if NETFRAMEWORK - /// - /// An implementation which adds the to client endpoints and the - /// to service endpoints. - /// +/// +/// An implementation which adds the to client endpoints and the +/// to service endpoints. +/// #else - /// - /// An implementation which adds the to client endpoints. - /// +/// +/// An implementation which adds the to client endpoints. +/// #endif - public class TelemetryEndpointBehavior : IEndpointBehavior +public class TelemetryEndpointBehavior : IEndpointBehavior +{ + /// + public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { - /// - public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) - { - } + } - /// - public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) - { - ApplyClientBehaviorToClientRuntime(clientRuntime); - } + /// + public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) + { + ApplyClientBehaviorToClientRuntime(clientRuntime); + } - /// - public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) - { + /// + public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) + { #if NETFRAMEWORK - ApplyDispatchBehaviorToEndpoint(endpointDispatcher); + ApplyDispatchBehaviorToEndpoint(endpointDispatcher); #endif - } + } - /// - public void Validate(ServiceEndpoint endpoint) - { - } + /// + public void Validate(ServiceEndpoint endpoint) + { + } - internal static void ApplyClientBehaviorToClientRuntime(ClientRuntime clientRuntime) - { - var actionMappings = new Dictionary(StringComparer.OrdinalIgnoreCase); + internal static void ApplyClientBehaviorToClientRuntime(ClientRuntime clientRuntime) + { + var actionMappings = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var clientOperation in clientRuntime.ClientOperations) + foreach (var clientOperation in clientRuntime.ClientOperations) + { + actionMappings[clientOperation.Action] = new ActionMetadata { - actionMappings[clientOperation.Action] = new ActionMetadata - { - ContractName = $"{clientRuntime.ContractNamespace}{clientRuntime.ContractName}", - OperationName = clientOperation.Name, - }; - } - - clientRuntime.ClientMessageInspectors.Add(new TelemetryClientMessageInspector(actionMappings)); + ContractName = $"{clientRuntime.ContractNamespace}{clientRuntime.ContractName}", + OperationName = clientOperation.Name, + }; } + clientRuntime.ClientMessageInspectors.Add(new TelemetryClientMessageInspector(actionMappings)); + } + #if NETFRAMEWORK - internal static void ApplyDispatchBehaviorToEndpoint(EndpointDispatcher endpointDispatcher) - { - var actionMappings = new Dictionary(StringComparer.OrdinalIgnoreCase); + internal static void ApplyDispatchBehaviorToEndpoint(EndpointDispatcher endpointDispatcher) + { + var actionMappings = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var dispatchOperation in endpointDispatcher.DispatchRuntime.Operations) + foreach (var dispatchOperation in endpointDispatcher.DispatchRuntime.Operations) + { + actionMappings[dispatchOperation.Action] = new ActionMetadata { - actionMappings[dispatchOperation.Action] = new ActionMetadata - { - ContractName = $"{endpointDispatcher.ContractNamespace}{endpointDispatcher.ContractName}", - OperationName = dispatchOperation.Name, - }; - } - - endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new TelemetryDispatchMessageInspector(actionMappings)); + ContractName = $"{endpointDispatcher.ContractNamespace}{endpointDispatcher.ContractName}", + OperationName = dispatchOperation.Name, + }; } -#endif + + endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new TelemetryDispatchMessageInspector(actionMappings)); } +#endif } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehaviorExtensionElement.cs b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehaviorExtensionElement.cs index c02c03f98d..c2bd78c1a0 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehaviorExtensionElement.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryEndpointBehaviorExtensionElement.cs @@ -18,21 +18,21 @@ using System; using System.ServiceModel.Configuration; -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// A for registering on a service endpoint through configuration. +/// +public class TelemetryEndpointBehaviorExtensionElement : BehaviorExtensionElement { - /// - /// A for registering on a service endpoint through configuration. - /// - public class TelemetryEndpointBehaviorExtensionElement : BehaviorExtensionElement - { - /// - public override Type BehaviorType => typeof(TelemetryEndpointBehavior); + /// + public override Type BehaviorType => typeof(TelemetryEndpointBehavior); - /// - protected override object CreateBehavior() - { - return new TelemetryEndpointBehavior(); - } + /// + protected override object CreateBehavior() + { + return new TelemetryEndpointBehavior(); } } + #endif diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehavior.cs b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehavior.cs index d616800688..c9cb943025 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehavior.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehavior.cs @@ -14,43 +14,40 @@ // limitations under the License. // -#pragma warning disable IDE0005 // Using directive is unnecessary. +#if NETFRAMEWORK using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; -#pragma warning restore IDE0005 // Using directive is unnecessary. -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// An implementation to add the +/// to service operations. +/// +public class TelemetryServiceBehavior : IServiceBehavior { -#if NETFRAMEWORK - /// - /// An implementation to add the - /// to service operations. - /// - public class TelemetryServiceBehavior : IServiceBehavior + /// + public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { - /// - public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) - { - } + } - /// - public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + /// + public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + { + foreach (var channelDispatcherBase in serviceHostBase.ChannelDispatchers) { - foreach (var channelDispatcherBase in serviceHostBase.ChannelDispatchers) + var channelDispatcher = (ChannelDispatcher)channelDispatcherBase; + foreach (var endpointDispatcher in channelDispatcher.Endpoints) { - var channelDispatcher = (ChannelDispatcher)channelDispatcherBase; - foreach (var endpointDispatcher in channelDispatcher.Endpoints) - { - TelemetryEndpointBehavior.ApplyDispatchBehaviorToEndpoint(endpointDispatcher); - } + TelemetryEndpointBehavior.ApplyDispatchBehaviorToEndpoint(endpointDispatcher); } } + } - /// - public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) - { - } + /// + public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + { } -#endif } +#endif diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehaviorExtensionElement.cs b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehaviorExtensionElement.cs index a1df56f16d..90fb6794af 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehaviorExtensionElement.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TelemetryServiceBehaviorExtensionElement.cs @@ -18,21 +18,21 @@ using System; using System.ServiceModel.Configuration; -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// A for registering on a service through configuration. +/// +public class TelemetryServiceBehaviorExtensionElement : BehaviorExtensionElement { - /// - /// A for registering on a service through configuration. - /// - public class TelemetryServiceBehaviorExtensionElement : BehaviorExtensionElement - { - /// - public override Type BehaviorType => typeof(TelemetryServiceBehavior); + /// + public override Type BehaviorType => typeof(TelemetryServiceBehavior); - /// - protected override object CreateBehavior() - { - return new TelemetryServiceBehavior(); - } + /// + protected override object CreateBehavior() + { + return new TelemetryServiceBehavior(); } } + #endif diff --git a/src/OpenTelemetry.Instrumentation.Wcf/TracerProviderBuilderExtensions.cs b/src/OpenTelemetry.Instrumentation.Wcf/TracerProviderBuilderExtensions.cs index 2d99b44919..fbfad45d92 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/TracerProviderBuilderExtensions.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/TracerProviderBuilderExtensions.cs @@ -18,34 +18,33 @@ using OpenTelemetry.Instrumentation.Wcf; using OpenTelemetry.Internal; -namespace OpenTelemetry.Trace +namespace OpenTelemetry.Trace; + +/// +/// Extension methods to simplify registering of dependency instrumentation. +/// +public static class TracerProviderBuilderExtensions { /// - /// Extension methods to simplify registering of dependency instrumentation. + /// Enables the outgoing requests automatic data collection for WCF. /// - public static class TracerProviderBuilderExtensions + /// being configured. + /// Wcf configuration options. + /// The instance of to chain the calls. + public static TracerProviderBuilder AddWcfInstrumentation(this TracerProviderBuilder builder, Action configure = null) { - /// - /// Enables the outgoing requests automatic data collection for WCF. - /// - /// being configured. - /// Wcf configuration options. - /// The instance of to chain the calls. - public static TracerProviderBuilder AddWcfInstrumentation(this TracerProviderBuilder builder, Action configure = null) - { - Guard.ThrowIfNull(builder); + Guard.ThrowIfNull(builder); - if (WcfInstrumentationActivitySource.Options != null) - { - throw new NotSupportedException("WCF instrumentation has already been registered and doesn't support multiple registrations."); - } + if (WcfInstrumentationActivitySource.Options != null) + { + throw new NotSupportedException("WCF instrumentation has already been registered and doesn't support multiple registrations."); + } - var options = new WcfInstrumentationOptions(); - configure?.Invoke(options); + var options = new WcfInstrumentationOptions(); + configure?.Invoke(options); - WcfInstrumentationActivitySource.Options = options; + WcfInstrumentationActivitySource.Options = options; - return builder.AddSource(WcfInstrumentationActivitySource.ActivitySourceName); - } + return builder.AddSource(WcfInstrumentationActivitySource.ActivitySourceName); } } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/WcfEnrichEventNames.cs b/src/OpenTelemetry.Instrumentation.Wcf/WcfEnrichEventNames.cs index 87044abdee..02b1dbe0e9 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/WcfEnrichEventNames.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/WcfEnrichEventNames.cs @@ -14,33 +14,32 @@ // limitations under the License. // -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// Constants used for event names when enriching an activity. +/// +public static class WcfEnrichEventNames { +#if NETFRAMEWORK /// - /// Constants used for event names when enriching an activity. + /// WCF service activity, event happens before WCF service method is invoked. /// - public static class WcfEnrichEventNames - { -#if NETFRAMEWORK - /// - /// WCF service activity, event happens before WCF service method is invoked. - /// - public const string AfterReceiveRequest = "AfterReceiveRequest"; + public const string AfterReceiveRequest = "AfterReceiveRequest"; - /// - /// WCF service activity, event happens after the WCF service method is invoked but before the reply is sent back to the client. - /// - public const string BeforeSendReply = "BeforeSendReply"; + /// + /// WCF service activity, event happens after the WCF service method is invoked but before the reply is sent back to the client. + /// + public const string BeforeSendReply = "BeforeSendReply"; #endif - /// - /// WCF client activity, event happens before the request is sent across the wire. - /// - public const string BeforeSendRequest = "BeforeSendRequest"; + /// + /// WCF client activity, event happens before the request is sent across the wire. + /// + public const string BeforeSendRequest = "BeforeSendRequest"; - /// - /// WCF client activity, event happens after a reply from the WCF service is received. - /// - public const string AfterReceiveReply = "AfterReceiveReply"; - } + /// + /// WCF client activity, event happens after a reply from the WCF service is received. + /// + public const string AfterReceiveReply = "AfterReceiveReply"; } diff --git a/src/OpenTelemetry.Instrumentation.Wcf/WcfInstrumentationOptions.cs b/src/OpenTelemetry.Instrumentation.Wcf/WcfInstrumentationOptions.cs index cd2c65dc93..83cca12ecd 100644 --- a/src/OpenTelemetry.Instrumentation.Wcf/WcfInstrumentationOptions.cs +++ b/src/OpenTelemetry.Instrumentation.Wcf/WcfInstrumentationOptions.cs @@ -18,49 +18,48 @@ using System.Diagnostics; using System.ServiceModel.Channels; -namespace OpenTelemetry.Instrumentation.Wcf +namespace OpenTelemetry.Instrumentation.Wcf; + +/// +/// Options for WCF instrumentation. +/// +public class WcfInstrumentationOptions { /// - /// Options for WCF instrumentation. + /// Gets or sets an action to enrich an Activity. /// - public class WcfInstrumentationOptions - { - /// - /// Gets or sets an action to enrich an Activity. - /// - /// - /// : the activity being enriched. - /// string: the name of the event. Will be one of the constants in . - /// - /// object: the raw from which additional information can be extracted to enrich the activity. - /// - /// - public Action Enrich { get; set; } + /// + /// : the activity being enriched. + /// string: the name of the event. Will be one of the constants in . + /// + /// object: the raw from which additional information can be extracted to enrich the activity. + /// + /// + public Action Enrich { get; set; } - /// - /// Gets or sets a Filter function to filter instrumentation for requests on a per request basis. - /// The Filter gets the Message, and should return a boolean. - /// If Filter returns true, the request is collected. - /// If Filter returns false or throw exception, the request is filtered out. - /// - public Func IncomingRequestFilter { get; set; } + /// + /// Gets or sets a Filter function to filter instrumentation for requests on a per request basis. + /// The Filter gets the Message, and should return a boolean. + /// If Filter returns true, the request is collected. + /// If Filter returns false or throw exception, the request is filtered out. + /// + public Func IncomingRequestFilter { get; set; } - /// - /// Gets or sets a Filter function to filter instrumentation for requests on a per request basis. - /// The Filter gets the Message, and should return a boolean. - /// If Filter returns true, the request is collected. - /// If Filter returns false or throw exception, the request is filtered out. - /// - public Func OutgoingRequestFilter { get; set; } + /// + /// Gets or sets a Filter function to filter instrumentation for requests on a per request basis. + /// The Filter gets the Message, and should return a boolean. + /// If Filter returns true, the request is collected. + /// If Filter returns false or throw exception, the request is filtered out. + /// + public Func OutgoingRequestFilter { get; set; } - /// - /// Gets or sets a value indicating whether down stream instrumentation (HttpClient) is suppressed (disabled). Default value: True. - /// - public bool SuppressDownstreamInstrumentation { get; set; } = true; + /// + /// Gets or sets a value indicating whether down stream instrumentation (HttpClient) is suppressed (disabled). Default value: True. + /// + public bool SuppressDownstreamInstrumentation { get; set; } = true; - /// - /// Gets or sets a value indicating whether or not the SOAP message version should be added as the tag. Default value: False. - /// - public bool SetSoapMessageVersion { get; set; } - } + /// + /// Gets or sets a value indicating whether or not the SOAP message version should be added as the tag. Default value: False. + /// + public bool SetSoapMessageVersion { get; set; } } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryClientMessageInspectorTests.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryClientMessageInspectorTests.cs index 55fabbfc42..5e535f3f57 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryClientMessageInspectorTests.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryClientMessageInspectorTests.cs @@ -27,281 +27,280 @@ using OpenTelemetry.Trace; using Xunit; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +[Collection("WCF")] +public class TelemetryClientMessageInspectorTests : IDisposable { - [Collection("WCF")] - public class TelemetryClientMessageInspectorTests : IDisposable - { - private readonly Uri serviceBaseUri; - private readonly HttpListener listener; - private readonly EventWaitHandle initializationHandle; + private readonly Uri serviceBaseUri; + private readonly HttpListener listener; + private readonly EventWaitHandle initializationHandle; - public TelemetryClientMessageInspectorTests() + public TelemetryClientMessageInspectorTests() + { + Random random = new Random(); + var retryCount = 5; + while (retryCount > 0) { - Random random = new Random(); - var retryCount = 5; - while (retryCount > 0) + try { - try - { - this.serviceBaseUri = new Uri($"http://localhost:{random.Next(2000, 5000)}/"); + this.serviceBaseUri = new Uri($"http://localhost:{random.Next(2000, 5000)}/"); - this.listener = new HttpListener(); - this.listener.Prefixes.Add(this.serviceBaseUri.OriginalString); - this.listener.Start(); - break; - } - catch - { - this.listener.Stop(); - this.listener = null; - retryCount--; - } + this.listener = new HttpListener(); + this.listener.Prefixes.Add(this.serviceBaseUri.OriginalString); + this.listener.Start(); + break; } - - if (this.listener == null) + catch { - throw new InvalidOperationException("HttpListener could not be started."); + this.listener.Stop(); + this.listener = null; + retryCount--; } + } - this.initializationHandle = new EventWaitHandle(false, EventResetMode.ManualReset); - try - { - Listener(); + if (this.listener == null) + { + throw new InvalidOperationException("HttpListener could not be started."); + } - this.initializationHandle.WaitOne(); - } - finally - { - this.initializationHandle.Dispose(); - this.initializationHandle = null; - } + this.initializationHandle = new EventWaitHandle(false, EventResetMode.ManualReset); + try + { + Listener(); + + this.initializationHandle.WaitOne(); + } + finally + { + this.initializationHandle.Dispose(); + this.initializationHandle = null; + } - async void Listener() + async void Listener() + { + while (true) { - while (true) + try { - try - { - var ctxTask = this.listener.GetContextAsync(); + var ctxTask = this.listener.GetContextAsync(); - this.initializationHandle?.Set(); + this.initializationHandle?.Set(); - var ctx = await ctxTask.ConfigureAwait(false); + var ctx = await ctxTask.ConfigureAwait(false); - using StreamReader reader = new StreamReader(ctx.Request.InputStream); + using StreamReader reader = new StreamReader(ctx.Request.InputStream); - string request = reader.ReadToEnd(); + string request = reader.ReadToEnd(); - ctx.Response.StatusCode = 200; - ctx.Response.ContentType = "text/xml; charset=utf-8"; + ctx.Response.StatusCode = 200; + ctx.Response.ContentType = "text/xml; charset=utf-8"; - using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) + using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) + { + if (request.Contains("ExecuteWithEmptyActionName")) { - if (request.Contains("ExecuteWithEmptyActionName")) - { - writer.Write(@"RSP: Hello Open Telemetry!"); - } - else - { - writer.Write(@"RSP: Hello Open Telemetry!"); - } + writer.Write(@"RSP: Hello Open Telemetry!"); } - - ctx.Response.Close(); - } - catch (Exception ex) - { - if (ex is ObjectDisposedException - || (ex is HttpListenerException httpEx && httpEx.ErrorCode == 995)) + else { - // Listener was closed before we got into GetContextAsync or - // Listener was closed while we were in GetContextAsync. - break; + writer.Write(@"RSP: Hello Open Telemetry!"); } + } - throw; + ctx.Response.Close(); + } + catch (Exception ex) + { + if (ex is ObjectDisposedException + || (ex is HttpListenerException httpEx && httpEx.ErrorCode == 995)) + { + // Listener was closed before we got into GetContextAsync or + // Listener was closed while we were in GetContextAsync. + break; } + + throw; } } } + } - public void Dispose() - { - this.listener?.Stop(); - } + public void Dispose() + { + this.listener?.Stop(); + } - [Theory] - [InlineData(true, false)] - [InlineData(true, true)] - [InlineData(true, false, false)] - [InlineData(false)] - [InlineData(true, false, true, true)] - [InlineData(true, false, true, true, true)] - [InlineData(true, false, true, true, true, true)] - [InlineData(true, false, true, true, true, true, true)] - public async Task OutgoingRequestInstrumentationTest( - bool instrument, - bool filter = false, - bool suppressDownstreamInstrumentation = true, - bool includeVersion = false, - bool enrich = false, - bool enrichmentException = false, - bool emptyOrNullAction = false) - { + [Theory] + [InlineData(true, false)] + [InlineData(true, true)] + [InlineData(true, false, false)] + [InlineData(false)] + [InlineData(true, false, true, true)] + [InlineData(true, false, true, true, true)] + [InlineData(true, false, true, true, true, true)] + [InlineData(true, false, true, true, true, true, true)] + public async Task OutgoingRequestInstrumentationTest( + bool instrument, + bool filter = false, + bool suppressDownstreamInstrumentation = true, + bool includeVersion = false, + bool enrich = false, + bool enrichmentException = false, + bool emptyOrNullAction = false) + { #if NETFRAMEWORK - const string OutgoingHttpOperationName = "OpenTelemetry.HttpWebRequest.HttpRequestOut"; + const string OutgoingHttpOperationName = "OpenTelemetry.HttpWebRequest.HttpRequestOut"; #else - const string OutgoingHttpOperationName = "System.Net.Http.HttpRequestOut"; + const string OutgoingHttpOperationName = "System.Net.Http.HttpRequestOut"; #endif - List stoppedActivities = new List(); + List stoppedActivities = new List(); - var builder = Sdk.CreateTracerProviderBuilder() - .AddInMemoryExporter(stoppedActivities); + var builder = Sdk.CreateTracerProviderBuilder() + .AddInMemoryExporter(stoppedActivities); - if (instrument) - { - builder - .AddWcfInstrumentation(options => + if (instrument) + { + builder + .AddWcfInstrumentation(options => + { + if (enrich) { - if (enrich) + if (!enrichmentException) { - if (!enrichmentException) + options.Enrich = (activity, eventName, message) => { - options.Enrich = (activity, eventName, message) => + switch (eventName) { - switch (eventName) - { - case WcfEnrichEventNames.BeforeSendRequest: - activity.SetTag("client.beforesendrequest", WcfEnrichEventNames.BeforeSendRequest); - break; - case WcfEnrichEventNames.AfterReceiveReply: - activity.SetTag("client.afterreceivereply", WcfEnrichEventNames.AfterReceiveReply); - break; - } - }; - } - else - { - options.Enrich = (activity, eventName, message) => throw new Exception("Error while enriching activity"); - } + case WcfEnrichEventNames.BeforeSendRequest: + activity.SetTag("client.beforesendrequest", WcfEnrichEventNames.BeforeSendRequest); + break; + case WcfEnrichEventNames.AfterReceiveReply: + activity.SetTag("client.afterreceivereply", WcfEnrichEventNames.AfterReceiveReply); + break; + } + }; + } + else + { + options.Enrich = (activity, eventName, message) => throw new Exception("Error while enriching activity"); } + } - options.OutgoingRequestFilter = (Message m) => !filter; - options.SuppressDownstreamInstrumentation = suppressDownstreamInstrumentation; - options.SetSoapMessageVersion = includeVersion; - }) - .AddHttpClientInstrumentation(); // <- Added to test SuppressDownstreamInstrumentation. - } + options.OutgoingRequestFilter = (Message m) => !filter; + options.SuppressDownstreamInstrumentation = suppressDownstreamInstrumentation; + options.SetSoapMessageVersion = includeVersion; + }) + .AddHttpClientInstrumentation(); // <- Added to test SuppressDownstreamInstrumentation. + } - TracerProvider tracerProvider = builder.Build(); + TracerProvider tracerProvider = builder.Build(); - ServiceClient client = new ServiceClient( - new BasicHttpBinding(BasicHttpSecurityMode.None), - new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); - try - { - client.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); + ServiceClient client = new ServiceClient( + new BasicHttpBinding(BasicHttpSecurityMode.None), + new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); + try + { + client.Endpoint.EndpointBehaviors.Add(new TelemetryEndpointBehavior()); - if (emptyOrNullAction) - { - await client.ExecuteWithEmptyActionNameAsync( - new ServiceRequest - { - Payload = "Hello Open Telemetry!", - }).ConfigureAwait(false); - } - else - { - await client.ExecuteAsync( - new ServiceRequest - { - Payload = "Hello Open Telemetry!", - }).ConfigureAwait(false); - } + if (emptyOrNullAction) + { + await client.ExecuteWithEmptyActionNameAsync( + new ServiceRequest + { + Payload = "Hello Open Telemetry!", + }).ConfigureAwait(false); } - finally + else + { + await client.ExecuteAsync( + new ServiceRequest + { + Payload = "Hello Open Telemetry!", + }).ConfigureAwait(false); + } + } + finally + { + if (client.State == CommunicationState.Faulted) { - if (client.State == CommunicationState.Faulted) + client.Abort(); + } + else + { + client.Close(); + } + + tracerProvider.Shutdown(); + tracerProvider.Dispose(); + + WcfInstrumentationActivitySource.Options = null; + } + + if (instrument) + { + if (!suppressDownstreamInstrumentation) + { + Assert.NotEmpty(stoppedActivities); + if (filter) { - client.Abort(); + Assert.Single(stoppedActivities); + Assert.Equal(OutgoingHttpOperationName, stoppedActivities[0].OperationName); } else { - client.Close(); + Assert.Equal(2, stoppedActivities.Count); + Assert.Equal(OutgoingHttpOperationName, stoppedActivities[0].OperationName); + Assert.Equal(WcfInstrumentationActivitySource.OutgoingRequestActivityName, stoppedActivities[1].OperationName); } - - tracerProvider.Shutdown(); - tracerProvider.Dispose(); - - WcfInstrumentationActivitySource.Options = null; } - - if (instrument) + else { - if (!suppressDownstreamInstrumentation) + if (!filter) { Assert.NotEmpty(stoppedActivities); - if (filter) + Assert.Single(stoppedActivities); + + Activity activity = stoppedActivities[0]; + + if (emptyOrNullAction) { - Assert.Single(stoppedActivities); - Assert.Equal(OutgoingHttpOperationName, stoppedActivities[0].OperationName); + Assert.Equal(WcfInstrumentationActivitySource.OutgoingRequestActivityName, activity.DisplayName); + Assert.Equal("ExecuteWithEmptyActionName", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); } else { - Assert.Equal(2, stoppedActivities.Count); - Assert.Equal(OutgoingHttpOperationName, stoppedActivities[0].OperationName); - Assert.Equal(WcfInstrumentationActivitySource.OutgoingRequestActivityName, stoppedActivities[1].OperationName); + Assert.Equal("http://opentelemetry.io/Service/Execute", activity.DisplayName); + Assert.Equal("Execute", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); } - } - else - { - if (!filter) - { - Assert.NotEmpty(stoppedActivities); - Assert.Single(stoppedActivities); - Activity activity = stoppedActivities[0]; - - if (emptyOrNullAction) - { - Assert.Equal(WcfInstrumentationActivitySource.OutgoingRequestActivityName, activity.DisplayName); - Assert.Equal("ExecuteWithEmptyActionName", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); - } - else - { - Assert.Equal("http://opentelemetry.io/Service/Execute", activity.DisplayName); - Assert.Equal("Execute", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); - } - - Assert.Equal(WcfInstrumentationActivitySource.OutgoingRequestActivityName, activity.OperationName); - Assert.Equal(WcfInstrumentationConstants.WcfSystemValue, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcSystemTag).Value); - Assert.Equal("http://opentelemetry.io/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcServiceTag).Value); - Assert.Equal(this.serviceBaseUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetPeerNameTag).Value); - Assert.Equal(this.serviceBaseUri.Port, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetPeerPortTag).Value); - Assert.Equal("http", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelSchemeTag).Value); - Assert.Equal("/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelPathTag).Value); - if (includeVersion) - { - Assert.Equal("Soap11 (http://schemas.xmlsoap.org/soap/envelope/) AddressingNone (http://schemas.microsoft.com/ws/2005/05/addressing/none)", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.SoapMessageVersionTag).Value); - } - - if (enrich && !enrichmentException) - { - Assert.Equal(WcfEnrichEventNames.BeforeSendRequest, activity.TagObjects.Single(t => t.Key == "client.beforesendrequest").Value); - Assert.Equal(WcfEnrichEventNames.AfterReceiveReply, activity.TagObjects.Single(t => t.Key == "client.afterreceivereply").Value); - } + Assert.Equal(WcfInstrumentationActivitySource.OutgoingRequestActivityName, activity.OperationName); + Assert.Equal(WcfInstrumentationConstants.WcfSystemValue, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcSystemTag).Value); + Assert.Equal("http://opentelemetry.io/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcServiceTag).Value); + Assert.Equal(this.serviceBaseUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetPeerNameTag).Value); + Assert.Equal(this.serviceBaseUri.Port, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetPeerPortTag).Value); + Assert.Equal("http", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelSchemeTag).Value); + Assert.Equal("/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelPathTag).Value); + if (includeVersion) + { + Assert.Equal("Soap11 (http://schemas.xmlsoap.org/soap/envelope/) AddressingNone (http://schemas.microsoft.com/ws/2005/05/addressing/none)", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.SoapMessageVersionTag).Value); } - else + + if (enrich && !enrichmentException) { - Assert.Empty(stoppedActivities); + Assert.Equal(WcfEnrichEventNames.BeforeSendRequest, activity.TagObjects.Single(t => t.Key == "client.beforesendrequest").Value); + Assert.Equal(WcfEnrichEventNames.AfterReceiveReply, activity.TagObjects.Single(t => t.Key == "client.afterreceivereply").Value); } } + else + { + Assert.Empty(stoppedActivities); + } } - else - { - Assert.Empty(stoppedActivities); - } + } + else + { + Assert.Empty(stoppedActivities); } } } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs index 127173852e..8dd1ec1bb9 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorForOneWayOperationsTests.netfx.cs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // + #if NETFRAMEWORK using System; using System.Collections.Generic; @@ -25,134 +26,134 @@ using Xunit; using Xunit.Abstractions; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +[Collection("WCF")] +public class TelemetryDispatchMessageInspectorForOneWayOperationsTests : IDisposable { - [Collection("WCF")] - public class TelemetryDispatchMessageInspectorForOneWayOperationsTests : IDisposable - { - private readonly ITestOutputHelper output; - private readonly Uri serviceBaseUri; - private readonly ServiceHost serviceHost; + private readonly ITestOutputHelper output; + 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 EventWaitHandle(false, EventResetMode.ManualReset); + private readonly List thrownExceptions = new List(); - public TelemetryDispatchMessageInspectorForOneWayOperationsTests(ITestOutputHelper outputHelper) - { - this.output = outputHelper; + public TelemetryDispatchMessageInspectorForOneWayOperationsTests(ITestOutputHelper outputHelper) + { + this.output = outputHelper; - Random random = new Random(); - var retryCount = 5; - while (retryCount > 0) + Random random = new Random(); + var retryCount = 5; + while (retryCount > 0) + { + try { - try - { - this.serviceBaseUri = new Uri($"net.tcp://localhost:{random.Next(2000, 5000)}/"); - this.serviceHost = new ServiceHost(new Service(), this.serviceBaseUri); + this.serviceBaseUri = new Uri($"net.tcp://localhost:{random.Next(2000, 5000)}/"); + this.serviceHost = new ServiceHost(new Service(), this.serviceBaseUri); - var endpoint = this.serviceHost.AddServiceEndpoint( - typeof(IServiceContract), - new NetTcpBinding(), - "/Service"); - endpoint.Behaviors.Add(new TelemetryEndpointBehavior()); + var endpoint = this.serviceHost.AddServiceEndpoint( + typeof(IServiceContract), + new NetTcpBinding(), + "/Service"); + endpoint.Behaviors.Add(new TelemetryEndpointBehavior()); - this.serviceHost.Description.Behaviors.Add( - new ErrorHandlerServiceBehavior(this.thrownExceptionsHandle, ex => this.thrownExceptions.Add(ex))); + this.serviceHost.Description.Behaviors.Add( + new ErrorHandlerServiceBehavior(this.thrownExceptionsHandle, ex => this.thrownExceptions.Add(ex))); - this.serviceHost.Open(); + this.serviceHost.Open(); - break; + break; + } + catch (Exception ex) + { + this.output.WriteLine(ex.ToString()); + if (this.serviceHost.State == CommunicationState.Faulted) + { + this.serviceHost.Abort(); } - catch (Exception ex) + else { - this.output.WriteLine(ex.ToString()); - if (this.serviceHost.State == CommunicationState.Faulted) - { - this.serviceHost.Abort(); - } - else - { - this.serviceHost.Close(); - } - - this.serviceHost = null; - retryCount--; + this.serviceHost.Close(); } - } - if (this.serviceHost == null) - { - throw new InvalidOperationException("ServiceHost could not be started."); + this.serviceHost = null; + retryCount--; } } - public void Dispose() + if (this.serviceHost == null) { - this.serviceHost?.Close(); - this.thrownExceptionsHandle?.Dispose(); + throw new InvalidOperationException("ServiceHost could not be started."); } + } - [Fact] - public void IncomingRequestOneWayOperationInstrumentationTest() - { - List stoppedActivities = new List(); + public void Dispose() + { + this.serviceHost?.Close(); + this.thrownExceptionsHandle?.Dispose(); + } - using ActivityListener activityListener = new ActivityListener - { - ShouldListenTo = activitySource => true, - ActivityStopped = activity => stoppedActivities.Add(activity), - }; + [Fact] + public void IncomingRequestOneWayOperationInstrumentationTest() + { + List stoppedActivities = new List(); - ActivitySource.AddActivityListener(activityListener); - TracerProvider tracerProvider = Sdk.CreateTracerProviderBuilder() - .AddWcfInstrumentation() - .Build(); + using ActivityListener activityListener = new ActivityListener + { + ShouldListenTo = activitySource => true, + ActivityStopped = activity => stoppedActivities.Add(activity), + }; - ServiceClient client = new ServiceClient( - new NetTcpBinding(), - new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); + ActivitySource.AddActivityListener(activityListener); + TracerProvider tracerProvider = Sdk.CreateTracerProviderBuilder() + .AddWcfInstrumentation() + .Build(); - try + ServiceClient client = new ServiceClient( + new NetTcpBinding(), + new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); + + try + { + client.ExecuteWithOneWay(new ServiceRequest()); + this.thrownExceptionsHandle.WaitOne(3000); + } + finally + { + if (client.State == CommunicationState.Faulted) { - client.ExecuteWithOneWay(new ServiceRequest()); - this.thrownExceptionsHandle.WaitOne(3000); + client.Abort(); } - finally + else { - if (client.State == CommunicationState.Faulted) - { - client.Abort(); - } - else - { - client.Close(); - } + client.Close(); + } - tracerProvider?.Shutdown(); - tracerProvider?.Dispose(); + tracerProvider?.Shutdown(); + tracerProvider?.Dispose(); - WcfInstrumentationActivitySource.Options = null; - } + WcfInstrumentationActivitySource.Options = null; + } - // Assert - Assert.Empty(this.thrownExceptions); + // Assert + Assert.Empty(this.thrownExceptions); - Assert.NotEmpty(stoppedActivities); - Assert.Single(stoppedActivities); + Assert.NotEmpty(stoppedActivities); + Assert.Single(stoppedActivities); - Activity 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); + Activity 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); - Assert.Equal(WcfInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName); - Assert.Equal(WcfInstrumentationConstants.WcfSystemValue, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcSystemTag).Value); - Assert.Equal("http://opentelemetry.io/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcServiceTag).Value); - Assert.Equal(this.serviceBaseUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostNameTag).Value); - Assert.Equal(this.serviceBaseUri.Port, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostPortTag).Value); - Assert.Equal("net.tcp", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelSchemeTag).Value); - Assert.Equal("/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelPathTag).Value); - } + Assert.Equal(WcfInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName); + Assert.Equal(WcfInstrumentationConstants.WcfSystemValue, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcSystemTag).Value); + Assert.Equal("http://opentelemetry.io/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcServiceTag).Value); + Assert.Equal(this.serviceBaseUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostNameTag).Value); + Assert.Equal(this.serviceBaseUri.Port, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostPortTag).Value); + Assert.Equal("net.tcp", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelSchemeTag).Value); + Assert.Equal("/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelPathTag).Value); } } + #endif diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs index a8e6b58a15..c6776c9f82 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/TelemetryDispatchMessageInspectorTests.netfx.cs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // + #if NETFRAMEWORK using System; using System.Collections.Generic; @@ -25,217 +26,217 @@ using Xunit; using Xunit.Abstractions; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +[Collection("WCF")] +public class TelemetryDispatchMessageInspectorTests : IDisposable { - [Collection("WCF")] - public class TelemetryDispatchMessageInspectorTests : IDisposable + private readonly ITestOutputHelper output; + private readonly Uri serviceBaseUri; + private readonly ServiceHost serviceHost; + + public TelemetryDispatchMessageInspectorTests(ITestOutputHelper outputHelper) { - private readonly ITestOutputHelper output; - private readonly Uri serviceBaseUri; - private readonly ServiceHost serviceHost; + this.output = outputHelper; - public TelemetryDispatchMessageInspectorTests(ITestOutputHelper outputHelper) + Random random = new Random(); + var retryCount = 5; + while (retryCount > 0) { - this.output = outputHelper; - - Random random = new Random(); - var retryCount = 5; - while (retryCount > 0) + try { - try + this.serviceBaseUri = new Uri($"net.tcp://localhost:{random.Next(2000, 5000)}/"); + this.serviceHost = new ServiceHost(new Service(), this.serviceBaseUri); + var endpoint = this.serviceHost.AddServiceEndpoint( + typeof(IServiceContract), + new NetTcpBinding(), + "/Service"); + endpoint.Behaviors.Add(new TelemetryEndpointBehavior()); + this.serviceHost.Open(); + break; + } + catch (Exception ex) + { + this.output.WriteLine(ex.ToString()); + if (this.serviceHost.State == CommunicationState.Faulted) { - this.serviceBaseUri = new Uri($"net.tcp://localhost:{random.Next(2000, 5000)}/"); - this.serviceHost = new ServiceHost(new Service(), this.serviceBaseUri); - var endpoint = this.serviceHost.AddServiceEndpoint( - typeof(IServiceContract), - new NetTcpBinding(), - "/Service"); - endpoint.Behaviors.Add(new TelemetryEndpointBehavior()); - this.serviceHost.Open(); - break; + this.serviceHost.Abort(); } - catch (Exception ex) + else { - this.output.WriteLine(ex.ToString()); - if (this.serviceHost.State == CommunicationState.Faulted) - { - this.serviceHost.Abort(); - } - else - { - this.serviceHost.Close(); - } - - this.serviceHost = null; - retryCount--; + this.serviceHost.Close(); } - } - if (this.serviceHost == null) - { - throw new InvalidOperationException("ServiceHost could not be started."); + this.serviceHost = null; + retryCount--; } } - public void Dispose() + if (this.serviceHost == null) { - this.serviceHost?.Close(); + throw new InvalidOperationException("ServiceHost could not be started."); } + } - [Theory] - [InlineData(true, false)] - [InlineData(true, true)] - [InlineData(false)] - [InlineData(true, false, true)] - [InlineData(true, false, true, true)] - [InlineData(true, false, true, true, true)] - [InlineData(true, false, true, true, true, true)] - public async Task IncomingRequestInstrumentationTest( - bool instrument, - bool filter = false, - bool includeVersion = false, - bool enrich = false, - bool enrichmentExcecption = false, - bool emptyOrNullAction = false) - { - List stoppedActivities = new List(); + public void Dispose() + { + this.serviceHost?.Close(); + } - using ActivityListener activityListener = new ActivityListener - { - ShouldListenTo = activitySource => true, - ActivityStopped = activity => stoppedActivities.Add(activity), - }; + [Theory] + [InlineData(true, false)] + [InlineData(true, true)] + [InlineData(false)] + [InlineData(true, false, true)] + [InlineData(true, false, true, true)] + [InlineData(true, false, true, true, true)] + [InlineData(true, false, true, true, true, true)] + public async Task IncomingRequestInstrumentationTest( + bool instrument, + bool filter = false, + bool includeVersion = false, + bool enrich = false, + bool enrichmentExcecption = false, + bool emptyOrNullAction = false) + { + List stoppedActivities = new List(); - ActivitySource.AddActivityListener(activityListener); + using ActivityListener activityListener = new ActivityListener + { + ShouldListenTo = activitySource => true, + ActivityStopped = activity => stoppedActivities.Add(activity), + }; - TracerProvider tracerProvider = null; - if (instrument) - { - tracerProvider = Sdk.CreateTracerProviderBuilder() - .AddWcfInstrumentation(options => + ActivitySource.AddActivityListener(activityListener); + + TracerProvider tracerProvider = null; + if (instrument) + { + tracerProvider = Sdk.CreateTracerProviderBuilder() + .AddWcfInstrumentation(options => + { + if (enrich) { - if (enrich) + if (!enrichmentExcecption) { - if (!enrichmentExcecption) + options.Enrich = (activity, eventName, message) => { - options.Enrich = (activity, eventName, message) => + switch (eventName) { - switch (eventName) - { - case WcfEnrichEventNames.AfterReceiveRequest: - activity.SetTag( - "server.afterreceiverequest", - WcfEnrichEventNames.AfterReceiveRequest); - break; - case WcfEnrichEventNames.BeforeSendReply: - activity.SetTag( - "server.beforesendreply", - WcfEnrichEventNames.BeforeSendReply); - break; - } - }; - } - else + case WcfEnrichEventNames.AfterReceiveRequest: + activity.SetTag( + "server.afterreceiverequest", + WcfEnrichEventNames.AfterReceiveRequest); + break; + case WcfEnrichEventNames.BeforeSendReply: + activity.SetTag( + "server.beforesendreply", + WcfEnrichEventNames.BeforeSendReply); + break; + } + }; + } + else + { + options.Enrich = (activity, eventName, message) => { - options.Enrich = (activity, eventName, message) => - { - throw new Exception("Failure whilst enriching activity"); - }; - } + throw new Exception("Failure whilst enriching activity"); + }; } + } - options.IncomingRequestFilter = (Message m) => - { - return !filter; - }; - options.SetSoapMessageVersion = includeVersion; - }) - .Build(); - } + options.IncomingRequestFilter = (Message m) => + { + return !filter; + }; + options.SetSoapMessageVersion = includeVersion; + }) + .Build(); + } - ServiceClient client = new ServiceClient( - new NetTcpBinding(), - new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); - try + ServiceClient client = new ServiceClient( + new NetTcpBinding(), + new EndpointAddress(new Uri(this.serviceBaseUri, "/Service"))); + try + { + if (emptyOrNullAction) { - if (emptyOrNullAction) - { - await client.ExecuteWithEmptyActionNameAsync( - new ServiceRequest - { - Payload = "Hello Open Telemetry!", - }).ConfigureAwait(false); - } - else - { - await client.ExecuteAsync( - new ServiceRequest - { - Payload = "Hello Open Telemetry!", - }).ConfigureAwait(false); - } + await client.ExecuteWithEmptyActionNameAsync( + new ServiceRequest + { + Payload = "Hello Open Telemetry!", + }).ConfigureAwait(false); } - finally + else { - if (client.State == CommunicationState.Faulted) - { - client.Abort(); - } - else - { - client.Close(); - } - - tracerProvider?.Shutdown(); - tracerProvider?.Dispose(); - - WcfInstrumentationActivitySource.Options = null; + await client.ExecuteAsync( + new ServiceRequest + { + Payload = "Hello Open Telemetry!", + }).ConfigureAwait(false); } - - if (instrument && !filter) + } + finally + { + if (client.State == CommunicationState.Faulted) + { + client.Abort(); + } + else { - Assert.NotEmpty(stoppedActivities); - Assert.Single(stoppedActivities); + client.Close(); + } - Activity activity = stoppedActivities[0]; + tracerProvider?.Shutdown(); + tracerProvider?.Dispose(); - if (emptyOrNullAction) - { - Assert.Equal(WcfInstrumentationActivitySource.IncomingRequestActivityName, activity.DisplayName); - Assert.Equal("ExecuteWithEmptyActionName", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); - Assert.Equal("http://opentelemetry.io/Service/ExecuteWithEmptyActionNameResponse", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.SoapReplyActionTag).Value); - } - else - { - Assert.Equal("http://opentelemetry.io/Service/Execute", activity.DisplayName); - Assert.Equal("Execute", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); - Assert.Equal("http://opentelemetry.io/Service/ExecuteResponse", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.SoapReplyActionTag).Value); - } + WcfInstrumentationActivitySource.Options = null; + } - Assert.Equal(WcfInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName); - Assert.Equal(WcfInstrumentationConstants.WcfSystemValue, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcSystemTag).Value); - Assert.Equal("http://opentelemetry.io/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcServiceTag).Value); - Assert.Equal(this.serviceBaseUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostNameTag).Value); - Assert.Equal(this.serviceBaseUri.Port, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostPortTag).Value); - Assert.Equal("net.tcp", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelSchemeTag).Value); - Assert.Equal("/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelPathTag).Value); + if (instrument && !filter) + { + Assert.NotEmpty(stoppedActivities); + Assert.Single(stoppedActivities); - if (includeVersion) - { - 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); - } + Activity activity = stoppedActivities[0]; - if (enrich && !enrichmentExcecption) - { - 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); - } + if (emptyOrNullAction) + { + Assert.Equal(WcfInstrumentationActivitySource.IncomingRequestActivityName, activity.DisplayName); + Assert.Equal("ExecuteWithEmptyActionName", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); + Assert.Equal("http://opentelemetry.io/Service/ExecuteWithEmptyActionNameResponse", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.SoapReplyActionTag).Value); } else { - Assert.Empty(stoppedActivities); + Assert.Equal("http://opentelemetry.io/Service/Execute", activity.DisplayName); + Assert.Equal("Execute", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcMethodTag).Value); + Assert.Equal("http://opentelemetry.io/Service/ExecuteResponse", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.SoapReplyActionTag).Value); + } + + Assert.Equal(WcfInstrumentationActivitySource.IncomingRequestActivityName, activity.OperationName); + Assert.Equal(WcfInstrumentationConstants.WcfSystemValue, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcSystemTag).Value); + Assert.Equal("http://opentelemetry.io/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.RpcServiceTag).Value); + Assert.Equal(this.serviceBaseUri.Host, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostNameTag).Value); + Assert.Equal(this.serviceBaseUri.Port, activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.NetHostPortTag).Value); + Assert.Equal("net.tcp", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelSchemeTag).Value); + Assert.Equal("/Service", activity.TagObjects.FirstOrDefault(t => t.Key == WcfInstrumentationConstants.WcfChannelPathTag).Value); + + if (includeVersion) + { + 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) + { + 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); } } + else + { + Assert.Empty(stoppedActivities); + } } } + #endif diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandler.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandler.netfx.cs index bc6f065e7b..afe5f9e201 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandler.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandler.netfx.cs @@ -13,36 +13,37 @@ // See the License for the specific language governing permissions and // limitations under the License. // + #if NETFRAMEWORK using System; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Threading; -namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools +namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools; + +internal class ErrorHandler : IErrorHandler { - internal class ErrorHandler : IErrorHandler + private readonly EventWaitHandle handle; + private readonly Action log; + + public ErrorHandler(EventWaitHandle handle, Action log) + { + this.handle = handle; + this.log = log; + } + + public bool HandleError(Exception error) + { + this.log(error); + this.handle.Set(); + + return true; + } + + public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { - private readonly EventWaitHandle handle; - private readonly Action log; - - public ErrorHandler(EventWaitHandle handle, Action log) - { - this.handle = handle; - this.log = log; - } - - public bool HandleError(Exception error) - { - this.log(error); - this.handle.Set(); - - return true; - } - - public void ProvideFault(Exception error, MessageVersion version, ref Message fault) - { - } } } + #endif diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs index 6332d79162..85af0db661 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/Tools/ErrorHandlerServiceBehavior.netfx.cs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // + #if NETFRAMEWORK using System; using System.Collections.ObjectModel; @@ -22,34 +23,34 @@ using System.ServiceModel.Dispatcher; using System.Threading; -namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools +namespace OpenTelemetry.Instrumentation.Wcf.Tests.Tools; + +internal class ErrorHandlerServiceBehavior : IServiceBehavior { - internal class ErrorHandlerServiceBehavior : IServiceBehavior - { - private readonly EventWaitHandle handle; - private readonly Action action; + private readonly EventWaitHandle handle; + private readonly Action action; - public ErrorHandlerServiceBehavior(EventWaitHandle handle, Action action) - { - this.handle = handle; - this.action = action; - } + public ErrorHandlerServiceBehavior(EventWaitHandle handle, Action action) + { + this.handle = handle; + this.action = action; + } - public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters) - { - } + public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters) + { + } - public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + { + foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers) { - foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers) - { - dispatcher.ErrorHandlers.Add(new ErrorHandler(this.handle, this.action)); - } + dispatcher.ErrorHandlers.Add(new ErrorHandler(this.handle, this.action)); } + } - public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) - { - } + public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) + { } } + #endif diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs index 92abafbe02..5dbee33438 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/IServiceContract.cs @@ -17,18 +17,17 @@ using System.ServiceModel; using System.Threading.Tasks; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +[ServiceContract(Namespace = "http://opentelemetry.io/", Name = "Service", SessionMode = SessionMode.Allowed)] +public interface IServiceContract { - [ServiceContract(Namespace = "http://opentelemetry.io/", Name = "Service", SessionMode = SessionMode.Allowed)] - public interface IServiceContract - { - [OperationContract] - Task ExecuteAsync(ServiceRequest request); + [OperationContract] + Task ExecuteAsync(ServiceRequest request); - [OperationContract(Action = "")] - Task ExecuteWithEmptyActionNameAsync(ServiceRequest request); + [OperationContract(Action = "")] + Task ExecuteWithEmptyActionNameAsync(ServiceRequest request); - [OperationContract(IsOneWay = true)] - void ExecuteWithOneWay(ServiceRequest request); - } + [OperationContract(IsOneWay = true)] + void ExecuteWithOneWay(ServiceRequest request); } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/Service.netfx.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/Service.netfx.cs index d172ae8ec9..3cecbe1cb9 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/Service.netfx.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/Service.netfx.cs @@ -13,41 +13,42 @@ // See the License for the specific language governing permissions and // limitations under the License. // + #if NETFRAMEWORK using System.ServiceModel; using System.Threading.Tasks; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +[ServiceBehavior( + Namespace = "http://opentelemetry.io/", + ConcurrencyMode = ConcurrencyMode.Multiple, + InstanceContextMode = InstanceContextMode.Single, + UseSynchronizationContext = false, + Name = "Service")] +public class Service : IServiceContract { - [ServiceBehavior( - Namespace = "http://opentelemetry.io/", - ConcurrencyMode = ConcurrencyMode.Multiple, - InstanceContextMode = InstanceContextMode.Single, - UseSynchronizationContext = false, - Name = "Service")] - public class Service : IServiceContract + public Task ExecuteAsync(ServiceRequest request) { - public Task ExecuteAsync(ServiceRequest request) - { - return Task.FromResult( - new ServiceResponse - { - Payload = $"RSP: {request.Payload}", - }); - } + return Task.FromResult( + new ServiceResponse + { + Payload = $"RSP: {request.Payload}", + }); + } - public Task ExecuteWithEmptyActionNameAsync(ServiceRequest request) - { - return Task.FromResult( - new ServiceResponse - { - Payload = $"RSP: {request.Payload}", - }); - } + public Task ExecuteWithEmptyActionNameAsync(ServiceRequest request) + { + return Task.FromResult( + new ServiceResponse + { + Payload = $"RSP: {request.Payload}", + }); + } - public void ExecuteWithOneWay(ServiceRequest request) - { - } + public void ExecuteWithOneWay(ServiceRequest request) + { } } + #endif diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs index 353cd624de..7381b135fc 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceClient.cs @@ -18,22 +18,21 @@ using System.ServiceModel.Channels; using System.Threading.Tasks; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +public class ServiceClient : ClientBase, IServiceContract { - public class ServiceClient : ClientBase, IServiceContract + public ServiceClient(Binding binding, EndpointAddress remoteAddress) + : base(binding, remoteAddress) { - public ServiceClient(Binding binding, EndpointAddress remoteAddress) - : base(binding, remoteAddress) - { - } + } - public Task ExecuteAsync(ServiceRequest request) - => this.Channel.ExecuteAsync(request); + public Task ExecuteAsync(ServiceRequest request) + => this.Channel.ExecuteAsync(request); - public Task ExecuteWithEmptyActionNameAsync(ServiceRequest request) - => this.Channel.ExecuteWithEmptyActionNameAsync(request); + public Task ExecuteWithEmptyActionNameAsync(ServiceRequest request) + => this.Channel.ExecuteWithEmptyActionNameAsync(request); - public void ExecuteWithOneWay(ServiceRequest request) - => this.Channel.ExecuteWithOneWay(request); - } + public void ExecuteWithOneWay(ServiceRequest request) + => this.Channel.ExecuteWithOneWay(request); } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs index 60da5eca97..6e7ffcb3b6 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceRequest.cs @@ -16,12 +16,11 @@ using System.Runtime.Serialization; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +[DataContract] +public class ServiceRequest { - [DataContract] - public class ServiceRequest - { - [DataMember] - public string Payload { get; set; } - } + [DataMember] + public string Payload { get; set; } } diff --git a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs index e8856e2847..b076c64f7a 100644 --- a/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs +++ b/test/OpenTelemetry.Instrumentation.Wcf.Tests/WCF/ServiceResponse.cs @@ -16,12 +16,11 @@ using System.Runtime.Serialization; -namespace OpenTelemetry.Instrumentation.Wcf.Tests +namespace OpenTelemetry.Instrumentation.Wcf.Tests; + +[DataContract] +public class ServiceResponse { - [DataContract] - public class ServiceResponse - { - [DataMember] - public string Payload { get; set; } - } + [DataMember] + public string Payload { get; set; } }