Imported Upstream version 4.6.0.125

Former-commit-id: a2155e9bd80020e49e72e86c44da02a8ac0e57a4
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2016-08-03 10:59:49 +00:00
parent a569aebcfd
commit e79aa3c0ed
17047 changed files with 3137615 additions and 392334 deletions

View File

@@ -0,0 +1,52 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Runtime.Diagnostics;
class Activity : IDisposable
{
protected Guid parentId;
Guid currentId;
bool mustDispose = false;
protected Activity(Guid activityId, Guid parentId)
{
this.currentId = activityId;
this.parentId = parentId;
this.mustDispose = true;
DiagnosticTraceBase.ActivityId = this.currentId;
}
internal static Activity CreateActivity(Guid activityId)
{
Activity retval = null;
if (activityId != Guid.Empty)
{
Guid currentActivityId = DiagnosticTraceBase.ActivityId;
if (activityId != currentActivityId)
{
retval = new Activity(activityId, currentActivityId);
}
}
return retval;
}
public virtual void Dispose()
{
if (this.mustDispose)
{
this.mustDispose = false;
DiagnosticTraceBase.ActivityId = this.parentId;
}
GC.SuppressFinalize(this);
}
protected Guid Id
{
get { return this.currentId; }
}
}
}

View File

@@ -0,0 +1,46 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
static class DiagnosticStrings
{
internal const string DiagnosticsNamespace = "http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics";
internal const string ActivityIdName = "E2ETrace.ActivityID";
internal const string ActivityId = "ActivityId";
internal const string AppDomain = "AppDomain";
internal const string DataTag = "Data";
internal const string DataItemsTag = "DataItems";
internal const string DeflateCookieAfterDeflatingTag = "AfterDeflating";
internal const string DeflateCookieOriginalSizeTag = "OriginalSize";
internal const string DescriptionTag = "Description";
internal const string EventLogTag = "EventLog";
internal const string ExceptionTag = "Exception";
internal const string ExceptionTypeTag = "ExceptionType";
internal const string ExceptionStringTag = "ExceptionString";
internal const string ExtendedDataTag = "ExtendedData";
internal const string HeaderTag = "Header";
internal const string InnerExceptionTag = "InnerException";
internal const string KeyTag = "Key";
internal const string MessageTag = "Message";
internal const string NameTag = "Name";
internal const string NamespaceTag = "xmlns";
internal const string NativeErrorCodeTag = "NativeErrorCode";
internal const string ProcessId = "ProcessId";
internal const string ProcessName = "ProcessName";
internal const string RoleTag = "Role";
internal const string SeverityTag = "Severity";
internal const string SourceTag = "Source";
internal const string StackTraceTag = "StackTrace";
internal const string TraceCodeTag = "TraceIdentifier";
internal const string TraceRecordTag = "TraceRecord";
internal const string ValueTag = "Value";
internal static string[][] HeadersPaths = {
new string[] { DiagnosticStrings.TraceRecordTag, DiagnosticStrings.ExtendedDataTag, "MessageHeaders", "Security" },
new string[] { DiagnosticStrings.TraceRecordTag, DiagnosticStrings.ExtendedDataTag, "MessageHeaders", "IssuedTokens" } };
internal static string[] PiiList = new string[] { "BinarySecret", "Entropy", "Password", "Nonce", "Username", "BinarySecurityToken", "NameIdentifier", "SubjectLocality", "AttributeValue" };
}
}

View File

@@ -0,0 +1,55 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Diagnostics;
class DiagnosticTraceSource : PiiTraceSource
{
const string PropagateActivityValue = "propagateActivity";
internal DiagnosticTraceSource(string name, string eventSourceName)
: base(name, eventSourceName)
{
}
internal DiagnosticTraceSource(string name, string eventSourceName, SourceLevels level)
: base(name, eventSourceName, level)
{
}
protected override string[] GetSupportedAttributes()
{
string[] baseAttributes = base.GetSupportedAttributes();
string[] supportedAttributes = new string[baseAttributes.Length + 1];
for (int i = 0; i < baseAttributes.Length; i++)
{
supportedAttributes[i] = baseAttributes[i];
}
supportedAttributes[baseAttributes.Length] = DiagnosticTraceSource.PropagateActivityValue;
return supportedAttributes;
}
internal bool PropagateActivity
{
get
{
bool retval = false;
string attributeValue = this.Attributes[DiagnosticTraceSource.PropagateActivityValue];
if (!string.IsNullOrEmpty(attributeValue))
{
if (!bool.TryParse(attributeValue, out retval))
{
retval = false;
}
}
return retval;
}
set
{
this.Attributes[DiagnosticTraceSource.PropagateActivityValue] = value.ToString();
}
}
}
}

View File

@@ -0,0 +1,18 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
static class DiagnosticsTraceCode
{
// Diagnostic trace codes
public const int Diagnostics = 0X20000;
public const int AppDomainUnload = DiagnosticsTraceCode.Diagnostics | 0X0001; //
public const int EventLog = DiagnosticsTraceCode.Diagnostics | 0X0002; //
public const int ThrowingException = DiagnosticsTraceCode.Diagnostics | 0X0003; //
public const int TraceHandledException = DiagnosticsTraceCode.Diagnostics | 0X0004; //
public const int UnhandledException = DiagnosticsTraceCode.Diagnostics | 0X0005; //
public const int TraceTruncatedQuotaExceeded = DiagnosticsTraceCode.Diagnostics | 0X000C; //
}
}

View File

@@ -0,0 +1,63 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Xml;
using System.Text;
using System.IO;
class EncodingFallbackAwareXmlTextWriter : XmlTextWriter
{
Encoding encoding;
internal EncodingFallbackAwareXmlTextWriter(TextWriter writer)
: base(writer)
{
this.encoding = writer.Encoding;
}
public override void WriteString(string value)
{
if (!string.IsNullOrEmpty(value) &&
ContainsInvalidXmlChar(value))
{
byte[] blob = encoding.GetBytes(value);
value = encoding.GetString(blob);
}
base.WriteString(value);
}
bool ContainsInvalidXmlChar(string value)
{
if (string.IsNullOrEmpty(value))
{
return false;
}
int i = 0;
int len = value.Length;
while (i < len)
{
if (XmlConvert.IsXmlChar(value[i]))
{
i++;
continue;
}
if (i + 1 < len &&
XmlConvert.IsXmlSurrogatePair(value[i + 1], value[i]))
{
i += 2;
continue;
}
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,28 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
// FUTURE: This class is kept so that 4.0 Extended SKU runs fine on 4.5 Client. Will remove this in the future.
// Order is important here. The order must match the order of strings in ..\EventLog\EventLog.mc
[Obsolete("This has been replaced by System.Runtime.Diagnostics.EventLogCategory")]
enum EventLogCategory : ushort
{
ServiceAuthorization = 1, // reserved
MessageAuthentication, // reserved
ObjectAccess, // reserved
Tracing,
WebHost,
FailFast,
MessageLogging,
PerformanceCounter,
Wmi,
ComPlus,
StateMachine,
Wsat,
SharingService,
ListenerAdapter
}
}

View File

@@ -0,0 +1,100 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
// FUTURE: This class is kept so that 4.0 Extended SKU runs fine on 4.5 Client. Will remove this in the future.
// Order is important here. The order must match the order of strings in ..\EventLog\EventLog.mc
[Obsolete("This has been replaced by System.Runtime.Diagnostics.EventLogEventId")]
enum EventLogEventId : uint
{
// EventIDs from shared Diagnostics and Reliability code
FailedToSetupTracing = 0xC0010064,
FailedToInitializeTraceSource,
FailFast,
FailFastException,
FailedToTraceEvent,
FailedToTraceEventWithException,
InvariantAssertionFailed,
PiiLoggingOn,
PiiLoggingNotAllowed,
// ServiceModel EventIDs
WebHostUnhandledException = 0xC0020001,
WebHostHttpError,
WebHostFailedToProcessRequest,
WebHostFailedToListen,
FailedToLogMessage,
RemovedBadFilter,
FailedToCreateMessageLoggingTraceSource,
MessageLoggingOn,
MessageLoggingOff,
FailedToLoadPerformanceCounter,
FailedToRemovePerformanceCounter,
WmiGetObjectFailed,
WmiPutInstanceFailed,
WmiDeleteInstanceFailed,
WmiCreateInstanceFailed,
WmiExecQueryFailed,
WmiExecMethodFailed,
WmiRegistrationFailed,
WmiUnregistrationFailed,
WmiAdminTypeMismatch,
WmiPropertyMissing,
ComPlusServiceHostStartingServiceError,
ComPlusDllHostInitializerStartingError,
ComPlusTLBImportError,
ComPlusInvokingMethodFailed,
ComPlusInstanceCreationError,
ComPlusInvokingMethodFailedMismatchedTransactions,
// TransactionBridge
UnhandledStateMachineExceptionRecordDescription = 0xC0030001,
FatalUnexpectedStateMachineEvent,
ParticipantRecoveryLogEntryCorrupt,
CoordinatorRecoveryLogEntryCorrupt,
CoordinatorRecoveryLogEntryCreationFailure,
ParticipantRecoveryLogEntryCreationFailure,
ProtocolInitializationFailure,
ProtocolStartFailure,
ProtocolRecoveryBeginningFailure,
ProtocolRecoveryCompleteFailure,
TransactionBridgeRecoveryFailure,
ProtocolStopFailure,
NonFatalUnexpectedStateMachineEvent,
PerformanceCounterInitializationFailure,
ProtocolRecoveryComplete,
ProtocolStopped,
ThumbPrintNotFound,
ThumbPrintNotValidated,
SslNoPrivateKey,
SslNoAccessiblePrivateKey,
MissingNecessaryKeyUsage,
MissingNecessaryEnhancedKeyUsage,
// SMSvcHost
StartErrorPublish = 0xC0040001,
BindingError,
LAFailedToListenForApp,
UnknownListenerAdapterError,
WasDisconnected,
WasConnectionTimedout,
ServiceStartFailed,
MessageQueueDuplicatedSocketLeak,
MessageQueueDuplicatedPipeLeak,
SharingUnhandledException,
// SecurityAudit
ServiceAuthorizationSuccess = 0x40060001,
ServiceAuthorizationFailure = 0xC0060002,
MessageAuthenticationSuccess = 0x40060003,
MessageAuthenticationFailure = 0xC0060004,
SecurityNegotiationSuccess = 0x40060005,
SecurityNegotiationFailure = 0xC0060006,
TransportAuthenticationSuccess = 0x40060007,
TransportAuthenticationFailure = 0xC0060008,
ImpersonationSuccess = 0x40060009,
ImpersonationFailure = 0xC006000A
}
}

View File

@@ -0,0 +1,60 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
//
[Obsolete("This has been replaced by System.Runtime.Diagnostics.EventLogger")]
class EventLogger
{
System.Runtime.Diagnostics.EventLogger innerEventLogger;
EventLogger()
{
}
[Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.EventLog instead")]
internal EventLogger(string eventLogSourceName, object diagnosticTrace)
{
this.innerEventLogger = new System.Runtime.Diagnostics.EventLogger(eventLogSourceName, (System.Runtime.Diagnostics.DiagnosticTraceBase)diagnosticTrace);
}
[System.Runtime.Fx.Tag.SecurityNote(Critical = "Calling SecurityCritical method/property")]
[SecurityCritical]
internal static EventLogger UnsafeCreateEventLogger(string eventLogSourceName, object diagnosticTrace)
{
EventLogger logger = new EventLogger();
logger.innerEventLogger = System.Runtime.Diagnostics.EventLogger.UnsafeCreateEventLogger(eventLogSourceName, (System.Runtime.Diagnostics.DiagnosticTraceBase)diagnosticTrace);
return logger;
}
internal void LogEvent(TraceEventType type, EventLogCategory category, EventLogEventId eventId, bool shouldTrace, params string[] values)
{
this.innerEventLogger.LogEvent(type, (ushort)category, (uint)eventId, shouldTrace, values);
}
[System.Runtime.Fx.Tag.SecurityNote(Critical = "Calling SecurityCritical method/property")]
[SecurityCritical]
internal void UnsafeLogEvent(TraceEventType type, EventLogCategory category, EventLogEventId eventId, bool shouldTrace, params string[] values)
{
this.innerEventLogger.UnsafeLogEvent(type, (ushort)category, (uint)eventId,
shouldTrace, values);
}
internal void LogEvent(TraceEventType type, EventLogCategory category, EventLogEventId eventId, params string[] values)
{
this.innerEventLogger.LogEvent(type, (ushort)category, (uint)eventId, values);
}
internal static string NormalizeEventLogParameter(string param)
{
return System.Runtime.Diagnostics.EventLogger.NormalizeEventLogParameter(param);
}
}
}

View File

@@ -0,0 +1,273 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.Serialization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Xml;
class ExceptionUtility
{
const string ExceptionStackAsStringKey = "System.ServiceModel.Diagnostics.ExceptionUtility.ExceptionStackAsString";
// This field should be only used for debug build.
internal static ExceptionUtility mainInstance;
LegacyDiagnosticTrace diagnosticTrace;
ExceptionTrace exceptionTrace;
string name;
string eventSourceName;
[ThreadStatic]
static Guid activityId;
[ThreadStatic]
static bool useStaticActivityId;
[Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.ExceptionUtility instead")]
internal ExceptionUtility(string name, string eventSourceName, object diagnosticTrace, object exceptionTrace)
{
this.diagnosticTrace = (LegacyDiagnosticTrace)diagnosticTrace;
this.exceptionTrace = (ExceptionTrace)exceptionTrace;
this.name = name;
this.eventSourceName = eventSourceName;
}
[Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.ExceptionUtility instead")]
[MethodImpl(MethodImplOptions.NoInlining)]
#pragma warning disable 56500
internal void TraceFailFast(string message)
{
System.Runtime.Diagnostics.EventLogger logger = null;
try
{
#pragma warning disable 618
logger = new System.Runtime.Diagnostics.EventLogger(this.eventSourceName, this.diagnosticTrace);
#pragma warning restore 618
}
finally
{
#pragma warning disable 618
TraceFailFast(message, logger);
#pragma warning restore 618
}
}
// Fail-- Event Log entry will be generated.
// To force a Watson on a dev machine, do the following:
// 1. Set \HKLM\SOFTWARE\Microsoft\PCHealth\ErrorReporting ForceQueueMode = 0
// 2. In the command environment, set COMPLUS_DbgJitDebugLaunchSetting=0
[Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.ExceptionUtility instead")]
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TraceFailFast(string message, System.Runtime.Diagnostics.EventLogger logger)
{
try
{
if (logger != null)
{
string stackTrace = null;
try
{
stackTrace = new StackTrace().ToString();
}
catch (Exception exception)
{
stackTrace = exception.Message;
}
finally
{
logger.LogEvent(TraceEventType.Critical,
(ushort)EventLogCategory.FailFast,
(uint)EventLogEventId.FailFast,
message,
stackTrace);
}
}
}
catch (Exception e)
{
if (logger != null)
{
logger.LogEvent(TraceEventType.Critical,
(ushort)EventLogCategory.FailFast,
(uint)EventLogEventId.FailFastException,
e.ToString());
}
throw;
}
}
#pragma warning restore 56500
[Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.ExceptionUtility instead")]
internal void TraceFailFastException(Exception exception)
{
TraceFailFast(exception == null ? null : exception.ToString());
}
internal Exception ThrowHelper(Exception exception, TraceEventType eventType, TraceRecord extendedData)
{
#pragma warning disable 618
bool shouldTrace = (this.diagnosticTrace != null && this.diagnosticTrace.ShouldTrace(eventType));
#pragma warning restore 618
if (shouldTrace)
{
using (ExceptionUtility.useStaticActivityId ? Activity.CreateActivity(ExceptionUtility.activityId) : null)
{
this.diagnosticTrace.TraceEvent(eventType, DiagnosticsTraceCode.ThrowingException, LegacyDiagnosticTrace.GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", "ThrowingException"), TraceSR.GetString(TraceSR.ThrowingException), extendedData, exception, null);
}
IDictionary data = exception.Data;
if (data != null && !data.IsReadOnly && !data.IsFixedSize)
{
object existingString = data[ExceptionStackAsStringKey];
string stackString = existingString == null ? "" : existingString as string;
if (stackString != null)
{
string stack = exception.StackTrace;
if (!string.IsNullOrEmpty(stack))
{
stackString = string.Concat(stackString, stackString.Length == 0 ? "" : Environment.NewLine, "throw", Environment.NewLine, stack, Environment.NewLine, "catch", Environment.NewLine);
data[ExceptionStackAsStringKey] = stackString;
}
}
}
}
// Trace using ETW as well.
exceptionTrace.TraceEtwException(exception, eventType);
return exception;
}
internal Exception ThrowHelper(Exception exception, TraceEventType eventType)
{
return this.ThrowHelper(exception, eventType, null);
}
internal ArgumentException ThrowHelperArgument(string message)
{
return (ArgumentException)this.ThrowHelperError(new ArgumentException(message));
}
internal ArgumentException ThrowHelperArgument(string paramName, string message)
{
return (ArgumentException)this.ThrowHelperError(new ArgumentException(message, paramName));
}
internal ArgumentNullException ThrowHelperArgumentNull(string paramName)
{
return (ArgumentNullException)this.ThrowHelperError(new ArgumentNullException(paramName));
}
internal ArgumentNullException ThrowHelperArgumentNull(string paramName, string message)
{
return (ArgumentNullException)this.ThrowHelperError(new ArgumentNullException(paramName, message));
}
internal ArgumentException ThrowHelperArgumentNullOrEmptyString(string arg)
{
return (ArgumentException)this.ThrowHelperError(new ArgumentException(TraceSR.GetString(TraceSR.StringNullOrEmpty), arg));
}
internal Exception ThrowHelperFatal(string message, Exception innerException)
{
return this.ThrowHelperError(new FatalException(message, innerException));
}
internal Exception ThrowHelperInternal(bool fatal)
{
return fatal ? Fx.AssertAndThrowFatal("Fatal InternalException should never be thrown.") : Fx.AssertAndThrow("InternalException should never be thrown.");
}
internal Exception ThrowHelperInvalidOperation(string message)
{
return ThrowHelperError(new InvalidOperationException(message));
}
internal Exception ThrowHelperCallback(string message, Exception innerException)
{
return this.ThrowHelperCritical(new CallbackException(message, innerException));
}
internal Exception ThrowHelperCallback(Exception innerException)
{
return this.ThrowHelperCallback(TraceSR.GetString(TraceSR.GenericCallbackException), innerException);
}
internal Exception ThrowHelperCritical(Exception exception)
{
return this.ThrowHelper(exception, TraceEventType.Critical);
}
internal Exception ThrowHelperError(Exception exception)
{
return this.ThrowHelper(exception, TraceEventType.Error);
}
internal Exception ThrowHelperWarning(Exception exception)
{
return this.ThrowHelper(exception, TraceEventType.Warning);
}
internal Exception ThrowHelperXml(XmlReader reader, string message)
{
return this.ThrowHelperXml(reader, message, null);
}
internal Exception ThrowHelperXml(XmlReader reader, string message, Exception inner)
{
IXmlLineInfo lineInfo = reader as IXmlLineInfo;
return this.ThrowHelperError(new XmlException(
message,
inner,
(null != lineInfo) ? lineInfo.LineNumber : 0,
(null != lineInfo) ? lineInfo.LinePosition : 0));
}
internal void DiagnosticTraceHandledException(Exception exception, TraceEventType eventType)
{
#pragma warning disable 618
bool shouldTrace = (this.diagnosticTrace != null && this.diagnosticTrace.ShouldTrace(eventType));
#pragma warning restore 618
if (shouldTrace)
{
using (ExceptionUtility.useStaticActivityId ? Activity.CreateActivity(ExceptionUtility.activityId) : null)
{
this.diagnosticTrace.TraceEvent(eventType, DiagnosticsTraceCode.TraceHandledException, LegacyDiagnosticTrace.GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", "TraceHandledException"), TraceSR.GetString(TraceSR.TraceHandledException), null, exception, null);
}
}
}
// On a single thread, these functions will complete just fine
// and don't need to worry about locking issues because the effected
// variables are ThreadStatic.
internal static void UseActivityId(Guid activityId)
{
ExceptionUtility.activityId = activityId;
ExceptionUtility.useStaticActivityId = true;
}
internal static void ClearActivityId()
{
ExceptionUtility.useStaticActivityId = false;
ExceptionUtility.activityId = Guid.Empty;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static bool IsInfrastructureException(Exception exception)
{
return exception != null && (exception is ThreadAbortException || exception is AppDomainUnloadedException);
}
}
}

View File

@@ -0,0 +1,310 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Xml;
using System.Diagnostics.CodeAnalysis;
class LegacyDiagnosticTrace : DiagnosticTraceBase
{
const int MaxTraceSize = 65535;
bool shouldUseActivity = false;
TraceSourceKind traceSourceType = TraceSourceKind.PiiTraceSource;
const string subType = "";
const string version = "1";
const int traceFailureLogThreshold = 1;
const SourceLevels DefaultLevel = SourceLevels.Off;
static object classLockObject = new object();
protected override void OnSetLevel(SourceLevels level)
{
if (this.TraceSource != null)
{
if (this.TraceSource.Switch.Level != SourceLevels.Off &&
level == SourceLevels.Off)
{
TraceSource temp = this.TraceSource;
this.CreateTraceSource();
temp.Close();
}
this.shouldUseActivity = (level & SourceLevels.ActivityTracing) != 0;
}
}
[Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.ShouldUseActivity instead")]
internal bool ShouldUseActivity
{
get { return this.shouldUseActivity; }
}
#pragma warning disable 56500
[Obsolete("For SMDiagnostics.dll use only. Never 'new' this type up unless you are DiagnosticUtility.")]
[Fx.Tag.SecurityNote(Critical = "Sets eventSourceName.")]
[SecurityCritical]
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "LegacyDiagnosticTrace is an internal class without derived classes")]
internal LegacyDiagnosticTrace(TraceSourceKind sourceType, string traceSourceName, string eventSourceName)
: base(traceSourceName)
{
this.traceSourceType = sourceType;
this.EventSourceName = eventSourceName;
try
{
this.CreateTraceSource();
this.AddDomainEventHandlersForCleanup();
}
#if !NO_CONFIGURATION
catch (ConfigurationErrorsException)
{
throw;
}
#endif
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
System.Runtime.Diagnostics.EventLogger logger = new System.Runtime.Diagnostics.EventLogger(this.EventSourceName, null);
logger.LogEvent(TraceEventType.Error, (ushort)System.Runtime.Diagnostics.EventLogCategory.Tracing, (uint)System.Runtime.Diagnostics.EventLogEventId.FailedToSetupTracing, false,
e.ToString());
}
}
#pragma warning restore 56500
[SecuritySafeCritical]
void CreateTraceSource()
{
PiiTraceSource tempSource = null;
if (this.traceSourceType == TraceSourceKind.PiiTraceSource)
{
tempSource = new PiiTraceSource(this.TraceSourceName, this.EventSourceName, LegacyDiagnosticTrace.DefaultLevel);
}
else
{
tempSource = new DiagnosticTraceSource(this.TraceSourceName, this.EventSourceName, LegacyDiagnosticTrace.DefaultLevel);
}
SetTraceSource(tempSource);
}
#pragma warning disable 56500
internal void TraceEvent(TraceEventType type, int code, string msdnTraceCode, string description, TraceRecord trace, Exception exception, object source)
{
#pragma warning disable 618
Fx.Assert(exception == null || type <= TraceEventType.Information, "Exceptions should be traced at Information or higher");
Fx.Assert(!string.IsNullOrEmpty(description), "All TraceCodes should have a description");
#pragma warning restore 618
TraceXPathNavigator navigator = null;
try
{
#pragma warning disable 618
if (this.TraceSource != null && this.HaveListeners)
#pragma warning restore 618
{
try
{
BuildTrace(type, msdnTraceCode, description, trace, exception, source, out navigator);
}
catch (PlainXmlWriter.MaxSizeExceededException)
{
StringTraceRecord codeTraceRecord = new StringTraceRecord("TruncatedTraceId", msdnTraceCode);
this.TraceEvent(type, DiagnosticsTraceCode.TraceTruncatedQuotaExceeded, LegacyDiagnosticTrace.GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", "TraceTruncatedQuotaExceeded"), TraceSR.GetString(TraceSR.TraceCodeTraceTruncatedQuotaExceeded), codeTraceRecord, null, null);
}
this.TraceSource.TraceData(type, code, navigator);
if (this.CalledShutdown)
{
this.TraceSource.Flush();
}
// Must have been a successful trace.
this.LastFailure = DateTime.MinValue;
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
LogTraceFailure(navigator == null ? string.Empty : navigator.ToString(), e);
}
}
#pragma warning restore 56500
internal void TraceEvent(TraceEventType type, int code, string msdnTraceCode, string description, TraceRecord trace, Exception exception, Guid activityId, object source)
{
#pragma warning disable 618
using ((this.ShouldUseActivity && Guid.Empty != activityId) ? Activity.CreateActivity(activityId) : null)
#pragma warning restore 618
{
this.TraceEvent(type, code, msdnTraceCode, description, trace, exception, source);
}
}
// helper for standardized trace code generation
static internal string GenerateMsdnTraceCode(string traceSource, string traceCodeString)
{
return string.Format(CultureInfo.InvariantCulture,
"http://msdn.microsoft.com/{0}/library/{1}.{2}.aspx",
CultureInfo.CurrentCulture.Name,
traceSource, traceCodeString);
}
#pragma warning disable 56500
internal void TraceTransfer(Guid newId)
{
#pragma warning disable 618
if (this.ShouldUseActivity)
#pragma warning restore 618
{
Guid oldId = LegacyDiagnosticTrace.ActivityId;
if (newId != oldId)
{
#pragma warning disable 618
if (this.HaveListeners)
#pragma warning restore 618
{
try
{
this.TraceSource.TraceTransfer(0, null, newId);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
LogTraceFailure(null, e);
}
}
}
}
}
protected override void OnShutdownTracing()
{
if (null != this.TraceSource)
{
#pragma warning disable 618
if (this.Level != SourceLevels.Off)
{
if (this.ShouldTrace(TraceEventType.Information))
#pragma warning restore 618
{
Dictionary<string, string> values = new Dictionary<string, string>(3);
values["AppDomain.FriendlyName"] = AppDomain.CurrentDomain.FriendlyName;
values["ProcessName"] = DiagnosticTraceBase.ProcessName;
values["ProcessId"] = DiagnosticTraceBase.ProcessId.ToString(CultureInfo.CurrentCulture);
this.TraceEvent(TraceEventType.Information, DiagnosticsTraceCode.AppDomainUnload, LegacyDiagnosticTrace.GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", "AppDomainUnload"), TraceSR.GetString(TraceSR.TraceCodeAppDomainUnload),
new DictionaryTraceRecord(values), null, null);
}
this.TraceSource.Flush();
}
}
}
protected override void OnUnhandledException(Exception exception)
{
TraceEvent(TraceEventType.Critical, DiagnosticsTraceCode.UnhandledException, "UnhandledException", TraceSR.GetString(TraceSR.UnhandledException), null, exception, null);
}
public bool ShouldLogPii
{
get
{
PiiTraceSource traceSource = this.TraceSource as PiiTraceSource;
if (traceSource != null)
{
return traceSource.ShouldLogPii;
}
return false;
}
set
{
PiiTraceSource traceSource = this.TraceSource as PiiTraceSource;
if (traceSource != null)
{
traceSource.ShouldLogPii = value;
}
}
}
void BuildTrace(TraceEventType type, string msdnTraceCode, string description, TraceRecord trace,
Exception exception, object source, out TraceXPathNavigator navigator)
{
PlainXmlWriter xmlWriter = new PlainXmlWriter(LegacyDiagnosticTrace.MaxTraceSize);
navigator = xmlWriter.Navigator;
this.BuildTrace(xmlWriter, type, msdnTraceCode, description, trace, exception, source);
if (!ShouldLogPii)
{
navigator.RemovePii(DiagnosticStrings.HeadersPaths);
}
}
void BuildTrace(PlainXmlWriter xml, TraceEventType type, string msdnTraceCode, string description,
TraceRecord trace, Exception exception, object source)
{
xml.WriteStartElement(DiagnosticStrings.TraceRecordTag);
xml.WriteAttributeString(DiagnosticStrings.NamespaceTag, LegacyDiagnosticTrace.TraceRecordVersion);
xml.WriteAttributeString(DiagnosticStrings.SeverityTag, DiagnosticTraceBase.LookupSeverity(type));
xml.WriteElementString(DiagnosticStrings.TraceCodeTag, msdnTraceCode);
xml.WriteElementString(DiagnosticStrings.DescriptionTag, description);
xml.WriteElementString(DiagnosticStrings.AppDomain, DiagnosticTraceBase.AppDomainFriendlyName);
if (source != null)
{
xml.WriteElementString(DiagnosticStrings.SourceTag, CreateSourceString(source));
}
if (trace != null)
{
xml.WriteStartElement(DiagnosticStrings.ExtendedDataTag);
xml.WriteAttributeString(DiagnosticStrings.NamespaceTag, trace.EventId);
trace.WriteTo(xml);
xml.WriteEndElement();
}
if (exception != null)
{
xml.WriteStartElement(DiagnosticStrings.ExceptionTag);
AddExceptionToTraceString(xml, exception);
xml.WriteEndElement();
}
xml.WriteEndElement();
}
public override bool IsEnabled()
{
return true;
}
public override void TraceEventLogEvent(TraceEventType type, TraceRecord traceRecord)
{
TraceEvent(type,
DiagnosticsTraceCode.EventLog, LegacyDiagnosticTrace.GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", "EventLog"),
TraceSR.GetString(TraceSR.TraceCodeEventLog),
traceRecord, null, null);
}
}
}

View File

@@ -0,0 +1,58 @@
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
#if !NO_CONFIGURATION
namespace System.ServiceModel.Configuration
{
using System.Configuration;
internal class MachineSettingsSection : ConfigurationSection
{
static bool enableLoggingKnownPii;
static bool hasInitialized = false;
static object syncRoot = new object();
const string enableLoggingKnownPiiKey = "enableLoggingKnownPii";
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty(MachineSettingsSection.enableLoggingKnownPiiKey, typeof(System.Boolean), false, null, null, System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
public static bool EnableLoggingKnownPii
{
get
{
if (!hasInitialized)
{
lock (syncRoot)
{
if (!hasInitialized)
{
MachineSettingsSection machineSettingsSection = (MachineSettingsSection)ConfigurationManager.GetSection("system.serviceModel/machineSettings");
enableLoggingKnownPii = (bool)machineSettingsSection[MachineSettingsSection.enableLoggingKnownPiiKey];
hasInitialized = true;
}
}
}
return enableLoggingKnownPii;
}
}
}
}
#endif

View File

@@ -0,0 +1,22 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
static class NativeMethods
{
const string ADVAPI32 = "advapi32.dll";
[DllImport(ADVAPI32, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
[ResourceExposure(ResourceScope.Machine)]
[Fx.Tag.SecurityNote(Critical = "Returns security critical type SafeEventLogWriteHandle.")]
[SecurityCritical]
internal static extern SafeEventLogWriteHandle RegisterEventSource(string uncServerName, string sourceName);
}
}

View File

@@ -0,0 +1,116 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
#if !NO_CONFIGURATION
using System.Configuration;
#endif
using System.Diagnostics;
using System.Runtime;
using System.Runtime.Diagnostics;
#if !NO_CONFIGURATION
using System.ServiceModel.Configuration;
#endif
class PiiTraceSource : TraceSource
{
string eventSourceName = String.Empty;
internal const string LogPii = "logKnownPii";
bool shouldLogPii = false;
bool initialized = false;
object localSyncObject = new object();
internal PiiTraceSource(string name, string eventSourceName)
: base(name)
{
#pragma warning disable 618
Fx.Assert(!String.IsNullOrEmpty(eventSourceName), "Event log source name must be valid");
#pragma warning restore 618
this.eventSourceName = eventSourceName;
}
internal PiiTraceSource(string name, string eventSourceName, SourceLevels levels)
: base(name, levels)
{
#pragma warning disable 618
Fx.Assert(!String.IsNullOrEmpty(eventSourceName), "Event log source name must be valid");
#pragma warning restore 618
this.eventSourceName = eventSourceName;
}
void Initialize()
{
if (!this.initialized)
{
lock (localSyncObject)
{
if (!this.initialized)
{
string attributeValue = this.Attributes[PiiTraceSource.LogPii];
bool shouldLogPii = false;
if (!string.IsNullOrEmpty(attributeValue))
{
if (!bool.TryParse(attributeValue, out shouldLogPii))
{
shouldLogPii = false;
}
}
if (shouldLogPii)
{
#pragma warning disable 618
System.Runtime.Diagnostics.EventLogger logger = new System.Runtime.Diagnostics.EventLogger(this.eventSourceName, null);
#pragma warning restore 618
#if !NO_CONFIGURATION
if (MachineSettingsSection.EnableLoggingKnownPii)
#else
if (false)
#endif
{
logger.LogEvent(TraceEventType.Information,
(ushort)System.Runtime.Diagnostics.EventLogCategory.MessageLogging,
(uint)System.Runtime.Diagnostics.EventLogEventId.PiiLoggingOn,
false);
this.shouldLogPii = true;
}
else
{
logger.LogEvent(TraceEventType.Error,
(ushort)System.Runtime.Diagnostics.EventLogCategory.MessageLogging,
(uint)System.Runtime.Diagnostics.EventLogEventId.PiiLoggingNotAllowed,
false);
}
}
this.initialized = true;
}
}
}
}
protected override string[] GetSupportedAttributes()
{
return new string[] { PiiTraceSource.LogPii };
}
internal bool ShouldLogPii
{
get
{
// ShouldLogPii is called very frequently, don't call Initialize unless we have to.
if (!this.initialized)
{
Initialize();
}
return this.shouldLogPii;
}
set
{
// If you call this, you know what you're doing
this.initialized = true;
this.shouldLogPii = value;
}
}
}
}

View File

@@ -0,0 +1,220 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Xml;
using System.Runtime;
using System.Diagnostics;
/// <summary>
/// Very basic performance-oriented XmlWriter implementation. No validation/encoding is made.
/// Namespaces are not supported
/// Minimal formatting support
/// </summary>
internal class PlainXmlWriter : XmlWriter
{
internal class MaxSizeExceededException : Exception
{
}
TraceXPathNavigator navigator;
bool writingAttribute = false;
string currentAttributeName;
string currentAttributePrefix;
string currentAttributeNs;
string currentAttributeText = string.Empty;
public PlainXmlWriter()
: this(-1) //no quota
{
}
public PlainXmlWriter(int maxSize)
{
this.navigator = new TraceXPathNavigator(maxSize);
}
public TraceXPathNavigator Navigator
{
get
{
return this.navigator;
}
}
public override void WriteStartDocument() { }
public override void WriteStartDocument(bool standalone) { }
public override void WriteDocType(string name, string pubid, string sysid, string subset) { }
public override void WriteEndDocument() { }
public override string LookupPrefix(string ns)
{
return this.navigator.LookupPrefix(ns);
}
public override WriteState WriteState
{
get { return this.navigator.WriteState; }
}
public override XmlSpace XmlSpace
{
get { return XmlSpace.Default; }
}
public override string XmlLang
{
get { return string.Empty; }
}
public override void WriteValue(object value)
{
this.navigator.AddText(value.ToString());
}
public override void WriteValue(string value)
{
this.navigator.AddText(value);
}
public override void WriteBase64(byte[] buffer, int offset, int count) { }
public override void WriteStartElement(string prefix, string localName, string ns)
{
#pragma warning disable 618
Fx.Assert(!String.IsNullOrEmpty(localName), "");
#pragma warning restore 618
if (String.IsNullOrEmpty(localName))
{
throw new ArgumentNullException("localName");
}
this.navigator.AddElement(prefix, localName, ns);
}
public override void WriteFullEndElement()
{
WriteEndElement();
}
public override void WriteEndElement()
{
this.navigator.CloseElement();
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
#pragma warning disable 618
Fx.Assert(!this.writingAttribute, "");
#pragma warning restore 618
if (this.writingAttribute)
{
throw new InvalidOperationException();
}
this.currentAttributeName = localName;
this.currentAttributePrefix = prefix;
this.currentAttributeNs = ns;
this.currentAttributeText = string.Empty;
this.writingAttribute = true;
}
public override void WriteEndAttribute()
{
#pragma warning disable 618
Fx.Assert(this.writingAttribute, "");
#pragma warning restore 618
if (!this.writingAttribute)
{
throw new InvalidOperationException();
}
this.navigator.AddAttribute(this.currentAttributeName, this.currentAttributeText, this.currentAttributeNs, this.currentAttributePrefix);
this.writingAttribute = false;
}
public override void WriteCData(string text)
{
this.WriteRaw("<![CDATA[" + text + "]]>");
}
public override void WriteComment(string text)
{
this.navigator.AddComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
this.navigator.AddProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name)
{
}
public override void WriteCharEntity(char ch)
{
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
}
public override void WriteWhitespace(string ws)
{
}
public override void WriteString(string text)
{
if (this.writingAttribute)
{
currentAttributeText += text;
}
else
{
this.WriteValue(text);
}
}
public override void WriteChars(Char[] buffer, int index, int count)
{
// Exceptions being thrown as per data found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlxmlwriterclasswritecharstopic.asp
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if ((buffer.Length - index) < count)
{
throw new ArgumentException(TraceSR.GetString(TraceSR.WriteCharsInvalidContent));
}
this.WriteString(new string(buffer, index, count));
}
public override void WriteRaw(String data)
{
this.WriteString(data);
}
public override void WriteRaw(Char[] buffer, int index, int count)
{
this.WriteChars(buffer, index, count);
}
public override void Close()
{
}
public override void Flush()
{
}
}
}

View File

@@ -0,0 +1,53 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Globalization;
using System.Diagnostics;
using System.Security;
using System.Runtime;
[Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
[SecurityCritical]
sealed class SafeEventLogWriteHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// Note: RegisterEventSource returns 0 on failure
[Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
[SecurityCritical]
SafeEventLogWriteHandle() : base(true) { }
[ResourceConsumption(ResourceScope.Machine)]
[Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
[SecurityCritical]
internal static SafeEventLogWriteHandle RegisterEventSource(string uncServerName, string sourceName)
{
SafeEventLogWriteHandle retval = NativeMethods.RegisterEventSource(uncServerName, sourceName);
int error = Marshal.GetLastWin32Error();
if (retval.IsInvalid)
{
Debug.Print("SafeEventLogWriteHandle::RegisterEventSource[" + uncServerName + ", " + sourceName + "] Failed. Last Error: " +
error.ToString(CultureInfo.InvariantCulture));
}
return retval;
}
[DllImport("advapi32", SetLastError = true)]
[ResourceExposure(ResourceScope.None)]
private static extern bool DeregisterEventSource(IntPtr hEventLog);
#pragma warning disable 56523
[Fx.Tag.SecurityNote(Critical = "Usage of SafeHandleZeroOrMinusOneIsInvalid, which is protected by a LinkDemand and InheritanceDemand")]
[SecurityCritical]
override protected bool ReleaseHandle()
{
return DeregisterEventSource(this.handle);
}
#pragma warning restore 56523
}
}

View File

@@ -0,0 +1,12 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
enum TraceSourceKind
{
DiagnosticTraceSource,
PiiTraceSource
}
}

View File

@@ -0,0 +1,77 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
class Utility
{
ExceptionUtility exceptionUtility;
[Obsolete("For SMDiagnostics.dll use only. Call DiagnosticUtility.Utility instead")]
internal Utility(ExceptionUtility exceptionUtility)
{
this.exceptionUtility = exceptionUtility;
}
// Call this when a p/invoke with an 'out SafeHandle' parameter returns an error. This will safely clean up the handle.
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.TransparentMethodsMustNotReferenceCriticalCode)] // we got APTCA approval with no requirement to fix this transparency warning
internal static void CloseInvalidOutSafeHandle(SafeHandle handle)
{
// Workaround for 64-bit CLR bug VSWhidbey 546830 - sometimes invalid SafeHandles come back null.
if (handle != null)
{
#pragma warning disable 618
Fx.Assert(handle.IsInvalid, "CloseInvalidOutSafeHandle called with a valid handle!");
#pragma warning restore 618
// Calls SuppressFinalize.
handle.SetHandleAsInvalid();
}
}
// Copy of the above for CriticalHandles.
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.TransparentMethodsMustNotReferenceCriticalCode)] // we got APTCA approval with no requirement to fix this transparency warning. plus, the callers of this method are not supported in partial trust.
internal static void CloseInvalidOutCriticalHandle(CriticalHandle handle)
{
if (handle != null)
{
#pragma warning disable 618
Fx.Assert(handle.IsInvalid, "CloseInvalidOutCriticalHandle called with a valid handle!");
#pragma warning restore 618
handle.SetHandleAsInvalid();
}
}
internal Guid CreateGuid(string guidString)
{
return Fx.CreateGuid(guidString);
}
internal bool TryCreateGuid(string guidString, out Guid result)
{
return Fx.TryCreateGuid(guidString, out result);
}
internal byte[] AllocateByteArray(int size)
{
return Fx.AllocateByteArray(size);
}
internal char[] AllocateCharArray(int size)
{
return Fx.AllocateCharArray(size);
}
}
}