public void When_correlation_is_not_initialized_then_it_forgets_the_correlation_keyvalues()
        {
            CorrelationState.TryAddOrUpdateCorrelationValue(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
            var values = CorrelationState.GetCorrelationValues();

            Assert.False(values.Any());
        }
Example #2
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            Guid?   existingCorrelationId = null;
            dynamic request = actionContext.ActionArguments.Values.FirstOrDefault();

            if (request != null)
            {
                if (_setCorrelationIdFromContext)
                {
                    try
                    {
                        existingCorrelationId = Guid.Parse(request.Context);
                    }
                    catch
                    {
                    }
                }
            }

            var disposableCorrelationState = CorrelationState.InitializeCorrelation(existingCorrelationId);

            actionContext.Request.RegisterForDispose(disposableCorrelationState);

            if (request != null)
            {
                CorrelationState.TryAddOrUpdateCorrelationValue("CallerContext", request.Context);
            }
        }
Example #3
0
        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            dynamic response = actionExecutedContext.ActionContext.Response?.Content;

            // Response can be null if we respond with streamed data (i.e. csv/pdf export)
            if (response != null)
            {
                // This method is always executed after each request but we can't guarantee
                // the thread context. If correlation Id is set in another thread in case
                // of exception - correlation id will not be set for this thread and we
                // shouldn't replace it.
                try
                {
                    if (string.IsNullOrEmpty(response.Value.CorrelationId))
                    {
                        response.Value.CorrelationId = CorrelationState.GetCurrentCorrelationId()?.ToString();
                    }

                    actionExecutedContext.ActionContext.Response.Content = response;
                }
                catch (RuntimeBinderException)
                {
                }
            }

            return(base.OnActionExecutedAsync(actionExecutedContext, cancellationToken));
        }
        public void When_correlation_is_set_with_a_predefined_correlation_id_Then_it_should_always_return_it()
        {
            var correlationId1 = Guid.NewGuid();
            var correlationId2 = Guid.NewGuid();

            var thread1 = Task <Guid?> .Factory.StartNew(() =>
            {
                CorrelationState.InitializeCorrelation(correlationId1);

                var correlationid = CorrelationState.GetCurrentCorrelationId();

                CorrelationState.ClearCorrelation();

                return(correlationid);
            });

            var thread2 = Task <Guid?> .Factory.StartNew(() =>
            {
                CorrelationState.InitializeCorrelation(correlationId2);

                var correlationid = CorrelationState.GetCurrentCorrelationId();

                CorrelationState.ClearCorrelation();

                return(correlationid);
            });

            Task.WaitAll(thread1, thread2);

            Assert.Equal(correlationId1, thread1.Result);
            Assert.Equal(correlationId2, thread2.Result);
        }
Example #5
0
        public void AuthorizationMessageInspector_BeforeSendReply___When_Synchronizer_throws___Logs_Exception()
        {
            var authorizationSynchronizer = new Mock <IAuthorizationSynchronizer>();
            var logger = new Mock <ILogger>();

            Exception synchronizationException = new Exception("exception during synchronization");

            authorizationSynchronizer.Setup(x => x.ReleaseLock(It.IsAny <string>(), It.IsAny <object>()))
            .Throws(synchronizationException);

            CorrelationState correlationState = new CorrelationState()
            {
                ObjectLock  = new object(),
                UserContext = new UserContext("myuserid", "mytoken")
            };
            var       inspector       = Create_AuthorizationMessageInspector(authorizationSynchronizer: authorizationSynchronizer.Object, logger: logger.Object);
            Exception thrownException = null;

            try
            {
                Message reply = null;
                inspector.BeforeSendReply(reply: ref reply, correlationState: correlationState);
            }
            catch (Exception ex)
            {
                thrownException = ex;
            }
            logger.Verify(x => x.LogException(It.Is <Exception>(y => object.ReferenceEquals(y, thrownException))), Times.Once);
        }
Example #6
0
        /// <summary>
        /// Called after the operation has returned but before the reply message is sent.
        /// </summary>
        /// <param name="reply">The reply.</param>
        /// <param name="correlationState">State of the correlation.</param>
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            CorrelationState state = correlationState as CorrelationState;

            Guid messageId = Guid.Empty;

            bool isOneWay = false;

            if (state != null)
            {
                messageId = state.MessageId;
                isOneWay  = state.IsOneWay;
            }

            Debug.WriteLine("DevLib.ServiceModel.WcfMessageInspector.BeforeSendReply: " + messageId.ToString());

            string validationError = this.ValidateMessage(reply, messageId);

            if (reply == null)
            {
                isOneWay = true;
            }

            if (!this.IgnoreMessageInspect)
            {
                this.RaiseEvent(this.SendingReply, reply, messageId, isOneWay, validationError);
            }
        }
Example #7
0
        public void AuthorizationMessageInspector_AfterReceiveRequest___With_call_to_Authorize_that_succeeds___SucceedsAndReturnsState()
        {
            var requestAuthorizer = new Mock <IRequestAuthorizer>();

            requestAuthorizer.Setup(x => x.IsAuthorizationNeeded(It.IsAny <Message>())).Returns(true);

            const string USERID = "myuserid";
            const string TOKEN  = "mytoken";

            string      errorMessage = null;
            UserContext userContext  = new UserContext(USERID, TOKEN);

            requestAuthorizer.Setup(x => x.Authorize(It.IsAny <Message>(), out errorMessage, out userContext))
            .Returns(true);

            var inspector = Create_AuthorizationMessageInspector(requestAuthorizer: requestAuthorizer.Object);

            Message request = null;
            object  ret     = inspector.AfterReceiveRequest(request: ref request, channel: null, instanceContext: null);

            Assert.IsNotNull(ret);
            Assert.IsInstanceOfType(ret, typeof(CorrelationState));
            CorrelationState correlationState = (CorrelationState)ret;

            Assert.IsNotNull(correlationState.UserContext);
            Assert.AreEqual(USERID, correlationState.UserContext.UserID);
            Assert.AreEqual(TOKEN, correlationState.UserContext.Token);
        }
        public void When_correlation_is_access_different_threads_It_returns_different_ids()
        {
            var thread1 = Task <Guid?> .Factory.StartNew(() =>
            {
                CorrelationState.InitializeCorrelation();

                var correlationid = CorrelationState.GetCurrentCorrelationId();

                CorrelationState.ClearCorrelation();

                return(correlationid);
            });

            var thread2 = Task <Guid?> .Factory.StartNew(() =>
            {
                CorrelationState.InitializeCorrelation();

                var correlationid = CorrelationState.GetCurrentCorrelationId();

                CorrelationState.ClearCorrelation();

                return(correlationid);
            });

            Task.WaitAll(thread1, thread2);

            Assert.NotEqual(thread1.Result, thread2.Result);
        }
        private ILogMessage CreateOutputMethodLogMessage(MethodReturn methodReturn, CorrelationState correlationState)
        {
            var logMessage = Target.CreateOutputMethodLogMessage(methodReturn, correlationState.InnerCorrelationState);

            logMessage.AddMessageProperty("HashCode", correlationState.TargetHashCode);

            return(logMessage);
        }
Example #10
0
        private ILogMessage CreateOutputMethodLogMessage(MethodReturn methodReturn, CorrelationState correlationState)
        {
            correlationState.Stopwatch.Stop();

            var logMessage = Target.CreateOutputMethodLogMessage(methodReturn, correlationState.InnerCorrelationState);

            logMessage.AddMessageProperty("Elapsed", correlationState.Stopwatch.Elapsed.TotalMilliseconds);

            return(logMessage);
        }
        public async Task When_correlation_id_is_set_outside_an_async_call_then_the_correlation_id_is_available_inside_the_async_call()
        {
            var expectedCorrelationId = Guid.NewGuid();

            CorrelationState.InitializeCorrelation(expectedCorrelationId);

            var correlationId = await Task.Run(() => CorrelationState.GetCurrentCorrelationId());

            Assert.Equal(expectedCorrelationId, correlationId);
        }
Example #12
0
        public void AfterInvoke(object correlationState)
        {
            CorrelationState state = (CorrelationState)correlationState;

            if (state != null)
            {
                ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, 0x50019, "TraceCodeComIntegrationInvokedMethod", this.info, state.From, state.Action, state.CallerIdentity, this.iid, state.InstanceID, false);
                state.Cleanup();
            }
        }
        public void When_correlation_is_uninitialized_Then_it_returns_null_when_asked_for_current_correlation_id()
        {
            var thread = Task <Guid?> .Factory.StartNew(() =>
            {
                CorrelationState.ClearCorrelation();
                return(CorrelationState.GetCurrentCorrelationId());
            });

            Task.WaitAll(thread);

            Assert.Null(thread.Result);
        }
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var currentCorrelationId = CorrelationState.GetCurrentCorrelationId();

            if (currentCorrelationId.HasValue)
            {
                var correlationDictionary = CorrelationState.GetCorrelationValues().ToDictionary(c => c.Key, c => c.Value);

                correlationDictionary["CorrelationId"] = currentCorrelationId.Value;

                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Correlation", correlationDictionary, destructureObjects: true));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("CorrelationId", currentCorrelationId.Value));
            }
        }
Example #15
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Guid?existingCorrelationId = null;

            if (_setCorrelationIdFromContext)
            {
                try
                {
                    existingCorrelationId = Guid.Parse(filterContext.HttpContext.Request.QueryString["Context"]);
                }
                catch
                {
                }
            }

            CorrelationState.InitializeCorrelation(existingCorrelationId);
        }
        public async Task When_correlation_values_is_set_outside_an_async_call_then_the_correlation_values_are_available_inside_the_async_call()
        {
            var key   = Guid.NewGuid().ToString();
            var value = Guid.NewGuid().ToString();

            CorrelationState.InitializeCorrelation();
            CorrelationState.TryAddOrUpdateCorrelationValue(key, value);

            var correlationValues = (await Task.Run(() => CorrelationState.GetCorrelationValues())).ToList();

            Assert.Equal(1, correlationValues.Count);

            var firstCorrelationValue = correlationValues.First();

            Assert.Equal(key, firstCorrelationValue.Key);
            Assert.Equal(value, firstCorrelationValue.Value);
        }
        public void When_correlation_is_initialized_and_then_cleared_then_it_forgets_the_correlation_keyvalues()
        {
            var thread = Task <IEnumerable <KeyValuePair <string, object> > > .Factory.StartNew(() =>
            {
                CorrelationState.InitializeCorrelation();

                CorrelationState.TryAddOrUpdateCorrelationValue(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

                CorrelationState.ClearCorrelation();

                return(CorrelationState.GetCorrelationValues());
            });

            Task.WaitAll(thread);

            Assert.False(thread.Result.Any());
        }
Example #18
0
        public void AuthorizationMessageInspector_BeforeSendReply___When_CorrelationState_is_passed_as_argument___Calls_Synchronizer_to_release_lock_with_correct_arguments()
        {
            var authorizationSynchronizer = new Mock <IAuthorizationSynchronizer>();

            const string USERID     = "myuserid";
            object       OBJECTLOCK = new object();

            CorrelationState correlationState = new CorrelationState()
            {
                ObjectLock  = OBJECTLOCK,
                UserContext = new UserContext(USERID, "dummytoken")
            };
            var     inspector = Create_AuthorizationMessageInspector(authorizationSynchronizer: authorizationSynchronizer.Object);
            Message reply     = null;

            inspector.BeforeSendReply(reply: ref reply, correlationState: correlationState);

            authorizationSynchronizer.Verify(x => x.ReleaseLock(It.Is <string>(y => y == USERID), It.Is <object>(y => object.ReferenceEquals(y, OBJECTLOCK))), Times.Once);
        }
        public void When_correlation_is_initialized_then_correlation_dictionary_accepts_new_correlation_keyvalues()
        {
            var key           = Guid.NewGuid().ToString();
            var expectedValue = Guid.NewGuid().ToString();

            var thread = Task <IEnumerable <KeyValuePair <string, object> > > .Factory.StartNew(() =>
            {
                CorrelationState.InitializeCorrelation();

                CorrelationState.TryAddOrUpdateCorrelationValue(key, expectedValue);

                return(CorrelationState.GetCorrelationValues());
            });

            Task.WaitAll(thread);

            var actualValue = thread.Result.SingleOrDefault(c => c.Key == key);

            Assert.Equal(expectedValue, actualValue.Value);
        }
Example #20
0
        private ILogMessage CreateOutputMethodLogMessage(MethodReturn methodReturn, CorrelationState correlationState)
        {
            if (methodReturn.Exception == null)
            {
                var logMessage = new LogMessage(_logMessageSettings.OutputLogMessageTemplate);

                logMessage.AddMessageProperty("ClassName", correlationState.ClassName);

                logMessage.AddMessageProperty("MethodName", correlationState.MethodName);

                if (methodReturn.ReturnValue == null)
                {
                    if (correlationState.Input?.Method?.ReturnType == typeof(void))
                    {
                        logMessage.AddMessageProperty("ReturnValue", "Void");

                        return(logMessage);
                    }
                }

                var returnValue = _logValueMapper.ToJson(methodReturn.ReturnValue);

                logMessage.AddMessageProperty("ReturnValue", returnValue);

                return(logMessage);
            }
            else
            {
                var logMessage = new LogMessage(_logMessageSettings.ErrorLogMessageTemplate);

                logMessage.AddMessageProperty("ClassName", correlationState.ClassName);

                logMessage.AddMessageProperty("MethodName", correlationState.MethodName);

                logMessage.AddMessageProperty("Exception", methodReturn.Exception);

                return(logMessage);
            }
        }
Example #21
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var transactionWrapperApi = _agent.CurrentTransaction;
            var correlationState      = new CorrelationState(transactionWrapperApi, transactionWrapperApi.CurrentSegment);

            if (!correlationState.Transaction.IsValid || !correlationState.Segment.IsExternal)
            {
                return(null);
            }

            try
            {
                if (_bindingType == typeof(NetTcpBinding))
                {
                    _agent.CurrentTransaction.InsertDistributedTraceHeaders(request, SetHeaders);
                }
                else
                {
                    HttpRequestMessageProperty httpRequestMessage;
                    if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out object httpRequestMessageObject))
                    {
                        httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
                    }
                    else
                    {
                        httpRequestMessage = new HttpRequestMessageProperty();
                        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
                    }

                    _agent.CurrentTransaction.InsertDistributedTraceHeaders(httpRequestMessage, SetHeaders);
                }
            }
            catch (Exception ex)
            {
                _agent.HandleWrapperException(ex);
            }

            return(correlationState);
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var transactionWrapperApi = _agent.CurrentTransaction;
            var correlationState      = new CorrelationState(transactionWrapperApi, transactionWrapperApi.CurrentSegment);

            if (!correlationState.Transaction.IsValid || !correlationState.Segment.IsExternal)
            {
                return(null);
            }

            HttpRequestMessageProperty httpRequestMessage;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out object httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
            }
            else
            {
                httpRequestMessage = new HttpRequestMessageProperty();
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }

            var setHeaders = new Action <HttpRequestMessageProperty, string, string>((carrier, key, value) =>
            {
                // 'Set' will replace an existing value
                carrier.Headers?.Set(key, value);
            });

            try
            {
                _agent.CurrentTransaction.InsertDistributedTraceHeaders(httpRequestMessage, setHeaders);
            }
            catch (Exception ex)
            {
                _agent.HandleWrapperException(ex);
            }

            return(correlationState);
        }
Example #23
0
        private void OnBeginRequest(object sender, EventArgs e)
        {
            var app     = (HttpApplication)sender;
            var request = app.Request;

            if (SkipRequest(request))
            {
                return;
            }

            var context = new LogCastContext
            {
                OperationName = GetOperationName(request),
                CorrelationId = GetCorrelationId(request),
                SuppressEmtpyContextMessages = true
            };

            var root = ApplyRequestData(context, request);

            var correlationState = new CorrelationState <Root>(context, root);

            app.Context.Items[CorrelationState <Root> .Key] = correlationState;
        }
 public override void OnActionExecuted(ActionExecutedContext context)
 {
     CorrelationState.ClearCorrelation();
     base.OnActionExecuted(context);
 }
 public override void OnActionExecuting(ActionExecutingContext actionContext)
 {
     CorrelationState.InitializeCorrelation();
 }
 public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
 {
     ComPlusServerSecurity serverSecurity = null;
     WindowsImpersonationContext context = null;
     object obj3;
     bool flag = false;
     WindowsIdentity clientIdentity = null;
     Uri from = null;
     int instanceID = 0;
     string action = null;
     TransactionProxy proxy = null;
     Transaction messageTransaction = null;
     Guid empty = Guid.Empty;
     try
     {
         try
         {
             clientIdentity = MessageUtil.GetMessageIdentity(message);
             if (message.Headers.From != null)
             {
                 from = message.Headers.From.Uri;
             }
             instanceID = instanceContext.GetServiceInstance(message).GetHashCode();
             action = message.Headers.Action;
             ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, 0x50018, "TraceCodeComIntegrationInvokingMethod", this.info, from, action, clientIdentity.Name, this.iid, instanceID, false);
             if (this.info.CheckRoles && !this.comAuth.IsAuthorizedForOperation(clientIdentity))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CallAccessDenied());
             }
             if (this.info.HostingMode != HostingMode.WebHostOutOfProcess)
             {
                 serverSecurity = new ComPlusServerSecurity(clientIdentity, this.info.CheckRoles);
             }
             proxy = instanceContext.Extensions.Find<TransactionProxy>();
             if (proxy != null)
             {
                 messageTransaction = MessageUtil.GetMessageTransaction(message);
                 if (messageTransaction != null)
                 {
                     empty = messageTransaction.TransactionInformation.DistributedIdentifier;
                 }
                 try
                 {
                     if (messageTransaction == null)
                     {
                         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.TransactionMismatch());
                     }
                     proxy.SetTransaction(messageTransaction);
                     ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, 0x5001a, "TraceCodeComIntegrationInvokingMethodNewTransaction", this.info, from, action, clientIdentity.Name, this.iid, instanceID, empty);
                     goto Label_02DC;
                 }
                 catch (FaultException exception)
                 {
                     Transaction currentTransaction = proxy.CurrentTransaction;
                     Guid distributedIdentifier = Guid.Empty;
                     if (currentTransaction != null)
                     {
                         distributedIdentifier = currentTransaction.TransactionInformation.DistributedIdentifier;
                     }
                     string name = string.Empty;
                     if (clientIdentity != null)
                     {
                         name = clientIdentity.Name;
                     }
                     DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.ComPlus, (EventLogEventId) (-1073610725), new string[] { empty.ToString("B").ToUpperInvariant(), distributedIdentifier.ToString("B").ToUpperInvariant(), from.ToString(), this.info.AppID.ToString("B").ToUpperInvariant(), this.info.Clsid.ToString("B").ToUpperInvariant(), this.iid.ToString(), action, instanceID.ToString(CultureInfo.InvariantCulture), Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture), System.ServiceModel.ComIntegration.SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture), name, exception.ToString() });
                     flag = true;
                     throw;
                 }
             }
             ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, 0x5001b, "TraceCodeComIntegrationInvokingMethodContextTransaction", this.info, from, action, clientIdentity.Name, this.iid, instanceID, true);
         Label_02DC:
             if (this.info.HostingMode == HostingMode.WebHostOutOfProcess)
             {
                 context = clientIdentity.Impersonate();
             }
             CorrelationState state = new CorrelationState(context, serverSecurity, from, action, clientIdentity.Name, instanceID);
             context = null;
             serverSecurity = null;
             obj3 = state;
         }
         finally
         {
             if (context != null)
             {
                 context.Undo();
             }
             if (serverSecurity != null)
             {
                 ((IDisposable) serverSecurity).Dispose();
             }
         }
     }
     catch (Exception exception2)
     {
         if (!flag && DiagnosticUtility.ShouldTraceError)
         {
             DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.ComPlus, (EventLogEventId) (-1073610727), new string[] { (from == null) ? string.Empty : from.ToString(), this.info.AppID.ToString("B").ToUpperInvariant(), this.info.Clsid.ToString("B").ToUpperInvariant(), this.iid.ToString("B").ToUpperInvariant(), action, instanceID.ToString(CultureInfo.InvariantCulture), Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture), System.ServiceModel.ComIntegration.SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture), clientIdentity.Name, exception2.ToString() });
         }
         throw;
     }
     return obj3;
 }
 public static void Enable()
 {
     CorrelationState.Use(new HttpContextCorrelationState());
 }
Example #28
0
 public async Task <HttpResponseMessage> Get()
 {
     return(await Task.Run(() => Request.CreateResponse(HttpStatusCode.OK, CorrelationState.GetCurrentCorrelationId())));
 }
        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            CorrelationState.ClearCorrelation();

            return(base.OnActionExecutedAsync(actionExecutedContext, cancellationToken));
        }
Example #30
0
        public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message)
        {
            ComPlusServerSecurity       serverSecurity = null;
            WindowsImpersonationContext context        = null;
            object           obj3;
            bool             flag               = false;
            WindowsIdentity  clientIdentity     = null;
            Uri              from               = null;
            int              instanceID         = 0;
            string           action             = null;
            TransactionProxy proxy              = null;
            Transaction      messageTransaction = null;
            Guid             empty              = Guid.Empty;

            try
            {
                try
                {
                    clientIdentity = MessageUtil.GetMessageIdentity(message);
                    if (message.Headers.From != null)
                    {
                        from = message.Headers.From.Uri;
                    }
                    instanceID = instanceContext.GetServiceInstance(message).GetHashCode();
                    action     = message.Headers.Action;
                    ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, 0x50018, "TraceCodeComIntegrationInvokingMethod", this.info, from, action, clientIdentity.Name, this.iid, instanceID, false);
                    if (this.info.CheckRoles && !this.comAuth.IsAuthorizedForOperation(clientIdentity))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CallAccessDenied());
                    }
                    if (this.info.HostingMode != HostingMode.WebHostOutOfProcess)
                    {
                        serverSecurity = new ComPlusServerSecurity(clientIdentity, this.info.CheckRoles);
                    }
                    proxy = instanceContext.Extensions.Find <TransactionProxy>();
                    if (proxy != null)
                    {
                        messageTransaction = MessageUtil.GetMessageTransaction(message);
                        if (messageTransaction != null)
                        {
                            empty = messageTransaction.TransactionInformation.DistributedIdentifier;
                        }
                        try
                        {
                            if (messageTransaction == null)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.TransactionMismatch());
                            }
                            proxy.SetTransaction(messageTransaction);
                            ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, 0x5001a, "TraceCodeComIntegrationInvokingMethodNewTransaction", this.info, from, action, clientIdentity.Name, this.iid, instanceID, empty);
                            goto Label_02DC;
                        }
                        catch (FaultException exception)
                        {
                            Transaction currentTransaction    = proxy.CurrentTransaction;
                            Guid        distributedIdentifier = Guid.Empty;
                            if (currentTransaction != null)
                            {
                                distributedIdentifier = currentTransaction.TransactionInformation.DistributedIdentifier;
                            }
                            string name = string.Empty;
                            if (clientIdentity != null)
                            {
                                name = clientIdentity.Name;
                            }
                            DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.ComPlus, (EventLogEventId)(-1073610725), new string[] { empty.ToString("B").ToUpperInvariant(), distributedIdentifier.ToString("B").ToUpperInvariant(), from.ToString(), this.info.AppID.ToString("B").ToUpperInvariant(), this.info.Clsid.ToString("B").ToUpperInvariant(), this.iid.ToString(), action, instanceID.ToString(CultureInfo.InvariantCulture), Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture), System.ServiceModel.ComIntegration.SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture), name, exception.ToString() });
                            flag = true;
                            throw;
                        }
                    }
                    ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, 0x5001b, "TraceCodeComIntegrationInvokingMethodContextTransaction", this.info, from, action, clientIdentity.Name, this.iid, instanceID, true);
Label_02DC:
                    if (this.info.HostingMode == HostingMode.WebHostOutOfProcess)
                    {
                        context = clientIdentity.Impersonate();
                    }
                    CorrelationState state = new CorrelationState(context, serverSecurity, from, action, clientIdentity.Name, instanceID);
                    context        = null;
                    serverSecurity = null;
                    obj3           = state;
                }
                finally
                {
                    if (context != null)
                    {
                        context.Undo();
                    }
                    if (serverSecurity != null)
                    {
                        ((IDisposable)serverSecurity).Dispose();
                    }
                }
            }
            catch (Exception exception2)
            {
                if (!flag && DiagnosticUtility.ShouldTraceError)
                {
                    DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.ComPlus, (EventLogEventId)(-1073610727), new string[] { (from == null) ? string.Empty : from.ToString(), this.info.AppID.ToString("B").ToUpperInvariant(), this.info.Clsid.ToString("B").ToUpperInvariant(), this.iid.ToString("B").ToUpperInvariant(), action, instanceID.ToString(CultureInfo.InvariantCulture), Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture), System.ServiceModel.ComIntegration.SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture), clientIdentity.Name, exception2.ToString() });
                }
                throw;
            }
            return(obj3);
        }
        public object BeforeInvoke(
            InstanceContext instanceContext,
            IClientChannel channel,
            Message message)
        {
            ComPlusServerSecurity serverSecurity = null;
            WindowsImpersonationContext impersonateContext = null;
            bool errorTraced = false;
            WindowsIdentity identity = null;
            Uri from = null;
            object instance = null;
            int instanceID = 0;
            string action = null;
            TransactionProxy proxy = null;
            Transaction tx = null;
            Guid incomingTransactionID = Guid.Empty;

            // The outer try block is to comply with FXCOP's WrapVulnerableFinallyClausesInOuterTry rule.
            try
            {
                try
                {

                    identity = MessageUtil.GetMessageIdentity(message);

                    if (message.Headers.From != null)
                        from = message.Headers.From.Uri;

                    instance = instanceContext.GetServiceInstance(message);
                    instanceID = instance.GetHashCode();
                    action = message.Headers.Action;



                    ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethod,
                        SR.TraceCodeComIntegrationInvokingMethod, this.info, from, action, identity.Name, iid, instanceID, false);

                    // Security
                    //

                    if (this.info.CheckRoles)
                    {
                        if (!this.comAuth.IsAuthorizedForOperation(identity))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CallAccessDenied());
                        }
                    }

                    if (this.info.HostingMode != HostingMode.WebHostOutOfProcess)
                    {
                        // NOTE: This has the side effect of setting up
                        //       the COM server security thing, so be sure
                        //       to clear it with Dispose() eventually.
                        //
                        serverSecurity = new ComPlusServerSecurity(identity,
                                                                   this.info.CheckRoles);
                    }

                    // Transactions
                    //
                    proxy = instanceContext.Extensions.Find<TransactionProxy>();
                    if (proxy != null)
                    {
                        // This makes the Tx header Understood.
                        tx = MessageUtil.GetMessageTransaction(message);
                        if (tx != null)
                        {
                            incomingTransactionID = tx.TransactionInformation.DistributedIdentifier;
                        }
                        try
                        {
                            if (tx != null)
                            {
                                proxy.SetTransaction(tx);
                            }
                            else
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.TransactionMismatch());
                            }
                            ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethodNewTransaction,
                            SR.TraceCodeComIntegrationInvokingMethodNewTransaction, this.info, from, action, identity.Name, iid, instanceID, incomingTransactionID);
                        }
                        catch (FaultException e)
                        {
                            Transaction txProxy = proxy.CurrentTransaction;
                            Guid currentTransactionID = Guid.Empty;
                            if (txProxy != null)
                                currentTransactionID = txProxy.TransactionInformation.DistributedIdentifier;

                            string identityName = String.Empty;

                            if (null != identity)
                                identityName = identity.Name;

                            DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                                (ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
                                (uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusInvokingMethodFailedMismatchedTransactions,
                                incomingTransactionID.ToString("B").ToUpperInvariant(),
                                currentTransactionID.ToString("B").ToUpperInvariant(),
                                from.ToString(),
                                this.info.AppID.ToString("B").ToUpperInvariant(),
                                this.info.Clsid.ToString("B").ToUpperInvariant(),
                                iid.ToString(),
                                action,
                                instanceID.ToString(CultureInfo.InvariantCulture),
                                System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture),
                                SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture),
                                identityName,
                                e.ToString());
                            errorTraced = true;
                            throw;
                        }
                    }
                    else
                    {
                        ComPlusMethodCallTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationInvokingMethodContextTransaction,
                        SR.TraceCodeComIntegrationInvokingMethodContextTransaction, this.info, from, action, identity.Name, iid, instanceID, true);
                    }

                    // Impersonation
                    //
                    if (this.info.HostingMode == HostingMode.WebHostOutOfProcess)
                    {
                        impersonateContext = identity.Impersonate();
                    }

                    CorrelationState correlationState;
                    correlationState = new CorrelationState(impersonateContext,
                                                            serverSecurity,
                                                            from,
                                                            action,
                                                            identity.Name,
                                                            instanceID);

                    impersonateContext = null;
                    serverSecurity = null;


                    return correlationState;
                }
                finally
                {
                    if (impersonateContext != null)
                        impersonateContext.Undo();

                    if (serverSecurity != null)
                        ((IDisposable)serverSecurity).Dispose();
                }

            }
            catch (Exception e)
            {
                if (errorTraced == false)
                {
                    if (DiagnosticUtility.ShouldTraceError)
                    {
                        DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                           (ushort)System.Runtime.Diagnostics.EventLogCategory.ComPlus,
                           (uint)System.Runtime.Diagnostics.EventLogEventId.ComPlusInvokingMethodFailed,
                           from == null ? string.Empty : from.ToString(),
                           this.info.AppID.ToString("B").ToUpperInvariant(),
                           this.info.Clsid.ToString("B").ToUpperInvariant(),
                           iid.ToString("B").ToUpperInvariant(),
                           action,
                           instanceID.ToString(CultureInfo.InvariantCulture),
                           System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture),
                           SafeNativeMethods.GetCurrentThreadId().ToString(CultureInfo.InvariantCulture),
                           identity.Name,
                           e.ToString());
                    }
                }
                throw;
            }

        }
 public void Dispose()
 {
     CorrelationState.ClearCorrelation();
 }