Skip to content

Instantly share code, notes, and snippets.

@debugthings
Created July 31, 2018 12:33
Show Gist options
  • Select an option

  • Save debugthings/91ab0560542320790e79c36b1087e202 to your computer and use it in GitHub Desktop.

Select an option

Save debugthings/91ab0560542320790e79c36b1087e202 to your computer and use it in GitHub Desktop.
Wcf Activity correlation
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
namespace CommonMSSolve.Models.DataStructures
{
public class ActivityCorrelationBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new ActivityCorrelationInspector());
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new ActivityCorrelationInspector());
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
public class ActivityCorrelationInspector : IClientMessageInspector, IDispatchMessageInspector
{
private const string OperationNameHeader = "OperationName";
private const string CorrelationHeaderValue = "AppInsightsCorrelationHeader";
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var header = (from hd in request.Headers where hd.Name == CorrelationHeaderValue select hd).Count();
if (header == 0)
{
var mh = System.ServiceModel.Channels.MessageHeader.CreateHeader(CorrelationHeaderValue, string.Empty, Activity.Current);
request.Headers.Add(mh);
}
return null;
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
var header = (from hd in request.Headers where hd.Name == CorrelationHeaderValue select hd).Count();
if (header > 0)
{
var remoteActivity = request.Headers.GetHeader<Activity>(CorrelationHeaderValue, string.Empty);
if (remoteActivity != null)
{
var operationName = remoteActivity.Tags.FirstOrDefault(tag => tag.Key == OperationNameHeader).Value;
if (System.Diagnostics.Activity.Current == null)
{
var act = new System.Diagnostics.Activity(operationName);
act.SetParentId(remoteActivity.Id);
act.Start();
}
else
{
System.Diagnostics.Activity.Current.SetParentId(remoteActivity.Id);
System.Diagnostics.Activity.Current.AddTag(OperationNameHeader, operationName);
}
}
}
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment