Esempio n. 1
0
        static PerformanceCounters()
        {
            PerformanceCounterScope performanceCountersFromConfig = GetPerformanceCountersFromConfig();

            if (performanceCountersFromConfig != PerformanceCounterScope.Off)
            {
                try
                {
                    if (performanceCountersFromConfig == PerformanceCounterScope.Default)
                    {
                        performanceCountersFromConfig = OSEnvironmentHelper.IsVistaOrGreater ? PerformanceCounterScope.ServiceOnly : PerformanceCounterScope.Off;
                    }
                    scope = performanceCountersFromConfig;
                }
                catch (SecurityException exception)
                {
                    scope = PerformanceCounterScope.Off;
                    if (DiagnosticUtility.ShouldTraceWarning)
                    {
                        DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
                        TraceUtility.TraceEvent(TraceEventType.Warning, 0x80038, System.ServiceModel.SR.GetString("PartialTrustPerformanceCountersNotEnabled"));
                    }
                }
            }
            else
            {
                scope = PerformanceCounterScope.Off;
            }
        }
        internal DefaultPerformanceCounters(ServiceHostBase serviceHost)
        {
            this.instanceName = DefaultPerformanceCounters.CreateFriendlyInstanceName(serviceHost);
            this.Counters     = new PerformanceCounter[(int)PerfCounters.TotalCounters];
            for (int i = 0; i < (int)PerfCounters.TotalCounters; i++)
            {
                try
                {
                    PerformanceCounter counter = PerformanceCounters.GetDefaultPerformanceCounter(this.perfCounterNames[i], this.instanceName);
                    if (counter != null)
                    {
                        this.Counters[i] = counter;
                    }
                    else
                    {
                        break;
                    }
                }
#pragma warning suppress 56500 // covered by FxCOP
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    if (DiagnosticUtility.ShouldTraceError)
                    {
                        TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.PerformanceCountersFailedForService,
                                                SR.GetString(SR.TraceCodePerformanceCountersFailedForService), null, e);
                    }
                    break;
                }
            }
        }
 internal OperationPerformanceCounters(string service, string contract, string operationName, string uri) : base(service, contract, operationName, uri)
 {
     this.Counters = new PerformanceCounter[15];
     for (int i = 0; i < 15; i++)
     {
         PerformanceCounter operationPerformanceCounter = PerformanceCounters.GetOperationPerformanceCounter(OperationPerformanceCountersBase.perfCounterNames[i], base.instanceName);
         if (operationPerformanceCounter == null)
         {
             break;
         }
         try
         {
             operationPerformanceCounter.RawValue = 0L;
             this.Counters[i] = operationPerformanceCounter;
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             if (DiagnosticUtility.ShouldTraceError)
             {
                 TraceUtility.TraceEvent(TraceEventType.Error, 0x80038, System.ServiceModel.SR.GetString("TraceCodePerformanceCounterFailedToLoad"), null, exception);
             }
             break;
         }
     }
 }
Esempio n. 4
0
        static PerformanceCounters()
        {
            PerformanceCounterScope scope = GetPerformanceCountersFromConfig();

            if (PerformanceCounterScope.Off != scope)
            {
                try
                {
                    if (scope == PerformanceCounterScope.Default)
                    {
                        scope = OSEnvironmentHelper.IsVistaOrGreater ? PerformanceCounterScope.ServiceOnly : PerformanceCounterScope.Off;
                    }
                    PerformanceCounters.scope = scope;
                }
                catch (SecurityException securityException)
                {
                    //switch off the counters - not supported in PT
                    PerformanceCounters.scope = PerformanceCounterScope.Off;

                    // not re-throwing on purpose
                    DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
                    if (DiagnosticUtility.ShouldTraceWarning)
                    {
                        TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning,
                                                TraceCode.PerformanceCounterFailedToLoad,
                                                SR.GetString(SR.PartialTrustPerformanceCountersNotEnabled));
                    }
                }
            }
            else
            {
                PerformanceCounters.scope = PerformanceCounterScope.Off;
            }
        }
        private static void LogInternal(MessageLogTraceRecord record)
        {
            PlainXmlWriter writer = new PlainXmlWriter(MaxMessageSize);

            try
            {
                record.WriteTo(writer);
                writer.Close();
                TraceXPathNavigator data = writer.Navigator;
                if (((messageTraceSource != null) && !messageTraceSource.ShouldLogPii) || !LogKnownPii)
                {
                    data.RemovePii(PiiHeadersPaths);
                    if ((LogMessageBody && (record.Message != null)) && HasSecurityAction(record.Message))
                    {
                        data.RemovePii(PiiBodyPaths);
                    }
                }
                LogInternal(record.MessageLoggingSource, data);
            }
            catch (PlainXmlWriter.MaxSizeExceededException)
            {
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning, 0x2000b, System.ServiceModel.SR.GetString("TraceCodeMessageNotLoggedQuotaExceeded"), record.Message);
                }
            }
        }
        internal static Guid ExtractActivityId(Message message)
        {
            Guid empty = Guid.Empty;

            try
            {
                if (((message == null) || (message.State == MessageState.Closed)) || (message.Headers == null))
                {
                    return(empty);
                }
                int headerIndex = message.Headers.FindHeader("ActivityId", "http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics");
                if (headerIndex < 0)
                {
                    return(empty);
                }
                using (XmlDictionaryReader reader = message.Headers.GetReaderAtHeader(headerIndex))
                {
                    empty = reader.ReadElementContentAsGuid();
                }
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                if (DiagnosticUtility.ShouldTraceError)
                {
                    TraceUtility.TraceEvent(TraceEventType.Error, 0x20007, System.ServiceModel.SR.GetString("TraceCodeFailedToReadAnActivityIdHeader"), null, exception);
                }
            }
            return(empty);
        }
Esempio n. 7
0
        static void IncrementLoggedMessagesCount(object data)
        {
            if (MessageLogger.numberOfMessagesToLog > 0)
            {
                lock (MessageLogger.syncObject)
                {
                    if (MessageLogger.numberOfMessagesToLog > 0)
                    {
                        MessageLogger.numberOfMessagesToLog--;
                        if (0 == MessageLogger.numberOfMessagesToLog)
                        {
                            if (DiagnosticUtility.ShouldTraceInformation)
                            {
                                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.MessageCountLimitExceeded,
                                                        SR.GetString(SR.TraceCodeMessageCountLimitExceeded), data);
                            }
                        }
                    }
                }
            }

            lock (MessageLogger.syncObject)
            {
                if (!MessageLogger.lastWriteSucceeded)
                {
                    MessageLogger.lastWriteSucceeded = true;
                }
            }
        }
Esempio n. 8
0
        static internal OperationPerformanceCountersBase CreateOperationCounters(string service, string contract, string operationName, string uri)
        {
            if (!CheckPermissions())
            {
                return(null);
            }

            if (OSEnvironmentHelper.IsVistaOrGreater)
            {
                try
                {
                    return(new OperationPerformanceCountersV2(service, contract, operationName, uri));
                }
#pragma warning suppress 56500 // covered by FxCOP
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    PerformanceCounters.Scope = PerformanceCounterScope.Off;
                    if (DiagnosticUtility.ShouldTraceError)
                    {
                        TraceUtility.TraceEvent(TraceEventType.Error,
                                                TraceCode.PerformanceCountersFailedForService,
                                                SR.GetString(SR.TraceCodePerformanceCountersFailedForService),
                                                null, e);
                    }
                    return(null);
                }
            }
            return(new OperationPerformanceCounters(service, contract, operationName, uri));
        }
Esempio n. 9
0
        internal static void EnsureInitialized()
        {
            lock (MessageLogger.syncObject)
            {
                if (!MessageLogger.initialized && !MessageLogger.initializing)
                {
                    try
                    {
                        Initialize();
                    }
#pragma warning suppress 56500 // covered by FxCOP
                    catch (SecurityException securityException)
                    {
                        // message logging is not support in PT, write the trace
                        MessageLogger.inPartialTrust = true;
                        if (DiagnosticUtility.ShouldTraceWarning)
                        {
                            TraceUtility.TraceEvent(TraceEventType.Warning,
                                                    TraceCode.TraceHandledException,
                                                    SR.GetString(SR.PartialTrustMessageLoggingNotEnabled),
                                                    null,
                                                    securityException);
                        }
                        // also write to event log
                        LogNonFatalInitializationException(
                            new SecurityException(
                                SR.GetString(SR.PartialTrustMessageLoggingNotEnabled),
                                securityException));
                    }
                    MessageLogger.initialized = true;
                }
            }
        }
 internal static ServicePerformanceCountersBase CreateServiceCounters(ServiceHostBase serviceHost)
 {
     if (OSEnvironmentHelper.IsVistaOrGreater)
     {
         try
         {
             ServicePerformanceCountersV2 sv = new ServicePerformanceCountersV2(serviceHost);
             EndpointPerformanceCountersV2.EnsureCounterSet();
             OperationPerformanceCountersV2.EnsureCounterSet();
             return(sv);
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             PerformanceCounters.Scope = PerformanceCounterScope.Off;
             if (DiagnosticUtility.ShouldTraceError)
             {
                 TraceUtility.TraceEvent(TraceEventType.Error, 0x8003b, System.ServiceModel.SR.GetString("TraceCodePerformanceCountersFailedForService"), null, exception);
             }
             return(null);
         }
     }
     return(new ServicePerformanceCounters(serviceHost));
 }
Esempio n. 11
0
 internal DefaultPerformanceCounters(ServiceHostBase serviceHost)
 {
     this.instanceName = CreateFriendlyInstanceName(serviceHost);
     this.Counters     = new PerformanceCounter[1];
     for (int i = 0; i < 1; i++)
     {
         try
         {
             PerformanceCounter defaultPerformanceCounter = PerformanceCounters.GetDefaultPerformanceCounter(this.perfCounterNames[i], this.instanceName);
             if (defaultPerformanceCounter != null)
             {
                 this.Counters[i] = defaultPerformanceCounter;
                 continue;
             }
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             if (DiagnosticUtility.ShouldTraceError)
             {
                 TraceUtility.TraceEvent(TraceEventType.Error, 0x8003b, System.ServiceModel.SR.GetString("TraceCodePerformanceCountersFailedForService"), null, exception);
             }
         }
         break;
     }
 }
Esempio n. 12
0
 internal ServicePerformanceCounters(ServiceHostBase serviceHost) : base(serviceHost)
 {
     this.Counters = new PerformanceCounter[0x27];
     for (int i = 0; i < 0x27; i++)
     {
         PerformanceCounter servicePerformanceCounter = PerformanceCounters.GetServicePerformanceCounter(ServicePerformanceCountersBase.perfCounterNames[i], this.InstanceName);
         if (servicePerformanceCounter == null)
         {
             break;
         }
         try
         {
             servicePerformanceCounter.RawValue = 0L;
             this.Counters[i] = servicePerformanceCounter;
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             if (DiagnosticUtility.ShouldTraceError)
             {
                 TraceUtility.TraceEvent(TraceEventType.Error, 0x8003b, System.ServiceModel.SR.GetString("TraceCodePerformanceCountersFailedForService"), null, exception);
             }
             break;
         }
     }
 }
        internal EndpointPerformanceCounters(string service, string contract, string uri)
            : base(service, contract, uri)
        {
            this.Counters = new PerformanceCounter[(int)PerfCounters.TotalCounters];
            for (int i = 0; i < (int)PerfCounters.TotalCounters; i++)
            {
                PerformanceCounter counter = PerformanceCounters.GetEndpointPerformanceCounter(perfCounterNames[i], this.instanceName);
                if (counter != null)
                {
                    try
                    {
                        counter.RawValue = 0;
                        this.Counters[i] = counter;
                    }
#pragma warning suppress 56500 // covered by FxCOP
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        if (DiagnosticUtility.ShouldTraceError)
                        {
                            TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.PerformanceCounterFailedToLoad,
                                                    SR.GetString(SR.TraceCodePerformanceCounterFailedToLoad), null, e);
                        }
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
        }
Esempio n. 14
0
 internal static void TracePerformanceCounterUpdateFailure(string instanceName, string perfCounterName)
 {
     if (DiagnosticUtility.ShouldTraceError)
     {
         TraceUtility.TraceEvent(TraceEventType.Error, 0x8003a, System.ServiceModel.SR.GetString("TraceCodePerformanceCountersFailedDuringUpdate", new object[] { perfCounterName + "::" + instanceName }));
     }
 }
 internal override void WriteTo(XmlWriter xml)
 {
     if (((this.message != null) && (this.message.State != MessageState.Closed)) && (this.message.Headers != null))
     {
         try
         {
             xml.WriteStartElement("MessageProperties");
             if (this.message.Properties.Encoder != null)
             {
                 xml.WriteElementString("Encoder", this.message.Properties.Encoder.ToString());
             }
             xml.WriteElementString("AllowOutputBatching", this.message.Properties.AllowOutputBatching.ToString());
             if ((this.message.Properties.Security != null) && (this.message.Properties.Security.ServiceSecurityContext != null))
             {
                 xml.WriteStartElement("Security");
                 xml.WriteElementString("IsAnonymous", this.message.Properties.Security.ServiceSecurityContext.IsAnonymous.ToString());
                 xml.WriteElementString("WindowsIdentityUsed", ((this.message.Properties.Security.ServiceSecurityContext.WindowsIdentity != null) && !string.IsNullOrEmpty(this.message.Properties.Security.ServiceSecurityContext.WindowsIdentity.Name)).ToString());
                 if (DiagnosticUtility.ShouldTraceVerbose)
                 {
                     xml.WriteStartElement("Claims");
                     AuthorizationContext authorizationContext = this.message.Properties.Security.ServiceSecurityContext.AuthorizationContext;
                     for (int j = 0; j < authorizationContext.ClaimSets.Count; j++)
                     {
                         ClaimSet set = authorizationContext.ClaimSets[j];
                         xml.WriteStartElement("ClaimSet");
                         xml.WriteAttributeString("ClrType", base.XmlEncode(set.GetType().AssemblyQualifiedName));
                         for (int k = 0; k < set.Count; k++)
                         {
                             SecurityTraceRecordHelper.WriteClaim(xml, set[k]);
                         }
                         xml.WriteEndElement();
                     }
                     xml.WriteEndElement();
                 }
                 xml.WriteEndElement();
             }
             if (this.message.Properties.Via != null)
             {
                 xml.WriteElementString("Via", this.message.Properties.Via.ToString());
             }
             xml.WriteEndElement();
             xml.WriteStartElement("MessageHeaders");
             for (int i = 0; i < this.message.Headers.Count; i++)
             {
                 this.message.Headers.WriteHeader(i, xml);
             }
             xml.WriteEndElement();
         }
         catch (CommunicationException exception)
         {
             if (DiagnosticUtility.ShouldTraceInformation)
             {
                 TraceUtility.TraceEvent(TraceEventType.Information, 0x2000a, System.ServiceModel.SR.GetString("TraceCodeDiagnosticsFailedMessageTrace"), (Exception)exception, this.message);
             }
         }
     }
 }
Esempio n. 16
0
        static void InitializeMessageTraceSource()
        {
            try
            {
                MessageLogger.attemptedTraceSourceInitialization = true;
                PiiTraceSource tempSource = new PiiTraceSource(MessageLogger.MessageTraceSourceName, DiagnosticUtility.EventSourceName);
                tempSource.Switch.Level = SourceLevels.Information;
                tempSource.Listeners.Remove(MessageLogger.DefaultTraceListenerName);
                if (tempSource.Listeners.Count > 0)
                {
                    AppDomain.CurrentDomain.DomainUnload       += new EventHandler(ExitOrUnloadEventHandler);
                    AppDomain.CurrentDomain.ProcessExit        += new EventHandler(ExitOrUnloadEventHandler);
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExitOrUnloadEventHandler);
                }
                else
                {
                    tempSource = null;
                }

                MessageLogger.messageTraceSource = tempSource;
            }
            catch (System.Configuration.ConfigurationErrorsException)
            {
                throw;
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (SecurityException securityException)
            {
                // message logging is not support in PT, write the trace
                MessageLogger.inPartialTrust = true;
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning,
                                            TraceCode.TraceHandledException,
                                            SR.GetString(SR.PartialTrustMessageLoggingNotEnabled),
                                            null,
                                            securityException);
                }
                // also write to event log
                LogNonFatalInitializationException(
                    new SecurityException(
                        SR.GetString(SR.PartialTrustMessageLoggingNotEnabled),
                        securityException));
            }
            catch (Exception e)
            {
                MessageLogger.messageTraceSource = null;

                if (Fx.IsFatal(e))
                {
                    throw;
                }

                LogNonFatalInitializationException(e);
            }
        }
Esempio n. 17
0
 static internal void TracePerformanceCounterUpdateFailure(string instanceName, string perfCounterName)
 {
     if (DiagnosticUtility.ShouldTraceError)
     {
         TraceUtility.TraceEvent(
             System.Diagnostics.TraceEventType.Error,
             TraceCode.PerformanceCountersFailedDuringUpdate,
             SR.GetString(SR.TraceCodePerformanceCountersFailedDuringUpdate, perfCounterName + "::" + instanceName));
     }
 }
Esempio n. 18
0
        static bool MatchFilters(Message message, MessageLoggingSource source)
        {
            bool result = true;

            if (MessageLogger.FilterMessages && (source & MessageLoggingSource.Malformed) == 0)
            {
                result = false;
                List <XPathMessageFilter> filtersToRemove = new List <XPathMessageFilter>();
                lock (MessageLogger.syncObject)
                {
                    foreach (XPathMessageFilter filter in MessageLogger.Filters)
                    {
                        try
                        {
                            if (filter.Match(message))
                            {
                                result = true;
                                break;
                            }
                        }
                        catch (FilterInvalidBodyAccessException)
                        {
                            filtersToRemove.Add(filter);
                        }
                        catch (MessageFilterException e)
                        {
                            if (DiagnosticUtility.ShouldTraceInformation)
                            {
                                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.FilterNotMatchedNodeQuotaExceeded,
                                                        SR.GetString(SR.TraceCodeFilterNotMatchedNodeQuotaExceeded), e, message);
                            }
                        }
                    }

                    foreach (XPathMessageFilter filter in filtersToRemove)
                    {
                        MessageLogger.Filters.Remove(filter);
                        PlainXmlWriter writer = new PlainXmlWriter();
                        filter.WriteXPathTo(writer, null, ConfigurationStrings.Filter, null, true);
                        DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                                                            (ushort)System.Runtime.Diagnostics.EventLogCategory.MessageLogging,
                                                            (uint)System.Runtime.Diagnostics.EventLogEventId.RemovedBadFilter,
                                                            writer.Navigator.ToString());
                    }

                    if (MessageLogger.FilterCount == 0)
                    {
                        result = true;
                    }
                }
            }

            return(result);
        }
        private static bool MatchFilters(Message message, MessageLoggingSource source)
        {
            bool flag = true;

            if (FilterMessages && ((source & MessageLoggingSource.Malformed) == MessageLoggingSource.None))
            {
                flag = false;
                List <XPathMessageFilter> list = new List <XPathMessageFilter>();
                lock (syncObject)
                {
                    foreach (XPathMessageFilter filter in Filters)
                    {
                        try
                        {
                            if (filter.Match(message))
                            {
                                flag = true;
                                break;
                            }
                        }
                        catch (FilterInvalidBodyAccessException)
                        {
                            list.Add(filter);
                        }
                        catch (MessageFilterException exception)
                        {
                            if (DiagnosticUtility.ShouldTraceInformation)
                            {
                                TraceUtility.TraceEvent(TraceEventType.Information, 0x20008, System.ServiceModel.SR.GetString("TraceCodeFilterNotMatchedNodeQuotaExceeded"), (Exception)exception, message);
                            }
                        }
                    }
                    foreach (XPathMessageFilter filter2 in list)
                    {
                        Filters.Remove(filter2);
                        PlainXmlWriter writer = new PlainXmlWriter();
                        filter2.WriteXPathTo(writer, null, "filter", null, true);
                        DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.MessageLogging, (EventLogEventId)(-1073610746), new string[] { writer.Navigator.ToString() });
                    }
                    if (FilterCount == 0)
                    {
                        flag = true;
                    }
                }
            }
            return(flag);
        }
 private static void InitializeMessageTraceSource()
 {
     try
     {
         attemptedTraceSourceInitialization = true;
         PiiTraceSource source = new PiiTraceSource("System.ServiceModel.MessageLogging", "System.ServiceModel 4.0.0.0")
         {
             Switch = { Level = SourceLevels.Information }
         };
         source.Listeners.Remove("Default");
         if (source.Listeners.Count > 0)
         {
             AppDomain.CurrentDomain.DomainUnload       += new EventHandler(MessageLogger.ExitOrUnloadEventHandler);
             AppDomain.CurrentDomain.ProcessExit        += new EventHandler(MessageLogger.ExitOrUnloadEventHandler);
             AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MessageLogger.ExitOrUnloadEventHandler);
         }
         else
         {
             source = null;
         }
         messageTraceSource = source;
     }
     catch (ConfigurationErrorsException)
     {
         throw;
     }
     catch (SecurityException exception)
     {
         inPartialTrust = true;
         if (DiagnosticUtility.ShouldTraceWarning)
         {
             TraceUtility.TraceEvent(TraceEventType.Warning, 0x20004, System.ServiceModel.SR.GetString("PartialTrustMessageLoggingNotEnabled"), null, exception);
         }
         LogNonFatalInitializationException(new SecurityException(System.ServiceModel.SR.GetString("PartialTrustMessageLoggingNotEnabled"), exception));
     }
     catch (Exception exception2)
     {
         messageTraceSource = null;
         if (Fx.IsFatal(exception2))
         {
             throw;
         }
         LogNonFatalInitializationException(exception2);
     }
 }
Esempio n. 21
0
        /// <summary>
        /// Returns true if we're running in full trust. Otherwise turns off performance counters and returns false.
        /// </summary>
        private static bool CheckPermissions()
        {
            // At this time (.net 4.5), performance counters require Unrestricted permissions to be created.
            if (PartialTrustHelpers.AppDomainFullyTrusted)
            {
                return(true);
            }

            PerformanceCounters.Scope = PerformanceCounterScope.Off;

            if (DiagnosticUtility.ShouldTraceWarning)
            {
                TraceUtility.TraceEvent(TraceEventType.Warning,
                                        TraceCode.PerformanceCountersFailedForService,
                                        SR.GetString(SR.PartialTrustPerformanceCountersNotEnabled));
            }

            return(false);
        }
Esempio n. 22
0
        internal static bool ExtractActivityAndCorrelationId(Message message, out Guid activityId, out Guid correlationId)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            activityId    = Guid.Empty;
            correlationId = Guid.Empty;

            try
            {
                if (message.State != MessageState.Closed && message.Headers != null)
                {
                    int index = message.Headers.FindHeader(DiagnosticStrings.ActivityId, DiagnosticStrings.DiagnosticsNamespace);

                    // Check the state again, in case the message was closed after we found the header
                    if (index >= 0)
                    {
                        using (XmlDictionaryReader reader = message.Headers.GetReaderAtHeader(index))
                        {
                            correlationId = Fx.CreateGuid(reader.GetAttribute("CorrelationId", null));
                            activityId    = reader.ReadElementContentAsGuid();
                            return(activityId != Guid.Empty);
                        }
                    }
                }
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                if (DiagnosticUtility.ShouldTraceError)
                {
                    TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToReadAnActivityIdHeader,
                                            SR.GetString(SR.TraceCodeFailedToReadAnActivityIdHeader), null, e);
                }
            }
            return(false);
        }
        static internal ServicePerformanceCountersBase CreateServiceCounters(ServiceHostBase serviceHost)
        {
            if (!CheckPermissions())
            {
                return(null);
            }

            if (OSEnvironmentHelper.IsVistaOrGreater)
            {
                try
                {
                    EnsureCategoriesExistIfNeeded();
                    var counters = new ServicePerformanceCountersV2(serviceHost);
                    // Workaround Sys.Diag.PerformanceData problem:
                    // Ensure that all three categories are initialized so other processes can still
                    // expose endpoint/operation perf counters event if this one doesn't
                    EndpointPerformanceCountersV2.EnsureCounterSet();
                    OperationPerformanceCountersV2.EnsureCounterSet();
                    return(counters);
                }
#pragma warning suppress 56500 // covered by FxCOP
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    PerformanceCounters.Scope = PerformanceCounterScope.Off;
                    if (DiagnosticUtility.ShouldTraceError)
                    {
                        TraceUtility.TraceEvent(TraceEventType.Error,
                                                TraceCode.PerformanceCountersFailedForService,
                                                SR.GetString(SR.TraceCodePerformanceCountersFailedForService),
                                                null, e);
                    }
                    return(null);
                }
            }
            return(new ServicePerformanceCounters(serviceHost));
        }
 internal static void EnsureInitialized()
 {
     lock (syncObject)
     {
         if (!initialized && !initializing)
         {
             try
             {
                 Initialize();
             }
             catch (SecurityException exception)
             {
                 inPartialTrust = true;
                 if (DiagnosticUtility.ShouldTraceWarning)
                 {
                     TraceUtility.TraceEvent(TraceEventType.Warning, 0x20004, System.ServiceModel.SR.GetString("PartialTrustMessageLoggingNotEnabled"), null, exception);
                 }
                 LogNonFatalInitializationException(new SecurityException(System.ServiceModel.SR.GetString("PartialTrustMessageLoggingNotEnabled"), exception));
             }
             initialized = true;
         }
     }
 }
 internal static bool ExtractActivityAndCorrelationId(Message message, out Guid activityId, out Guid correlationId)
 {
     if (message == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
     }
     activityId    = Guid.Empty;
     correlationId = Guid.Empty;
     try
     {
         if ((message.State != MessageState.Closed) && (message.Headers != null))
         {
             int headerIndex = message.Headers.FindHeader("ActivityId", "http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics");
             if (headerIndex >= 0)
             {
                 using (XmlDictionaryReader reader = message.Headers.GetReaderAtHeader(headerIndex))
                 {
                     correlationId = Fx.CreateGuid(reader.GetAttribute("CorrelationId", null));
                     activityId    = reader.ReadElementContentAsGuid();
                     return(activityId != Guid.Empty);
                 }
             }
         }
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         if (DiagnosticUtility.ShouldTraceError)
         {
             TraceUtility.TraceEvent(TraceEventType.Error, 0x20007, System.ServiceModel.SR.GetString("TraceCodeFailedToReadAnActivityIdHeader"), null, exception);
         }
     }
     return(false);
 }
Esempio n. 26
0
        static void LogInternal(MessageLogTraceRecord record)
        {
            Fx.Assert(null != record, "record cannot be null");

            PlainXmlWriter xmlWriter = new PlainXmlWriter(MessageLogger.MaxMessageSize);

            try
            {
                record.WriteTo(xmlWriter);
                xmlWriter.Close();
                TraceXPathNavigator navigator = xmlWriter.Navigator;

                if ((MessageLogger.messageTraceSource != null &&
                     !MessageLogger.messageTraceSource.ShouldLogPii) ||
                    !MessageLogger.LogKnownPii)
                {
                    navigator.RemovePii(MessageLogger.PiiHeadersPaths);
                    if (MessageLogger.LogMessageBody && null != record.Message)
                    {
                        if (HasSecurityAction(record.Message))
                        {
                            navigator.RemovePii(MessageLogger.PiiBodyPaths);
                        }
                    }
                }

                LogInternal(record.MessageLoggingSource, navigator);
            }
            catch (PlainXmlWriter.MaxSizeExceededException)
            {
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.MessageNotLoggedQuotaExceeded,
                                            SR.GetString(SR.TraceCodeMessageNotLoggedQuotaExceeded), record.Message);
                }
            }
        }
 internal static EndpointPerformanceCountersBase CreateEndpointCounters(string service, string contract, string uri)
 {
     if (OSEnvironmentHelper.IsVistaOrGreater)
     {
         try
         {
             return(new EndpointPerformanceCountersV2(service, contract, uri));
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             PerformanceCounters.Scope = PerformanceCounterScope.Off;
             if (DiagnosticUtility.ShouldTraceError)
             {
                 TraceUtility.TraceEvent(TraceEventType.Error, 0x8003b, System.ServiceModel.SR.GetString("TraceCodePerformanceCountersFailedForService"), null, exception);
             }
             return(null);
         }
     }
     return(new EndpointPerformanceCounters(service, contract, uri));
 }
 private static void IncrementLoggedMessagesCount(object data)
 {
     if (numberOfMessagesToLog > 0)
     {
         lock (syncObject)
         {
             if (numberOfMessagesToLog > 0)
             {
                 numberOfMessagesToLog--;
                 if ((numberOfMessagesToLog == 0) && DiagnosticUtility.ShouldTraceInformation)
                 {
                     TraceUtility.TraceEvent(TraceEventType.Information, 0x20009, System.ServiceModel.SR.GetString("TraceCodeMessageCountLimitExceeded"), data);
                 }
             }
         }
     }
     lock (syncObject)
     {
         if (!lastWriteSucceeded)
         {
             lastWriteSucceeded = true;
         }
     }
 }
Esempio n. 29
0
        internal static Guid ExtractActivityId(Message message)
        {
            Guid guid = Guid.Empty;

            try
            {
                if (message != null && message.State != MessageState.Closed && message.Headers != null)
                {
                    int index = message.Headers.FindHeader(DiagnosticStrings.ActivityId, DiagnosticStrings.DiagnosticsNamespace);

                    // Check the state again, in case the message was closed after we found the header
                    if (index >= 0)
                    {
                        using (XmlDictionaryReader reader = message.Headers.GetReaderAtHeader(index))
                        {
                            guid = reader.ReadElementContentAsGuid();
                        }
                    }
                }
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }
                if (DiagnosticUtility.ShouldTraceError)
                {
                    TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToReadAnActivityIdHeader,
                                            SR.GetString(SR.TraceCodeFailedToReadAnActivityIdHeader), null, e);
                }
            }

            return(guid);
        }
        // If EnsureUniquePerformanceCounterInstanceName is enabled, PerformanceCountersBase.cs will be checking if instances
        // exist in each of these categories, so we need to ensure the categories all exist. This works around System.Diagnostics
        // calls using PerformanceCounterLib to cache which categories do/don't exist.
        private static void EnsureCategoriesExistIfNeeded()
        {
            if (categoriesExist || !ServiceModelAppSettings.EnsureUniquePerformanceCounterInstanceNames)
            {
                return;
            }

            OperationPerformanceCountersV2 operationCounter = null;
            EndpointPerformanceCountersV2  endpointCounter  = null;
            ServicePerformanceCountersV2   serviceCounter   = null;

            try
            {
                if (PerformanceCounterCategory.Exists(PerformanceCounterStrings.SERVICEMODELOPERATION.OperationPerfCounters) &&
                    PerformanceCounterCategory.Exists(PerformanceCounterStrings.SERVICEMODELENDPOINT.EndpointPerfCounters) &&
                    PerformanceCounterCategory.Exists(PerformanceCounterStrings.SERVICEMODELSERVICE.ServicePerfCounters))
                {
                    categoriesExist = true;
                    return;
                }

                // Categories do not exist. Update PerformanceCounterLib's cache using dummy counters.
                const string dummyValue = "_WCF_Admin";


                // Older operating systems (such as windows 7) report the category as not existing unless a counter instance
                // has been created in it. Create one instance in each of the categories to ensure they will exist in the cache
                // that System.Diagnostics calls use.
                ServiceHost dummyServiceHost = new ServiceHost(typeof(object), new Uri("http://" + dummyValue));
                operationCounter = new OperationPerformanceCountersV2(dummyValue, dummyValue, dummyValue, dummyValue);
                endpointCounter  = new EndpointPerformanceCountersV2(dummyValue, dummyValue, dummyValue);
                serviceCounter   = new ServicePerformanceCountersV2(dummyServiceHost);

                // Throw away cached categories, then read from the categories to cause the cache to be repopulated.
                PerformanceCounter.CloseSharedResources();
                PerformanceCounterCategory.Exists(dummyValue);
            }
            catch (UnauthorizedAccessException)
            {
                // Don't have permission to read performance counters. Trace a warning.
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning,
                                            TraceCode.PerformanceCountersFailedForService,
                                            SR.GetString(SR.EnsureCategoriesExistFailedPermission));
                }
            }
            catch
            {
                // Failed to ensure all of the categories exist. Catch the exception and try to create the counter anyway.
            }
            finally
            {
                // Delete the dummy counters, we don't need them anymore.
                if (operationCounter != null)
                {
                    operationCounter.DeleteInstance();
                }

                if (endpointCounter != null)
                {
                    endpointCounter.DeleteInstance();
                }

                if (serviceCounter != null)
                {
                    serviceCounter.DeleteInstance();
                }

                categoriesExist = true;
            }
        }