TraceUtility.cs source code in C# .NET

Source code for the .NET framework in C#

                        

Code:

/ WCF / WCF / 3.5.30729.1 / untmp / Orcas / SP / ndp / cdf / src / WCF / ServiceModel / System / ServiceModel / Diagnostics / TraceUtility.cs / 1 / TraceUtility.cs

                            //---------------------------------------------------------------------------- 
// Copyright (c) Microsoft Corporation.  All rights reserved.
//---------------------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{ 
    using System.Diagnostics;
    using System.ServiceModel.Channels; 
    using System.Runtime.CompilerServices; 
    using System.Threading;
using System.Reflection; 
    using System.ServiceModel.Dispatcher;
    using System.Net;

    internal static class TraceUtility 
    {
        const string ActivityIdKey = "ActivityId"; 
        const string AsyncOperationActivityKey = "AsyncOperationActivity"; 
        static bool shouldPropagateActivity = false;
        static long messageNumber = 0; 

        static internal void AddActivityHeader(Message message)
        {
            try 
            {
                ActivityIdHeader activityIdHeader = new ActivityIdHeader(TraceUtility.ExtractActivityId(message)); 
                activityIdHeader.AddTo(message); 
            }
#pragma warning suppress 56500 // covered by FxCOP 
            catch (Exception e)
            {
                if (DiagnosticUtility.IsFatal(e))
                { 
                    throw;
                } 
                TraceUtility.TraceEvent(TraceEventType.Error, 
                    TraceCode.FailedToAddAnActivityIdHeader,
                    e, 
                    message);
            }
        }
 
        static internal void AddAmbientActivityToMessage(Message message)
        { 
            try 
            {
                ActivityIdHeader activityIdHeader = new ActivityIdHeader(DiagnosticTrace.ActivityId); 
                activityIdHeader.AddTo(message);
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e) 
            {
                if (DiagnosticUtility.IsFatal(e)) 
                { 
                    throw;
                } 
                TraceUtility.TraceEvent(TraceEventType.Error,
                    TraceCode.FailedToAddAnActivityIdHeader,
                    e,
                    message); 
            }
        } 
 
        static internal void CopyActivity(Message source, Message destination)
        { 
            if (DiagnosticUtility.ShouldUseActivity)
            {
                TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source));
            } 
        }
 
        static string Description(TraceCode traceCode) 
        {
            // This method's validity is checked via a BVT at 
            // ddsuites\src\indigo\Suites\diagnostics\Tracing\TraceCodeVerification
            string descriptionKey = "TraceCode" + DiagnosticTrace.CodeToString(traceCode);
            return SR.GetString(descriptionKey);
        } 

        internal static ServiceModelActivity ExtractActivity(Message message) 
        { 
            ServiceModelActivity retval = null;
 
            if (DiagnosticUtility.ShouldUseActivity &&
                (message != null) &&
                (message.State != MessageState.Closed))
            { 
                object property;
 
                if (message.Properties.TryGetValue(TraceUtility.ActivityIdKey, out property)) 
                {
                    retval = property as ServiceModelActivity; 
                }
            }
            return retval;
        } 

        internal static Guid ExtractActivityId(Message message) 
        { 
            ServiceModelActivity activity = ExtractActivity(message);
            return activity == null ? Guid.Empty : activity.Id; 
        }

        internal static ServiceModelActivity ExtractAndRemoveActivity(Message message)
        { 
            ServiceModelActivity retval = TraceUtility.ExtractActivity(message);
            if (retval != null) 
            { 
                // If the property is just removed, the item is disposed and we don't want the thing
                // to be disposed of. 
                message.Properties[TraceUtility.ActivityIdKey] = false;
            }
            return retval;
        } 

        internal static void ProcessIncomingMessage(Message message) 
        { 
            ServiceModelActivity activity = ServiceModelActivity.Current;
            if (DiagnosticUtility.ShouldUseActivity) 
            {
                ServiceModelActivity incomingActivity = TraceUtility.ExtractActivity(message);
                if (null != incomingActivity && incomingActivity.Id != activity.Id)
                { 
                    using (ServiceModelActivity.BoundOperation(incomingActivity))
                    { 
                        DiagnosticUtility.DiagnosticTrace.TraceTransfer(activity.Id); 
                    }
                } 
            }
            if (activity != null && DiagnosticUtility.ShouldUseActivity)
            {
                TraceUtility.SetActivity(message, activity); 
            }
 
            if (MessageLogger.LogMessagesAtServiceLevel) 
            {
                MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelReceiveReply | MessageLoggingSource.LastChance); 
            }
        }

        internal static void ProcessOutgoingMessage(Message message) 
        {
            ServiceModelActivity activity = ServiceModelActivity.Current; 
            if (DiagnosticUtility.ShouldUseActivity) 
            {
                TraceUtility.SetActivity(message, activity); 
            }
            if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity)
            {
                TraceUtility.AddAmbientActivityToMessage(message); 
            }
 
            if (MessageLogger.LogMessagesAtServiceLevel) 
            {
                MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelSendRequest | MessageLoggingSource.LastChance); 
            }
        }

        internal static void SetActivity(Message message, ServiceModelActivity activity) 
        {
            if (DiagnosticUtility.ShouldUseActivity && message != null && message.State != MessageState.Closed) 
            { 
                message.Properties[TraceUtility.ActivityIdKey] = activity;
            } 
        }

        internal static void TraceDroppedMessage(Message message, EndpointDispatcher dispatcher)
        { 
            if (DiagnosticUtility.ShouldTraceInformation)
            { 
                EndpointAddress endpointAddress = null; 
                if (dispatcher != null)
                { 
                    endpointAddress = dispatcher.EndpointAddress;
                }
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.DroppedAMessage,
                    new MessageDroppedTraceRecord(message, endpointAddress)); 
            }
        } 
 
        internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, object source)
        { 
            TraceEvent(severity, traceCode, null, source, (Exception)null);
        }

        internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, object source, Exception exception) 
        {
            TraceEvent(severity, traceCode, null, source, exception); 
        } 

        internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, Message message) 
        {
            if (null == message)
            {
                TraceEvent(severity, traceCode, null, (Exception)null); 
            }
            else 
            { 
                TraceEvent(severity, traceCode, message, message);
            } 
        }

        internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, object source, Message message)
        { 
            Guid activityId = TraceUtility.ExtractActivityId(message);
            if (DiagnosticUtility.ShouldTrace(severity)) 
            { 
                DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, Description(traceCode), new MessageTraceRecord(message), null, activityId, message);
            } 
        }

        internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, Exception exception, Message message)
        { 
            Guid activityId = TraceUtility.ExtractActivityId(message);
            if (DiagnosticUtility.ShouldTrace(severity)) 
            { 
                DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, Description(traceCode), new MessageTraceRecord(message), exception, activityId, null);
            } 
        }

        // These methods require a TraceRecord to be allocated, so we want them to show up on profiles if the caller didn't avoid
        // allocating the TraceRecord by using ShouldTrace. 
        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, TraceRecord extendedData, object source, Exception exception) 
        { 
            if (DiagnosticUtility.ShouldTrace(severity))
            { 
                DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, Description(traceCode), extendedData, exception, source);
            }
        }
 
        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, TraceRecord extendedData, object source, Exception exception, Message message) 
        { 
            Guid activityId = TraceUtility.ExtractActivityId(message);
            if (DiagnosticUtility.ShouldTrace(severity)) 
            {
                DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, Description(traceCode), extendedData, exception, activityId, source);
            }
        } 

        internal static Exception ThrowHelperError(Exception exception, Message message) 
        { 
            // If the message is closed, we won't get an activity
            Guid activityId = TraceUtility.ExtractActivityId(message); 
            if (DiagnosticUtility.ShouldTraceError)
            {
                DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null);
            } 
            return exception;
        } 
 
        internal static Exception ThrowHelperError(Exception exception, Guid activityId, object source)
        { 
            if (DiagnosticUtility.ShouldTraceError)
            {
                DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, source);
            } 
            return exception;
        } 
 
        internal static Exception ThrowHelperWarning(Exception exception, Message message)
        { 
            if (DiagnosticUtility.ShouldTraceWarning)
            {
                Guid activityId = TraceUtility.ExtractActivityId(message);
                DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning, TraceCode.ThrowingException, TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null); 
            }
            return exception; 
        } 

        internal static ArgumentException ThrowHelperArgument(string paramName, string message, Message msg) 
        {
            return (ArgumentException)TraceUtility.ThrowHelperError(new ArgumentException(message, paramName), msg);
        }
 
        internal static ArgumentNullException ThrowHelperArgumentNull(string paramName, Message message)
        { 
            return (ArgumentNullException)TraceUtility.ThrowHelperError(new ArgumentNullException(paramName), message); 
        }
 
        internal static void TraceHttpConnectionInformation(string localEndpoint, string remoteEndpoint, object source)
        {
            if (DiagnosticUtility.ShouldTraceInformation)
            { 
                System.Collections.Generic.Dictionary values = new System.Collections.Generic.Dictionary(2);
                values["LocalEndpoint"] = localEndpoint; 
                values["RemoteEndpoint"] = remoteEndpoint; 
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ConnectToIPEndpoint,
                    new DictionaryTraceRecord(values), source, null); 
            }
        }

        internal static void TraceUserCodeException(Exception e, MethodInfo method) 
        {
            if (DiagnosticUtility.ShouldTraceWarning) 
            { 
                StringTraceRecord record = new StringTraceRecord("Comment",
                    SR.GetString(SR.SFxUserCodeThrewException, method.DeclaringType.FullName, method.Name)); 
                DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning,
                    TraceCode.UnhandledExceptionInUserOperation,
                    SR.GetString(SR.TraceCodeUnhandledExceptionInUserOperation, method.DeclaringType.FullName, method.Name),
                    record, 
                    e);
            } 
        } 

        static TraceUtility() 
        {
            if (DiagnosticUtility.DiagnosticTrace != null)
            {
                DiagnosticTraceSource ts = (DiagnosticTraceSource)DiagnosticUtility.DiagnosticTrace.TraceSource; 
                TraceUtility.shouldPropagateActivity = ts.PropagateActivity;
            } 
        } 

        static public long RetrieveMessageNumber() 
        {
            return Interlocked.Increment(ref TraceUtility.messageNumber);
        }
 
        static public bool PropagateUserActivity
        { 
            get 
            {
                return TraceUtility.ShouldPropagateActivity && 
                    TraceUtility.PropagateUserActivityCore;
            }
        }
 
        // Most of the time, shouldPropagateActivity will be false.
        // This property will rarely be executed as a result. 
        static bool PropagateUserActivityCore 
        {
            [MethodImpl(MethodImplOptions.NoInlining)] 
            get
            {
                return !(DiagnosticUtility.TracingEnabled) &&
                    DiagnosticTrace.ActivityId != Guid.Empty; 
            }
        } 
 
        static internal bool ShouldPropagateActivity
        { 
            get { return TraceUtility.shouldPropagateActivity; }
        }

        internal static void TransferFromTransport(Message message) 
        {
            if (message != null && DiagnosticUtility.ShouldUseActivity) 
            { 
                Guid guid = Guid.Empty;
 
                // Only look if we are allowing user propagation
                if (TraceUtility.ShouldPropagateActivity)
                {
                    guid = ActivityIdHeader.ExtractActivityId(message); 
                }
 
                if (guid == Guid.Empty) 
                {
                    guid = Guid.NewGuid(); 
                }

                ServiceModelActivity activity = null;
                bool emitStart = true; 
                if (ServiceModelActivity.Current != null)
                { 
                    if ((ServiceModelActivity.Current.Id == guid) || 
                        (ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction))
                    { 
                        activity = ServiceModelActivity.Current;
                        emitStart = false;
                    }
                    else if (ServiceModelActivity.Current.PreviousActivity != null && 
                        ServiceModelActivity.Current.PreviousActivity.Id == guid)
                    { 
                        activity = ServiceModelActivity.Current.PreviousActivity; 
                        emitStart = false;
                    } 
                }

                if (activity == null)
                { 
                    activity = ServiceModelActivity.CreateActivity(guid);
                } 
                if (DiagnosticUtility.ShouldUseActivity) 
                {
                    if (emitStart) 
                    {
                        DiagnosticUtility.DiagnosticTrace.TraceTransfer(guid);
                        ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessAction, message.Headers.Action), ActivityType.ProcessAction);
                    } 
                }
                message.Properties[TraceUtility.ActivityIdKey] = activity; 
            } 
        }
 
        static internal void UpdateAsyncOperationContextWithActivity(object activity)
        {
            if (OperationContext.Current != null && activity != null)
            { 
                OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationActivityKey] = activity;
            } 
        } 

        static internal object ExtractAsyncOperationContextActivity() 
        {
            object data = null;
            if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationActivityKey, out data))
            { 
                OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationActivityKey);
            } 
            return data; 
        }
 
        internal class TracingAsyncCallbackState
        {
            object innerState;
            Guid activityId; 

            internal TracingAsyncCallbackState(object innerState) 
            { 
                this.innerState = innerState;
                this.activityId = DiagnosticTrace.ActivityId; 
            }

            internal object InnerState
            { 
                get { return this.innerState; }
            } 
 
            internal Guid ActivityId
            { 
                get { return this.activityId; }
            }
        }
 
        internal static AsyncCallback WrapExecuteUserCodeAsyncCallback(AsyncCallback callback)
        { 
            return (DiagnosticUtility.ShouldUseActivity && callback != null) ? 
                (new ExecuteUserCodeAsync(callback)).Callback
                : callback; 
        }

        sealed class ExecuteUserCodeAsync
        { 
            AsyncCallback callback;
 
            public ExecuteUserCodeAsync(AsyncCallback callback) 
            {
                this.callback = callback; 
            }

            public AsyncCallback Callback
            { 
                get
                { 
                    return DiagnosticUtility.ThunkAsyncCallback(new AsyncCallback(this.ExecuteUserCode)); 
                }
            } 

            void ExecuteUserCode(IAsyncResult result)
            {
                using (ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity()) 
                {
                    ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityCallback), ActivityType.ExecuteUserCode); 
                    this.callback(result); 
                }
            } 
        }

    }
} 

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.
                        

Link Menu

Network programming in C#, Network Programming in VB.NET, Network Programming in .NET
This book is available now!
Buy at Amazon US or
Buy at Amazon UK